diff --git a/BUILD.gn b/BUILD.gn index 04dde8d..7eecaedb 100644 --- a/BUILD.gn +++ b/BUILD.gn
@@ -861,13 +861,13 @@ "//content/shell:content_shell", "//content/test:mojo_layouttest_bindings_js_data_deps", "//device/bluetooth/public/interfaces:fake_bluetooth_interfaces_js_data_deps", - "//device/generic_sensor/public/interfaces:interfaces_js_data_deps", "//device/geolocation/public/interfaces:interfaces_js_data_deps", "//device/usb/public/interfaces:interfaces_js_data_deps", "//device/vr:mojo_bindings_js_data_deps", "//media/capture/mojo:image_capture_js_data_deps", "//mojo/public/interfaces/bindings/tests:test_data_deps", "//services/device/public/interfaces:interfaces_js_data_deps", + "//services/device/public/interfaces:generic_sensor_js_data_deps", "//services/service_manager/public/interfaces:interfaces_js_data_deps", "//services/shape_detection/public/interfaces:interfaces_js_data_deps", "//third_party/WebKit/public:blink_devtools_frontend_resources_files",
diff --git a/DEPS b/DEPS index 6728ebe2d..8a24730 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '7aad8cc2ff7a580bd5852d57289ace8c8dced6f5', + 'skia_revision': '0933f339964a3bf2d878db51ac4c6119a5046c8b', # 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': 'ddebefb50ab52b968fed0f9957c419e7acd2326f', + 'v8_revision': '63ba7b3883d7f2973f5c602f0d813f0a6347c1f6', # 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. @@ -60,11 +60,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '81aa97bd20033674ba28d779c05fbcee1539ebf7', + 'swiftshader_revision': '83a6bb93fd825b975161546ff92d6fb77a7a9c22', # 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': 'd7403971a25c317671e92ccc676a5f600ed223eb', + 'pdfium_revision': 'b137e75343cada31ddcf905fc581a3a86a63b5d5', # 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. @@ -92,11 +92,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. - 'freetype_revision': '7819aeb622a94be0d89caf8382f290d0266c4aed', + 'freetype_revision': 'c56d8851ea987023cc73981a70d261b3f6427545', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '34ef95cb09ce13d370163e36179981f566356c68', + 'catapult_revision': '5d065952a0d8060166cecc73093775bf518966f7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -235,7 +235,7 @@ Var('chromium_git') + '/native_client/src/third_party/scons-2.0.1.git' + '@' + '1c1550e17fc26355d08627fbdec13d8291227067', 'src/third_party/webrtc': - Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'eb8eec46f7c57ab1bc38111c70ae08eb16b8793d', # commit position 18901 + Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + '74848bb39b933921ca73a3ac9a0ef897b86aed94', # commit position 18908 'src/third_party/openmax_dl': Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' + Var('openmax_dl_revision'),
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index c5b5d16e..440d69e 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -99,6 +99,12 @@ ] } +java_cpp_enum("aw_safe_browsing_action") { + sources = [ + "browser/aw_safe_browsing_resource_throttle.h", + ] +} + jinja_template("system_webview_manifest") { input = "apk/java/AndroidManifest.xml" output = system_webview_android_manifest @@ -796,10 +802,12 @@ "java/src/org/chromium/android_webview/AwPicture.java", "java/src/org/chromium/android_webview/AwPrintDocumentAdapter.java", "java/src/org/chromium/android_webview/AwSafeBrowsingConfigHelper.java", + "java/src/org/chromium/android_webview/AwSafeBrowsingResponse.java", "java/src/org/chromium/android_webview/AwQuotaManagerBridge.java", "java/src/org/chromium/android_webview/AwRendererPriorityManager.java", "java/src/org/chromium/android_webview/AwRenderProcessGoneDetail.java", "java/src/org/chromium/android_webview/AwResource.java", + "java/src/org/chromium/android_webview/AwSafeBrowsingConversionHelper.java", "java/src/org/chromium/android_webview/AwScrollOffsetManager.java", "java/src/org/chromium/android_webview/AwServiceWorkerClient.java", "java/src/org/chromium/android_webview/AwServiceWorkerController.java", @@ -867,6 +875,8 @@ ":aw_permission_request_resource", ":aw_renderer_priority_manager_renderer_priority", ":aw_error_ui", + ":aw_safe_browsing_action", + "//components/safe_browsing_db:sb_threat_values", ] }
diff --git a/android_webview/browser/aw_autofill_client.cc b/android_webview/browser/aw_autofill_client.cc index 071975e..8920c51 100644 --- a/android_webview/browser/aw_autofill_client.cc +++ b/android_webview/browser/aw_autofill_client.cc
@@ -20,7 +20,6 @@ #include "components/prefs/pref_service.h" #include "components/prefs/pref_service_factory.h" #include "components/user_prefs/user_prefs.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/ssl_status.h" #include "content/public/browser/web_contents.h"
diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc index 1cd3605..be0ed2e 100644 --- a/android_webview/browser/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -57,12 +57,12 @@ #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/navigation_interception/intercept_navigation_delegate.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/android/synchronous_compositor.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/browsing_data_remover.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/favicon_status.h" +#include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_frame_host.h" @@ -74,6 +74,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/mhtml_generation_params.h" #include "content/public/common/renderer_preferences.h" +#include "gpu/config/gpu_info.h" #include "jni/AwContents_jni.h" #include "net/base/auth.h" #include "net/cert/x509_certificate.h" @@ -97,7 +98,6 @@ using base::android::ScopedJavaLocalRef; using navigation_interception::InterceptNavigationDelegate; using content::BrowserThread; -using content::ContentViewCore; using content::RenderFrameHost; using content::WebContents; @@ -107,8 +107,6 @@ bool g_should_download_favicons = false; -bool g_force_auxiliary_bitmap_rendering = false; - std::string g_locale; std::string g_locale_list; @@ -412,11 +410,11 @@ return reinterpret_cast<intptr_t>(new AwContents(std::move(web_contents))); } -static void SetForceAuxiliaryBitmapRendering( - JNIEnv* env, - const JavaParamRef<jclass>&, - jboolean force_auxiliary_bitmap_rendering) { - g_force_auxiliary_bitmap_rendering = force_auxiliary_bitmap_rendering; +static jboolean HasRequiredHardwareExtensions(JNIEnv* env, + const JavaParamRef<jclass>&) { + return content::GpuDataManager::GetInstance() + ->GetGPUInfo() + .can_support_threaded_texture_mailbox; } static void SetAwDrawSWFunctionTable(JNIEnv* env, @@ -991,14 +989,15 @@ jint visible_left, jint visible_top, jint visible_right, - jint visible_bottom) { + jint visible_bottom, + jboolean force_auxiliary_bitmap_rendering) { DCHECK_CURRENTLY_ON(BrowserThread::UI); gfx::Vector2d scroll(scroll_x, scroll_y); browser_view_renderer_.PrepareToDraw( scroll, gfx::Rect(visible_left, visible_top, visible_right - visible_left, visible_bottom - visible_top)); if (is_hardware_accelerated && browser_view_renderer_.attached_to_window() && - !g_force_auxiliary_bitmap_rendering) { + !force_auxiliary_bitmap_rendering) { return browser_view_renderer_.OnDrawHardware(); } @@ -1016,7 +1015,7 @@ // viewspace. Use the resulting rect as the auxiliary bitmap. std::unique_ptr<SoftwareCanvasHolder> canvas_holder = SoftwareCanvasHolder::Create(canvas, scroll, view_size, - g_force_auxiliary_bitmap_rendering); + force_auxiliary_bitmap_rendering); if (!canvas_holder || !canvas_holder->GetCanvas()) { TRACE_EVENT_INSTANT0("android_webview", "EarlyOut_NoSoftwareCanvas", TRACE_EVENT_SCOPE_THREAD);
diff --git a/android_webview/browser/aw_contents.h b/android_webview/browser/aw_contents.h index 7084b18..7d3ea1f72 100644 --- a/android_webview/browser/aw_contents.h +++ b/android_webview/browser/aw_contents.h
@@ -194,7 +194,8 @@ jint visible_left, jint visible_top, jint visible_right, - jint visible_bottom); + jint visible_bottom, + jboolean force_auxiliary_bitmap_rendering); jlong CapturePicture(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, int width,
diff --git a/android_webview/browser/aw_contents_client_bridge.cc b/android_webview/browser/aw_contents_client_bridge.cc index c3340d0..30013e7 100644 --- a/android_webview/browser/aw_contents_client_bridge.cc +++ b/android_webview/browser/aw_contents_client_bridge.cc
@@ -7,7 +7,6 @@ #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 "base/android/jni_android.h" @@ -451,6 +450,29 @@ safebrowsing_hit); } +void AwContentsClientBridge::OnSafeBrowsingHit( + const AwWebResourceRequest& request, + const safe_browsing::SBThreatType& threat_type, + const SafeBrowsingActionCallback& callback) { + int request_id = safe_browsing_callbacks_.Add( + base::MakeUnique<SafeBrowsingActionCallback>(callback)); + + DCHECK_CURRENTLY_ON(BrowserThread::UI); + JNIEnv* env = AttachCurrentThread(); + ScopedJavaLocalRef<jobject> obj = java_ref_.get(env); + if (obj.is_null()) + return; + + AwWebResourceRequest::AwJavaWebResourceRequest java_web_resource_request; + AwWebResourceRequest::ConvertToJava(env, request, &java_web_resource_request); + Java_AwContentsClientBridge_onSafeBrowsingHit( + env, obj, java_web_resource_request.jurl, request.is_main_frame, + request.has_user_gesture, java_web_resource_request.jmethod, + java_web_resource_request.jheader_names, + java_web_resource_request.jheader_values, static_cast<int>(threat_type), + request_id); +} + void AwContentsClientBridge::OnReceivedHttpError( const AwWebResourceRequest& request, const scoped_refptr<const net::HttpResponseHeaders>& response_headers) { @@ -518,6 +540,23 @@ pending_js_dialog_callbacks_.Remove(id); } +void AwContentsClientBridge::TakeSafeBrowsingAction(JNIEnv*, + const JavaRef<jobject>&, + int action, + bool reporting, + int request_id) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + auto* callback = safe_browsing_callbacks_.Lookup(request_id); + if (!callback) { + LOG(WARNING) << "Unexpected TakeSafeBrowsingAction. " << request_id; + return; + } + callback->Run( + static_cast<AwSafeBrowsingResourceThrottle::SafeBrowsingAction>(action), + reporting); + safe_browsing_callbacks_.Remove(request_id); +} + void AwContentsClientBridge::CancelJsResult(JNIEnv*, const JavaRef<jobject>&, int id) {
diff --git a/android_webview/browser/aw_contents_client_bridge.h b/android_webview/browser/aw_contents_client_bridge.h index 48fde9e..d96f659 100644 --- a/android_webview/browser/aw_contents_client_bridge.h +++ b/android_webview/browser/aw_contents_client_bridge.h
@@ -8,12 +8,14 @@ #include <jni.h> #include <memory> +#include "android_webview/browser/aw_safe_browsing_resource_throttle.h" #include "android_webview/browser/net/aw_web_resource_request.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/callback.h" #include "base/id_map.h" #include "base/supports_user_data.h" +#include "components/security_interstitials/content/unsafe_resource.h" #include "content/public/browser/certificate_request_result_type.h" #include "content/public/browser/javascript_dialog_manager.h" #include "content/public/browser/resource_request_info.h" @@ -99,6 +101,12 @@ int error_code, bool safebrowsing_hit); + void OnSafeBrowsingHit(const AwWebResourceRequest& request, + const safe_browsing::SBThreatType& threat_type, + const base::Callback<void( + AwSafeBrowsingResourceThrottle::SafeBrowsingAction, + bool)>& callback); + // Called when a response from the server is received with status code >= 400. void OnReceivedHttpError( const AwWebResourceRequest& request, @@ -121,12 +129,22 @@ const base::android::JavaRef<jstring>& prompt); void CancelJsResult(JNIEnv*, const base::android::JavaRef<jobject>&, int id); + void TakeSafeBrowsingAction(JNIEnv*, + const base::android::JavaRef<jobject>&, + int action, + bool reporting, + int request_id); + private: JavaObjectWeakGlobalRef java_ref_; typedef const base::Callback<void(content::CertificateRequestResultType)> CertErrorCallback; + typedef const base::Callback< + void(AwSafeBrowsingResourceThrottle::SafeBrowsingAction, bool)> + SafeBrowsingActionCallback; IDMap<std::unique_ptr<CertErrorCallback>> pending_cert_error_callbacks_; + IDMap<std::unique_ptr<SafeBrowsingActionCallback>> safe_browsing_callbacks_; IDMap<std::unique_ptr<content::JavaScriptDialogManager::DialogClosedCallback>> pending_js_dialog_callbacks_; IDMap<std::unique_ptr<content::ClientCertificateDelegate>>
diff --git a/android_webview/browser/aw_safe_browsing_blocking_page.cc b/android_webview/browser/aw_safe_browsing_blocking_page.cc index 62e858e..64ef66d6 100644 --- a/android_webview/browser/aw_safe_browsing_blocking_page.cc +++ b/android_webview/browser/aw_safe_browsing_blocking_page.cc
@@ -70,7 +70,8 @@ // static void AwSafeBrowsingBlockingPage::ShowBlockingPage( AwSafeBrowsingUIManager* ui_manager, - const UnsafeResource& unsafe_resource) { + const UnsafeResource& unsafe_resource, + bool extended_reporting_allowed) { DVLOG(1) << __func__ << " " << unsafe_resource.url.spec(); WebContents* web_contents = unsafe_resource.web_contents_getter.Run(); @@ -88,13 +89,12 @@ const UnsafeResourceList unsafe_resources{unsafe_resource}; BaseSafeBrowsingErrorUI::SBErrorDisplayOptions display_options = BaseSafeBrowsingErrorUI::SBErrorDisplayOptions( - IsMainPageLoadBlocked(unsafe_resources), - false, // kSafeBrowsingExtendedReportingOptInAllowed - false, // is_off_the_record - false, // is_extended_reporting - false, // is_scout - false, // kSafeBrowsingProceedAnywayDisabled - false, // should_open_links_in_new_tab + IsMainPageLoadBlocked(unsafe_resources), extended_reporting_allowed, + false, // is_off_the_record + false, // is_extended_reporting + false, // is_scout + false, // kSafeBrowsingProceedAnywayDisabled + false, // should_open_links_in_new_tab "cpn_safe_browsing_wv"); // help_center_article_link ErrorUiType errorType =
diff --git a/android_webview/browser/aw_safe_browsing_blocking_page.h b/android_webview/browser/aw_safe_browsing_blocking_page.h index 0569f866..9084d1a 100644 --- a/android_webview/browser/aw_safe_browsing_blocking_page.h +++ b/android_webview/browser/aw_safe_browsing_blocking_page.h
@@ -21,7 +21,8 @@ typedef security_interstitials::UnsafeResource UnsafeResource; static void ShowBlockingPage(AwSafeBrowsingUIManager* ui_manager, - const UnsafeResource& unsafe_resource); + const UnsafeResource& unsafe_resource, + bool extended_reporting_allowed); protected: // Used to specify which BaseSafeBrowsingErrorUI to instantiate, and
diff --git a/android_webview/browser/aw_safe_browsing_resource_throttle.cc b/android_webview/browser/aw_safe_browsing_resource_throttle.cc index a43fe85..4a30851 100644 --- a/android_webview/browser/aw_safe_browsing_resource_throttle.cc +++ b/android_webview/browser/aw_safe_browsing_resource_throttle.cc
@@ -4,12 +4,15 @@ #include "android_webview/browser/aw_safe_browsing_resource_throttle.h" +#include "android_webview/browser/aw_contents_client_bridge.h" #include "android_webview/browser/aw_safe_browsing_ui_manager.h" #include "base/macros.h" #include "components/safe_browsing/base_resource_throttle.h" #include "components/safe_browsing_db/database_manager.h" #include "components/safe_browsing_db/v4_protocol_manager_util.h" #include "components/security_interstitials/content/unsafe_resource.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_entry.h" #include "content/public/common/resource_type.h" #include "net/base/net_errors.h" #include "net/url_request/url_request.h" @@ -50,6 +53,80 @@ AwSafeBrowsingResourceThrottle::~AwSafeBrowsingResourceThrottle() {} +void AwSafeBrowsingResourceThrottle::StartDisplayingBlockingPageHelper( + security_interstitials::UnsafeResource resource) { + content::BrowserThread::PostTask( + content::BrowserThread::UI, FROM_HERE, + base::Bind(&AwSafeBrowsingResourceThrottle::StartApplicationResponse, + AsWeakPtr(), ui_manager(), resource, + AwWebResourceRequest(*request_))); +} + +// static +void AwSafeBrowsingResourceThrottle::StartApplicationResponse( + const base::WeakPtr<BaseResourceThrottle>& throttle, + scoped_refptr<safe_browsing::BaseUIManager> ui_manager, + const security_interstitials::UnsafeResource& resource, + const AwWebResourceRequest& request) { + content::WebContents* web_contents = resource.web_contents_getter.Run(); + AwContentsClientBridge* client = + AwContentsClientBridge::FromWebContents(web_contents); + + if (client) { + base::Callback<void(SafeBrowsingAction, bool)> callback = + base::Bind(&AwSafeBrowsingResourceThrottle::DoApplicationResponse, + throttle, ui_manager, resource); + + client->OnSafeBrowsingHit(request, resource.threat_type, callback); + } +} + +// static +void AwSafeBrowsingResourceThrottle::DoApplicationResponse( + const base::WeakPtr<BaseResourceThrottle>& throttle, + scoped_refptr<safe_browsing::BaseUIManager> ui_manager, + const security_interstitials::UnsafeResource& resource, + SafeBrowsingAction action, + bool reporting) { + if (!reporting) { + AwSafeBrowsingUIManager* casted_ui_manager = + static_cast<AwSafeBrowsingUIManager*>(ui_manager.get()); + casted_ui_manager->set_extended_reporting_allowed(false); + } + // TODO(ntfschr): fully handle reporting once we add support (crbug/688629) + bool proceed; + switch (action) { + case SafeBrowsingAction::SHOW_INTERSTITIAL: + content::BrowserThread::PostTask( + content::BrowserThread::UI, FROM_HERE, + base::Bind(&BaseResourceThrottle::StartDisplayingBlockingPage, + throttle, ui_manager, resource)); + return; + case SafeBrowsingAction::PROCEED: + proceed = true; + break; + case SafeBrowsingAction::BACK_TO_SAFETY: + proceed = false; + break; + default: + NOTREACHED(); + } + + content::WebContents* web_contents = resource.web_contents_getter.Run(); + content::NavigationEntry* entry = resource.GetNavigationEntryForResource(); + GURL main_frame_url = entry ? entry->GetURL() : GURL(); + + // Navigate back for back-to-safety on subresources + if (!proceed && resource.is_subframe) { + DCHECK(web_contents->GetController().CanGoBack()); + web_contents->GetController().GoBack(); + } + + ui_manager->OnBlockingPageDone( + std::vector<security_interstitials::UnsafeResource>{resource}, proceed, + web_contents, main_frame_url); +} + void AwSafeBrowsingResourceThrottle::CancelResourceLoad() { request_->SetUserData(kUserDataKey, base::MakeUnique<base::SupportsUserData::Data>());
diff --git a/android_webview/browser/aw_safe_browsing_resource_throttle.h b/android_webview/browser/aw_safe_browsing_resource_throttle.h index 65a17e6..ed3bceb 100644 --- a/android_webview/browser/aw_safe_browsing_resource_throttle.h +++ b/android_webview/browser/aw_safe_browsing_resource_throttle.h
@@ -6,6 +6,7 @@ #define ANDROID_WEBVIEW_BROWSER_AW_SAFE_BROWSING_RESOURCE_THROTTLE_H_ #include "android_webview/browser/aw_safe_browsing_ui_manager.h" +#include "android_webview/browser/net/aw_web_resource_request.h" #include "base/macros.h" #include "components/safe_browsing/base_resource_throttle.h" #include "components/safe_browsing_db/database_manager.h" @@ -24,6 +25,13 @@ class AwSafeBrowsingResourceThrottle : public safe_browsing::BaseResourceThrottle { public: + // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.android_webview + enum class SafeBrowsingAction { + SHOW_INTERSTITIAL, + PROCEED, + BACK_TO_SAFETY, + }; + // Will construct an AwSafeBrowsingResourceThrottle if GMS exists on device // and supports safebrowsing. static AwSafeBrowsingResourceThrottle* MaybeCreate( @@ -45,6 +53,26 @@ ~AwSafeBrowsingResourceThrottle() override; + void StartDisplayingBlockingPageHelper( + security_interstitials::UnsafeResource resource) override; + + static void StartApplicationResponse( + const base::WeakPtr<BaseResourceThrottle>& throttle, + scoped_refptr<safe_browsing::BaseUIManager> ui_manager, + const security_interstitials::UnsafeResource& resource, + const AwWebResourceRequest& request); + + // Follow the application's response to WebViewClient#onSafeBrowsingHit(). If + // the action is PROCEED or BACK_TO_SAFETY, then |reporting| will determine if + // we should send an extended report. Otherwise, |reporting| determines if we + // should allow showing the reporting checkbox or not. + static void DoApplicationResponse( + const base::WeakPtr<BaseResourceThrottle>& throttle, + scoped_refptr<safe_browsing::BaseUIManager> ui_manager, + const security_interstitials::UnsafeResource& resource, + SafeBrowsingAction action, + bool reporting); + void CancelResourceLoad() override; net::URLRequest* request_;
diff --git a/android_webview/browser/aw_safe_browsing_ui_manager.cc b/android_webview/browser/aw_safe_browsing_ui_manager.cc index 0dc54b9..5346c56 100644 --- a/android_webview/browser/aw_safe_browsing_ui_manager.cc +++ b/android_webview/browser/aw_safe_browsing_ui_manager.cc
@@ -65,7 +65,8 @@ void AwSafeBrowsingUIManager::ShowBlockingPageForResource( const UnsafeResource& resource) { - AwSafeBrowsingBlockingPage::ShowBlockingPage(this, resource); + AwSafeBrowsingBlockingPage::ShowBlockingPage(this, resource, + extended_reporting_allowed_); } int AwSafeBrowsingUIManager::GetErrorUiType(
diff --git a/android_webview/browser/aw_safe_browsing_ui_manager.h b/android_webview/browser/aw_safe_browsing_ui_manager.h index 263f89a5..688ea3b 100644 --- a/android_webview/browser/aw_safe_browsing_ui_manager.h +++ b/android_webview/browser/aw_safe_browsing_ui_manager.h
@@ -47,6 +47,10 @@ // protocol buffer, so the service can send it over. void SendSerializedThreatDetails(const std::string& serialized) override; + void set_extended_reporting_allowed(bool allowed) { + extended_reporting_allowed_ = allowed; + } + protected: ~AwSafeBrowsingUIManager() override; @@ -61,6 +65,8 @@ scoped_refptr<safe_browsing::SafeBrowsingURLRequestContextGetter> url_request_context_getter_; + bool extended_reporting_allowed_ = false; + DISALLOW_COPY_AND_ASSIGN(AwSafeBrowsingUIManager); };
diff --git a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc index 5df224c..4efdd75 100644 --- a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc +++ b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc
@@ -11,7 +11,6 @@ #include "base/command_line.h" #include "base/logging.h" #include "components/web_restrictions/browser/web_restrictions_mojo_implementation.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h"
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java index 2a3931f..286bc70b 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewContentsClientAdapter.java
@@ -44,9 +44,11 @@ import org.chromium.android_webview.AwContentsClientBridge; import org.chromium.android_webview.AwHttpAuthHandler; import org.chromium.android_webview.AwRenderProcessGoneDetail; +import org.chromium.android_webview.AwSafeBrowsingResponse; import org.chromium.android_webview.AwWebResourceResponse; import org.chromium.android_webview.JsPromptResultReceiver; import org.chromium.android_webview.JsResultReceiver; +import org.chromium.android_webview.SafeBrowsingAction; import org.chromium.android_webview.permission.AwPermissionRequest; import org.chromium.android_webview.permission.Resource; import org.chromium.base.Log; @@ -631,6 +633,14 @@ } @Override + public void onSafeBrowsingHit(AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback) { + // TODO(ntfschr): invoke the WebViewClient method once the next SDK rolls + callback.onReceiveValue(new AwSafeBrowsingResponse(SafeBrowsingAction.SHOW_INTERSTITIAL, + /* reporting */ true)); + } + + @Override public void onReceivedHttpError(AwWebResourceRequest request, AwWebResourceResponse response) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return; try {
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index b6b311df..4cf7eba4 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -118,11 +118,16 @@ // produce little visible difference. private static final float ZOOM_CONTROLS_EPSILON = 0.007f; - private static final boolean FORCE_AUXILIARY_BITMAP_RENDERING = - "goldfish".equals(Build.HARDWARE) || "ranchu".equals(Build.HARDWARE); - private static final double MIN_SCREEN_HEIGHT_PERCENTAGE_FOR_INTERSTITIAL = 0.7; + private static class ForceAuxiliaryBitmapRendering { + private static final boolean sResult = lazyCheck(); + private static boolean lazyCheck() { + return "goldfish".equals(Build.HARDWARE) || "ranchu".equals(Build.HARDWARE) + || !nativeHasRequiredHardwareExtensions(); + } + } + /** * WebKit hit test related data structure. These are used to implement * getHitTestResult, requestFocusNodeHref, requestImageRef methods in WebView. @@ -1319,8 +1324,6 @@ public static void setAwDrawSWFunctionTable(long functionTablePointer) { nativeSetAwDrawSWFunctionTable(functionTablePointer); - // Force auxiliary bitmap rendering in emulators. - nativeSetForceAuxiliaryBitmapRendering(FORCE_AUXILIARY_BITMAP_RENDERING); } public static void setAwDrawGLFunctionTable(long functionTablePointer) { @@ -3172,8 +3175,10 @@ } boolean did_draw = nativeOnDraw(mNativeAwContents, canvas, canvas.isHardwareAccelerated(), scrollX, scrollY, globalVisibleRect.left, - globalVisibleRect.top, globalVisibleRect.right, globalVisibleRect.bottom); - if (did_draw && canvas.isHardwareAccelerated() && !FORCE_AUXILIARY_BITMAP_RENDERING) { + globalVisibleRect.top, globalVisibleRect.right, globalVisibleRect.bottom, + ForceAuxiliaryBitmapRendering.sResult); + if (did_draw && canvas.isHardwareAccelerated() + && !ForceAuxiliaryBitmapRendering.sResult) { did_draw = mCurrentFunctor.requestDrawGL(canvas); } if (did_draw) { @@ -3488,8 +3493,7 @@ private static native long nativeInit(AwBrowserContext browserContext); private static native void nativeDestroy(long nativeAwContents); - private static native void nativeSetForceAuxiliaryBitmapRendering( - boolean forceAuxiliaryBitmapRendering); + private static native boolean nativeHasRequiredHardwareExtensions(); private static native void nativeSetAwDrawSWFunctionTable(long functionTablePointer); private static native void nativeSetAwDrawGLFunctionTable(long functionTablePointer); private static native int nativeGetNativeInstanceCount(); @@ -3515,8 +3519,9 @@ private native void nativeOnComputeScroll( long nativeAwContents, long currentAnimationTimeMillis); private native boolean nativeOnDraw(long nativeAwContents, Canvas canvas, - boolean isHardwareAccelerated, int scrollX, int scrollY, - int visibleLeft, int visibleTop, int visibleRight, int visibleBottom); + boolean isHardwareAccelerated, int scrollX, int scrollY, int visibleLeft, + int visibleTop, int visibleRight, int visibleBottom, + boolean forceAuxiliaryBitmapRendering); private native void nativeFindAllAsync(long nativeAwContents, String searchString); private native void nativeFindNext(long nativeAwContents, boolean forward); private native void nativeClearMatches(long nativeAwContents);
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java b/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java index 972f53d3..fc508d0f5a 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java
@@ -369,6 +369,9 @@ protected abstract void onReceivedError2( AwWebResourceRequest request, AwWebResourceError error); + protected abstract void onSafeBrowsingHit(AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback); + public abstract void onReceivedHttpError(AwWebResourceRequest request, AwWebResourceResponse response);
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContentsClientBridge.java b/android_webview/java/src/org/chromium/android_webview/AwContentsClientBridge.java index 8d341ba..ea82a15 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContentsClientBridge.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContentsClientBridge.java
@@ -361,6 +361,40 @@ } @CalledByNative + public void onSafeBrowsingHit( + // WebResourceRequest + String url, boolean isMainFrame, boolean hasUserGesture, String method, + String[] requestHeaderNames, String[] requestHeaderValues, int threatType, + final int requestId) { + AwContentsClient.AwWebResourceRequest request = new AwContentsClient.AwWebResourceRequest(); + request.url = url; + request.isMainFrame = isMainFrame; + request.hasUserGesture = hasUserGesture; + request.method = method; + request.requestHeaders = new HashMap<String, String>(requestHeaderNames.length); + for (int i = 0; i < requestHeaderNames.length; ++i) { + request.requestHeaders.put(requestHeaderNames[i], requestHeaderValues[i]); + } + + ValueCallback<AwSafeBrowsingResponse> callback = + new ValueCallback<AwSafeBrowsingResponse>() { + @Override + public void onReceiveValue(final AwSafeBrowsingResponse response) { + ThreadUtils.runOnUiThread(new Runnable() { + @Override + public void run() { + nativeTakeSafeBrowsingAction(mNativeContentsClientBridge, + response.action(), response.reporting(), requestId); + } + }); + } + }; + + mClient.getCallbackHelper().postOnSafeBrowsingHit( + request, AwSafeBrowsingConversionHelper.convertThreatType(threatType), callback); + } + + @CalledByNative private void onReceivedHttpError( // WebResourceRequest String url, boolean isMainFrame, boolean hasUserGesture, String method, @@ -417,6 +451,8 @@ //-------------------------------------------------------------------------------------------- // Native methods //-------------------------------------------------------------------------------------------- + private native void nativeTakeSafeBrowsingAction( + long nativeAwContentsClientBridge, int action, boolean reporting, int requestId); private native void nativeProceedSslError(long nativeAwContentsClientBridge, boolean proceed, int id); private native void nativeProvideClientCertificateResponse(long nativeAwContentsClientBridge,
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContentsClientCallbackHelper.java b/android_webview/java/src/org/chromium/android_webview/AwContentsClientCallbackHelper.java index 7d5586fc..a10a936 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContentsClientCallbackHelper.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContentsClientCallbackHelper.java
@@ -9,6 +9,7 @@ import android.os.Looper; import android.os.Message; import android.os.SystemClock; +import android.webkit.ValueCallback; import org.chromium.base.VisibleForTesting; @@ -75,6 +76,19 @@ } } + private static class OnSafeBrowsingHitInfo { + final AwContentsClient.AwWebResourceRequest mRequest; + final int mThreatType; + final ValueCallback<AwSafeBrowsingResponse> mCallback; + + OnSafeBrowsingHitInfo(AwContentsClient.AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback) { + mRequest = request; + mThreatType = threatType; + mCallback = callback; + } + } + private static class OnReceivedHttpErrorInfo { final AwContentsClient.AwWebResourceRequest mRequest; final AwWebResourceResponse mResponse; @@ -120,6 +134,7 @@ private static final int MSG_SYNTHESIZE_PAGE_LOADING = 12; private static final int MSG_DO_UPDATE_VISITED_HISTORY = 13; private static final int MSG_ON_FORM_RESUBMISSION = 14; + private static final int MSG_ON_SAFE_BROWSING_HIT = 15; // Minimum period allowed between consecutive onNewPicture calls, to rate-limit the callbacks. private static final long ON_NEW_PICTURE_MIN_PERIOD_MILLIS = 500; @@ -173,6 +188,12 @@ mContentsClient.onReceivedError(info.mRequest, info.mError); break; } + case MSG_ON_SAFE_BROWSING_HIT: { + OnSafeBrowsingHitInfo info = (OnSafeBrowsingHitInfo) msg.obj; + mContentsClient.onSafeBrowsingHit( + info.mRequest, info.mThreatType, info.mCallback); + break; + } case MSG_ON_NEW_PICTURE: { Picture picture = null; try { @@ -271,6 +292,12 @@ mHandler.sendMessage(mHandler.obtainMessage(MSG_ON_RECEIVED_ERROR, info)); } + public void postOnSafeBrowsingHit(AwContentsClient.AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback) { + OnSafeBrowsingHitInfo info = new OnSafeBrowsingHitInfo(request, threatType, callback); + mHandler.sendMessage(mHandler.obtainMessage(MSG_ON_SAFE_BROWSING_HIT, info)); + } + public void postOnNewPicture(Callable<Picture> pictureProvider) { if (mHasPendingOnNewPicture) return; mHasPendingOnNewPicture = true;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConversionHelper.java b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConversionHelper.java new file mode 100644 index 0000000..3c061cb --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConversionHelper.java
@@ -0,0 +1,42 @@ +// Copyright 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. + +package org.chromium.android_webview; + +import org.chromium.components.safe_browsing.SBThreatType; + +/** + * This is a helper class to map native SafeBrowsingActions and SAFE_BROWSING_THREATs to the + * constants in WebViewClient. + */ +public final class AwSafeBrowsingConversionHelper { + // TODO(ntfschr): set these values from WebViewClient after next SDK rolls + /** The resource was blocked for an unknown reason */ + public static final int SAFE_BROWSING_THREAT_UNKNOWN = 0; + /** The resource was blocked because it contains malware */ + public static final int SAFE_BROWSING_THREAT_MALWARE = 1; + /** The resource was blocked because it contains deceptive content */ + public static final int SAFE_BROWSING_THREAT_PHISHING = 2; + /** The resource was blocked because it contains unwanted software */ + public static final int SAFE_BROWSING_THREAT_UNWANTED_SOFTWARE = 3; + + /** + * Converts the threat type value from SafeBrowsing code to the WebViewClient constant. + */ + public static int convertThreatType(int chromiumThreatType) { + switch (chromiumThreatType) { + case SBThreatType.URL_MALWARE: + return SAFE_BROWSING_THREAT_MALWARE; + case SBThreatType.URL_PHISHING: + return SAFE_BROWSING_THREAT_PHISHING; + case SBThreatType.URL_UNWANTED: + return SAFE_BROWSING_THREAT_UNWANTED_SOFTWARE; + default: + return SAFE_BROWSING_THREAT_UNKNOWN; + } + } + + // Do not instantiate this class. + private AwSafeBrowsingConversionHelper() {} +}
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingResponse.java b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingResponse.java new file mode 100644 index 0000000..abd130e --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingResponse.java
@@ -0,0 +1,25 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.android_webview; + +/** + * Container to hold the application's response to WebViewClient#onSafeBrowsingHit(). + */ +public class AwSafeBrowsingResponse { + private int mAction; + private boolean mReporting; + + public AwSafeBrowsingResponse(int action, boolean reporting) { + mAction = action; + mReporting = reporting; + } + + public int action() { + return mAction; + } + public boolean reporting() { + return mReporting; + } +}
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/SafeBrowsingTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/SafeBrowsingTest.java index 78598bf..9721eda 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/SafeBrowsingTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/SafeBrowsingTest.java
@@ -18,10 +18,14 @@ import org.chromium.android_webview.AwContents.InternalAccessDelegate; import org.chromium.android_webview.AwContents.NativeDrawGLFunctorFactory; import org.chromium.android_webview.AwContentsClient; +import org.chromium.android_webview.AwContentsClient.AwWebResourceRequest; +import org.chromium.android_webview.AwSafeBrowsingConversionHelper; +import org.chromium.android_webview.AwSafeBrowsingResponse; import org.chromium.android_webview.AwSettings; import org.chromium.android_webview.AwSwitches; import org.chromium.android_webview.AwWebContentsObserver; import org.chromium.android_webview.ErrorCodeConversionHelper; +import org.chromium.android_webview.SafeBrowsingAction; import org.chromium.android_webview.test.TestAwContentsClient.OnReceivedError2Helper; import org.chromium.android_webview.test.util.GraphicsTestUtils; import org.chromium.base.ThreadUtils; @@ -38,6 +42,7 @@ import org.chromium.net.test.EmbeddedTestServer; import java.util.Arrays; +import java.util.concurrent.Callable; /** * Test suite for SafeBrowsing. @@ -45,7 +50,7 @@ * Ensures that interstitials can be successfully created for malicous pages. */ public class SafeBrowsingTest extends AwTestBase { - private TestAwContentsClient mContentsClient; + private SafeBrowsingContentsClient mContentsClient; private AwTestContainerView mContainerView; private MockAwContents mAwContents; private TestAwWebContentsObserver mWebContentsObserver; @@ -105,7 +110,8 @@ final String metadata; Arrays.sort(threatsOfInterest); - // TODO(ntfschr): remove this assert once we support UwS warnings (crbug/729272) + // TODO(ntfschr): remove this assert once we support Unwanted Software warnings + // (crbug/729272) assertEquals(Arrays.binarySearch(threatsOfInterest, UNWANTED_SOFTWARE_CODE), -1); if (uri.endsWith(PHISHING_HTML_PATH) @@ -194,6 +200,40 @@ } } + /** + * An AwContentsClient with customizable behavior for onSafeBrowsingHit(). + */ + private static class SafeBrowsingContentsClient extends TestAwContentsClient { + private AwWebResourceRequest mLastRequest; + private int mLastThreatType; + private int mAction = SafeBrowsingAction.SHOW_INTERSTITIAL; + private boolean mReporting = true; + + @Override + public void onSafeBrowsingHit(AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback) { + mLastRequest = request; + mLastThreatType = threatType; + callback.onReceiveValue(new AwSafeBrowsingResponse(mAction, mReporting)); + } + + public AwWebResourceRequest getLastRequest() { + return mLastRequest; + } + + public int getLastThreatType() { + return mLastThreatType; + } + + public void setSafeBrowsingAction(int action) { + mAction = action; + } + + public void setReporting(boolean value) { + mReporting = value; + } + } + private static class SafeBrowsingDependencyFactory extends AwTestBase.TestDependencyFactory { @Override public AwContents createAwContents(AwBrowserContext browserContext, ViewGroup containerView, @@ -221,7 +261,8 @@ @Override public void setUp() throws Exception { super.setUp(); - mContentsClient = new TestAwContentsClient(); + mContentsClient = new SafeBrowsingContentsClient(); + mContainerView = createAwTestContainerViewOnMainSync( mContentsClient, false, new SafeBrowsingDependencyFactory()); mAwContents = (MockAwContents) mContainerView.getAwContents(); @@ -373,8 +414,8 @@ @Feature({"AndroidWebView"}) @CommandLineFlags.Add(AwSwitches.WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT) public void testSafeBrowsingDoesNotBlockUnwantedSoftwarePages() throws Throwable { - // TODO(ntfschr): this is a temporary check until we add support for UwS warnings - // (crbug/729272) + // TODO(ntfschr): this is a temporary check until we add support for Unwanted Software + // warnings (crbug/729272) loadGreenPage(); final String responseUrl = mTestServer.getURL(UNWANTED_SOFTWARE_HTML_PATH); loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), responseUrl); @@ -595,4 +636,110 @@ mContentsClient.getOnPageFinishedHelper().waitForCallback(pageFinishedCount); assertTargetPageHasLoaded(PHISHING_PAGE_BACKGROUND_COLOR); } + + @SmallTest + @Feature({"AndroidWebView"}) + @CommandLineFlags.Add(AwSwitches.WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT) + public void testSafeBrowsingOnSafeBrowsingHitShowInterstitial() throws Throwable { + mContentsClient.setSafeBrowsingAction(SafeBrowsingAction.SHOW_INTERSTITIAL); + + loadGreenPage(); + loadPathAndWaitForInterstitial(PHISHING_HTML_PATH); + assertGreenPageNotShowing(); + assertTargetPageNotShowing(PHISHING_PAGE_BACKGROUND_COLOR); + // Assume that we are rendering the interstitial, since we see neither the previous page nor + // the target page + + // Check onSafeBrowsingHit arguments + final String responseUrl = mTestServer.getURL(PHISHING_HTML_PATH); + assertEquals(responseUrl, mContentsClient.getLastRequest().url); + assertEquals(AwSafeBrowsingConversionHelper.SAFE_BROWSING_THREAT_PHISHING, + mContentsClient.getLastThreatType()); + } + + @SmallTest + @Feature({"AndroidWebView"}) + @CommandLineFlags.Add(AwSwitches.WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT) + public void testSafeBrowsingOnSafeBrowsingHitProceed() throws Throwable { + mContentsClient.setSafeBrowsingAction(SafeBrowsingAction.PROCEED); + + loadGreenPage(); + final String responseUrl = mTestServer.getURL(PHISHING_HTML_PATH); + loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), responseUrl); + waitForVisualStateCallback(mAwContents); + assertTargetPageHasLoaded(PHISHING_PAGE_BACKGROUND_COLOR); + + // Check onSafeBrowsingHit arguments + assertEquals(responseUrl, mContentsClient.getLastRequest().url); + assertEquals(AwSafeBrowsingConversionHelper.SAFE_BROWSING_THREAT_PHISHING, + mContentsClient.getLastThreatType()); + } + + @SmallTest + @Feature({"AndroidWebView"}) + @CommandLineFlags.Add(AwSwitches.WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT) + public void testSafeBrowsingOnSafeBrowsingHitBackToSafety() throws Throwable { + mContentsClient.setSafeBrowsingAction(SafeBrowsingAction.BACK_TO_SAFETY); + + loadGreenPage(); + final String responseUrl = mTestServer.getURL(MALWARE_HTML_PATH); + loadUrlAsync(mAwContents, responseUrl); + OnReceivedError2Helper errorHelper = mContentsClient.getOnReceivedError2Helper(); + int errorCount = errorHelper.getCallCount(); + errorHelper.waitForCallback(errorCount); + assertEquals( + ErrorCodeConversionHelper.ERROR_UNSAFE_RESOURCE, errorHelper.getError().errorCode); + assertEquals("Network error is for the malicious page", responseUrl, + errorHelper.getRequest().url); + + assertEquals("Original page should be showing", GREEN_PAGE_BACKGROUND_COLOR, + GraphicsTestUtils.getPixelColorAtCenterOfView(mAwContents, mContainerView)); + + // Check onSafeBrowsingHit arguments + assertEquals(responseUrl, mContentsClient.getLastRequest().url); + assertEquals(AwSafeBrowsingConversionHelper.SAFE_BROWSING_THREAT_MALWARE, + mContentsClient.getLastThreatType()); + } + + @SmallTest + @Feature({"AndroidWebView"}) + @CommandLineFlags.Add(AwSwitches.WEBVIEW_ENABLE_SAFEBROWSING_SUPPORT) + public void testSafeBrowsingOnSafeBrowsingHitForSubresource() throws Throwable { + mContentsClient.setSafeBrowsingAction(SafeBrowsingAction.BACK_TO_SAFETY); + loadGreenPage(); + final String responseUrl = mTestServer.getURL(IFRAME_HTML_PATH); + final String subresourceUrl = mTestServer.getURL(MALWARE_HTML_PATH); + int pageFinishedCount = mContentsClient.getOnPageFinishedHelper().getCallCount(); + loadUrlAsync(mAwContents, responseUrl); + + // We'll successfully load IFRAME_HTML_PATH, and will soon call onSafeBrowsingHit + mContentsClient.getOnPageFinishedHelper().waitForCallback(pageFinishedCount); + + // Wait for the onSafeBrowsingHit to call BACK_TO_SAFETY and navigate back + pollUiThread(new Callable<Boolean>() { + @Override + public Boolean call() throws Exception { + return GREEN_PAGE_BACKGROUND_COLOR + == GraphicsTestUtils.getPixelColorAtCenterOfView( + mAwContents, mContainerView); + } + }); + + // Check onSafeBrowsingHit arguments + assertFalse(mContentsClient.getLastRequest().isMainFrame); + assertEquals(subresourceUrl, mContentsClient.getLastRequest().url); + assertEquals(AwSafeBrowsingConversionHelper.SAFE_BROWSING_THREAT_MALWARE, + mContentsClient.getLastThreatType()); + + mContentsClient.setSafeBrowsingAction(SafeBrowsingAction.PROCEED); + + loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), responseUrl); + waitForVisualStateCallback(mAwContents); + assertTargetPageHasLoaded(IFRAME_EMBEDDER_BACKGROUND_COLOR); + + assertFalse(mContentsClient.getLastRequest().isMainFrame); + assertEquals(subresourceUrl, mContentsClient.getLastRequest().url); + assertEquals(AwSafeBrowsingConversionHelper.SAFE_BROWSING_THREAT_MALWARE, + mContentsClient.getLastThreatType()); + } }
diff --git a/android_webview/test/shell/src/org/chromium/android_webview/test/NullContentsClient.java b/android_webview/test/shell/src/org/chromium/android_webview/test/NullContentsClient.java index 87efe6e..c9b5b9c 100644 --- a/android_webview/test/shell/src/org/chromium/android_webview/test/NullContentsClient.java +++ b/android_webview/test/shell/src/org/chromium/android_webview/test/NullContentsClient.java
@@ -21,9 +21,11 @@ import org.chromium.android_webview.AwContentsClientBridge; import org.chromium.android_webview.AwHttpAuthHandler; import org.chromium.android_webview.AwRenderProcessGoneDetail; +import org.chromium.android_webview.AwSafeBrowsingResponse; import org.chromium.android_webview.AwWebResourceResponse; import org.chromium.android_webview.JsPromptResultReceiver; import org.chromium.android_webview.JsResultReceiver; +import org.chromium.android_webview.SafeBrowsingAction; import org.chromium.android_webview.permission.AwPermissionRequest; import org.chromium.base.ThreadUtils; @@ -182,6 +184,13 @@ } @Override + public void onSafeBrowsingHit(AwWebResourceRequest request, int threatType, + ValueCallback<AwSafeBrowsingResponse> callback) { + callback.onReceiveValue(new AwSafeBrowsingResponse(SafeBrowsingAction.SHOW_INTERSTITIAL, + /* reporting */ true)); + } + + @Override public void onReceivedHttpError(AwWebResourceRequest request, AwWebResourceResponse response) { }
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index f20c23b..73ff43a 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -728,6 +728,8 @@ "wm/session_state_animator.h", "wm/session_state_animator_impl.cc", "wm/session_state_animator_impl.h", + "wm/splitview/split_view_controller.cc", + "wm/splitview/split_view_controller.h", "wm/stacking_controller.cc", "wm/stacking_controller.h", "wm/switchable_windows.cc", @@ -1270,6 +1272,7 @@ "wm/screen_dimmer_unittest.cc", "wm/screen_pinning_controller_unittest.cc", "wm/session_state_animator_impl_unittest.cc", + "wm/splitview/split_view_controller_unittest.cc", "wm/stacking_controller_unittest.cc", "wm/system_modal_container_layout_manager_unittest.cc", "wm/toplevel_window_event_handler_unittest.cc",
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 562904f5..55586074 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -219,7 +219,13 @@ All available users have already been added to this session. </message> <message name="IDS_ASH_STATUS_TRAY_NIGHT_LIGHT" desc="The label used for the button in the status tray to toggle the Night Light feature (which controls the color temperature of the screen) on or off."> - Night light + Night Light: <ph name="NIGHT_LIGHT_STATUS">$1<ex>On</ex></ph> + </message> + <message name="IDS_ASH_STATUS_TRAY_NIGHT_LIGHT_OFF_STATE" desc="The label for the Off state of the Night Light feature."> + Off + </message> + <message name="IDS_ASH_STATUS_TRAY_NIGHT_LIGHT_ON_STATE" desc="The label for the On state of the Night Light feature."> + On </message> <message name="IDS_ASH_STATUS_TRAY_CAST" desc="The label used as the header in the cast popup."> Cast screen
diff --git a/ash/ash_switches.cc b/ash/ash_switches.cc index 664c269..6fa85489 100644 --- a/ash/ash_switches.cc +++ b/ash/ash_switches.cc
@@ -47,6 +47,9 @@ const char kAshEnablePaletteOnAllDisplays[] = "ash-enable-palette-on-all-displays"; +// Enables the split view on tablet mode. +const char kAshEnableTabletSplitView[] = "enable-tablet-splitview"; + // Enables the observation of accelerometer events to enter touch-view mode. const char kAshEnableTouchView[] = "enable-touchview";
diff --git a/ash/ash_switches.h b/ash/ash_switches.h index 66f8266..e9bf822 100644 --- a/ash/ash_switches.h +++ b/ash/ash_switches.h
@@ -26,6 +26,7 @@ ASH_EXPORT extern const char kAshEnableMagnifierKeyScroller[]; ASH_EXPORT extern const char kAshEnablePaletteOnAllDisplays[]; ASH_EXPORT extern const char kAshEnableScaleSettingsTray[]; +ASH_EXPORT extern const char kAshEnableTabletSplitView[]; ASH_EXPORT extern const char kAshEnableTouchView[]; ASH_EXPORT extern const char kAshEnableMirroredScreen[]; ASH_EXPORT extern const char kAshEstimatedPresentationDelay[];
diff --git a/ash/autoclick/mus/autoclick_application.cc b/ash/autoclick/mus/autoclick_application.cc index b9e52e4..7804088 100644 --- a/ash/autoclick/mus/autoclick_application.cc +++ b/ash/autoclick/mus/autoclick_application.cc
@@ -90,9 +90,13 @@ AutoclickApplication::~AutoclickApplication() {} void AutoclickApplication::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) { + context()->QuitNow(); + return; + } autoclick_controller_common_.reset(new AutoclickControllerCommon( base::TimeDelta::FromMilliseconds(kDefaultAutoclickDelayMs), this)); }
diff --git a/ash/mus/window_manager_application.cc b/ash/mus/window_manager_application.cc index 274c231e..2f2d2ed 100644 --- a/ash/mus/window_manager_application.cc +++ b/ash/mus/window_manager_application.cc
@@ -129,10 +129,14 @@ mojo_interface_factory::RegisterInterfaces( ®istry_, base::ThreadTaskRunnerHandle::Get()); - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "ash_mus_resources.pak", "ash_mus_resources_200.pak", nullptr, views::AuraInit::Mode::AURA_MUS_WINDOW_MANAGER); + if (!aura_init_) { + context()->QuitNow(); + return; + } window_manager_ = base::MakeUnique<WindowManager>( context()->connector(), ash_config_, show_primary_host_on_connect_);
diff --git a/ash/public/interfaces/wallpaper.mojom b/ash/public/interfaces/wallpaper.mojom index 7215c31..02edb35c 100644 --- a/ash/public/interfaces/wallpaper.mojom +++ b/ash/public/interfaces/wallpaper.mojom
@@ -11,6 +11,10 @@ // Used by Chrome to set the wallpaper displayed by ash. interface WallpaperController { + // Calling this method triggers an initial notification of the wallpaper + // state. Observers are automatically removed as their connections are closed. + AddObserver(associated WallpaperObserver observer); + // Set the wallpaper picker interface, to let ash trigger Chrome's picker. SetWallpaperPicker(WallpaperPicker picker); @@ -19,6 +23,18 @@ // TODO(crbug.com/655875): Optimize ash wallpaper transport; avoid sending // large bitmaps over Mojo; use shared memory like BitmapUploader, etc. SetWallpaper(skia.mojom.Bitmap? wallpaper, WallpaperLayout layout); + + // Runs to get wallpaper prominent colors. + GetWallpaperColors() => (array<uint32> prominent_colors); +}; + +// Used to listen for wallpaper state changed. +interface WallpaperObserver { + // Called when the colors extracted from the current wallpaper change. May + // be called as a side effect of changing the wallpaper on the + // WallpaperController, e.g. WallpaperController::SetWallpaperImage(). + // Colors are ordered and are referenced in wallpaper::ColorProfileType. + OnWallpaperColorsChanged(array<uint32> prominent_colors); }; // Used by ash to trigger Chrome's wallpaper picker functionality.
diff --git a/ash/shelf/shelf_button.cc b/ash/shelf/shelf_button.cc index 0fc01bf..43c93a0b 100644 --- a/ash/shelf/shelf_button.cc +++ b/ash/shelf/shelf_button.cc
@@ -319,8 +319,12 @@ destroyed_flag_ = nullptr; // The menu will not propagate mouse events while its shown. To address, // the hover state gets cleared once the menu was shown (and this was not - // destroyed). - ClearState(STATE_HOVERED); + // destroyed). In case context menu is shown target view does not receive + // OnMouseReleased events and we need to cancel capture manually. + if (shelf_view_->drag_view() == this) + OnMouseCaptureLost(); + else + ClearState(STATE_HOVERED); } }
diff --git a/ash/shelf/shelf_view.h b/ash/shelf/shelf_view.h index 8c11c9e6..15fd7bd 100644 --- a/ash/shelf/shelf_view.h +++ b/ash/shelf/shelf_view.h
@@ -169,6 +169,8 @@ // the overflow shelf. ShelfView* main_shelf() { return main_shelf_; } + const ShelfButton* drag_view() const { return drag_view_; } + private: friend class ash::test::ShelfViewTestAPI;
diff --git a/ash/shell.cc b/ash/shell.cc index 6844249..0a6cf55 100644 --- a/ash/shell.cc +++ b/ash/shell.cc
@@ -108,6 +108,7 @@ #include "ash/wm/resize_shadow_controller.h" #include "ash/wm/root_window_finder.h" #include "ash/wm/screen_pinning_controller.h" +#include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/system_gesture_event_filter.h" #include "ash/wm/system_modal_container_event_filter.h" #include "ash/wm/system_modal_container_layout_manager.h" @@ -464,6 +465,10 @@ ->DoInitialAnimation(); } +bool Shell::IsSplitViewModeActive() const { + return split_view_controller_->IsSplitViewModeActive(); +} + void Shell::AddShellObserver(ShellObserver* observer) { shell_observers_.AddObserver(observer); } @@ -529,6 +534,16 @@ observer.OnOverviewModeEnded(); } +void Shell::NotifySplitViewModeStarting() { + for (auto& observer : shell_observers_) + observer.OnSplitViewModeStarting(); +} + +void Shell::NotifySplitViewModeEnded() { + for (auto& observer : shell_observers_) + observer.OnSplitViewModeEnded(); +} + void Shell::NotifyFullscreenStateChanged(bool is_fullscreen, aura::Window* root_window) { for (auto& observer : shell_observers_) @@ -642,7 +657,9 @@ // See bug crbug.com/134502. aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(nullptr); - // Please keep in same order as in Init() because it's easy to miss one. + // Please keep in reverse order as in Init() because it's easy to miss one. + split_view_controller_.reset(); + if (window_modality_controller_) window_modality_controller_.reset(); @@ -1108,6 +1125,8 @@ screen_layout_observer_.reset(new ScreenLayoutObserver()); sms_observer_.reset(new SmsObserver()); + split_view_controller_.reset(new SplitViewController()); + // The compositor thread and main message loop have to be running in // order to create mirror window. Run it after the main message loop // is started.
diff --git a/ash/shell.h b/ash/shell.h index 3c5afd3..b151530 100644 --- a/ash/shell.h +++ b/ash/shell.h
@@ -145,6 +145,7 @@ class ShutdownController; class ShutdownObserver; class SmsObserver; +class SplitViewController; class StickyKeysController; class SystemGestureEventFilter; class SystemModalContainerEventFilter; @@ -530,6 +531,13 @@ GPUSupport* gpu_support() { return gpu_support_.get(); } + SplitViewController* split_view_controller() { + return split_view_controller_.get(); + } + + // Returns true if split view mode is active. + bool IsSplitViewModeActive() const; + void AddShellObserver(ShellObserver* observer); void RemoveShellObserver(ShellObserver* observer); @@ -571,6 +579,13 @@ // Notifies observers that overview mode has ended. void NotifyOverviewModeEnded(); + // Notifies observers that split view mode is about to be started (before the + // window gets snapped and activated). + void NotifySplitViewModeStarting(); + + // Notifies observers that split view mode has ended. + void NotifySplitViewModeEnded(); + // Notifies observers that fullscreen mode has changed for |root_window|. void NotifyFullscreenStateChanged(bool is_fullscreen, aura::Window* root_window); @@ -795,6 +810,9 @@ std::unique_ptr<PartialMagnificationController> partial_magnification_controller_; + // The split view controller for Chrome OS in tablet mode. + std::unique_ptr<SplitViewController> split_view_controller_; + // |native_cursor_manager_| is owned by |cursor_manager_|, but we keep a // pointer to vend to test code. NativeCursorManagerAsh* native_cursor_manager_;
diff --git a/ash/shell_observer.h b/ash/shell_observer.h index 282e08cc..66f4c91 100644 --- a/ash/shell_observer.h +++ b/ash/shell_observer.h
@@ -52,6 +52,13 @@ // Called after overview mode has ended. virtual void OnOverviewModeEnded() {} + // Called when the split view mode is about to be started (before the window + // gets snapped and activated). + virtual void OnSplitViewModeStarting() {} + + // Called after split view mode has ended. + virtual void OnSplitViewModeEnded() {} + // Called when the always maximize mode has started. Windows might still // animate though. virtual void OnMaximizeModeStarted() {}
diff --git a/ash/system/night_light/OWNERS b/ash/system/night_light/OWNERS new file mode 100644 index 0000000..1bfdf742 --- /dev/null +++ b/ash/system/night_light/OWNERS
@@ -0,0 +1,2 @@ +afakhry@chromium.org +jamescook@chromium.org \ No newline at end of file
diff --git a/ash/system/night_light/night_light_toggle_button.cc b/ash/system/night_light/night_light_toggle_button.cc index 97d0444e..231d655 100644 --- a/ash/system/night_light/night_light_toggle_button.cc +++ b/ash/system/night_light/night_light_toggle_button.cc
@@ -36,6 +36,14 @@ kMenuIconColorDisabled); } +base::string16 GetNightLightTooltipText(bool night_light_enabled) { + return l10n_util::GetStringFUTF16( + IDS_ASH_STATUS_TRAY_NIGHT_LIGHT, + l10n_util::GetStringUTF16( + night_light_enabled ? IDS_ASH_STATUS_TRAY_NIGHT_LIGHT_ON_STATE + : IDS_ASH_STATUS_TRAY_NIGHT_LIGHT_OFF_STATE)); +} + } // namespace NightLightToggleButton::NightLightToggleButton(views::ButtonListener* listener) @@ -50,6 +58,7 @@ const bool night_light_enabled = Shell::Get()->night_light_controller()->GetEnabled(); + SetTooltipText(GetNightLightTooltipText(night_light_enabled)); SetImage(views::Button::STATE_NORMAL, GetNightLightNormalStateIcon(night_light_enabled)); SetImage(views::Button::STATE_DISABLED,
diff --git a/ash/touch_hud/mus/touch_hud_application.cc b/ash/touch_hud/mus/touch_hud_application.cc index 59f138ad..7bdd417 100644 --- a/ash/touch_hud/mus/touch_hud_application.cc +++ b/ash/touch_hud/mus/touch_hud_application.cc
@@ -69,9 +69,11 @@ TouchHudApplication::~TouchHudApplication() {} void TouchHudApplication::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) + context()->QuitNow(); } void TouchHudApplication::OnBindInterface(
diff --git a/ash/wallpaper/wallpaper_controller.cc b/ash/wallpaper/wallpaper_controller.cc index 7d2e5ca..e594db7 100644 --- a/ash/wallpaper/wallpaper_controller.cc +++ b/ash/wallpaper/wallpaper_controller.cc
@@ -23,6 +23,7 @@ #include "base/sequenced_task_runner.h" #include "base/task_scheduler/post_task.h" #include "components/wallpaper/wallpaper_color_calculator.h" +#include "components/wallpaper/wallpaper_color_profile.h" #include "components/wallpaper/wallpaper_resizer.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/managed_display_info.h" @@ -34,6 +35,7 @@ using color_utils::ColorProfile; using color_utils::LumaRange; using color_utils::SaturationRange; +using wallpaper::ColorProfileType; namespace ash { @@ -45,17 +47,6 @@ // How long to wait for resizing of the the wallpaper. constexpr int kCompositorLockTimeoutMs = 750; -// This enum is used to get the corresponding prominent color from the -// calculation results. -enum ColorProfileIndex { - COLOR_PROFILE_INDEX_DARK_VIBRANT = 0, - COLOR_PROFILE_INDEX_NORMAL_VIBRANT, - COLOR_PROFILE_INDEX_LIGHT_VIBRANT, - COLOR_PROFILE_INDEX_DARK_MUTED, - COLOR_PROFILE_INDEX_NORMAL_MUTED, - COLOR_PROFILE_INDEX_LIGHT_MUTED, -}; - // Returns true if a color should be extracted from the wallpaper based on the // command kAshShelfColor line arg. bool IsShelfColoringEnabled() { @@ -90,30 +81,30 @@ ColorProfile(LumaRange::LIGHT, SaturationRange::MUTED)}; } -// Gets the corresponding color profile index based on the given +// Gets the corresponding color profile type based on the given // |color_profile|. -ColorProfileIndex GetColorProfileIndex(ColorProfile color_profile) { +ColorProfileType GetColorProfileType(ColorProfile color_profile) { if (color_profile.saturation == SaturationRange::VIBRANT) { switch (color_profile.luma) { case LumaRange::DARK: - return COLOR_PROFILE_INDEX_DARK_VIBRANT; + return ColorProfileType::DARK_VIBRANT; case LumaRange::NORMAL: - return COLOR_PROFILE_INDEX_NORMAL_VIBRANT; + return ColorProfileType::NORMAL_VIBRANT; case LumaRange::LIGHT: - return COLOR_PROFILE_INDEX_LIGHT_VIBRANT; + return ColorProfileType::LIGHT_VIBRANT; } } else { switch (color_profile.luma) { case LumaRange::DARK: - return COLOR_PROFILE_INDEX_DARK_MUTED; + return ColorProfileType::DARK_MUTED; case LumaRange::NORMAL: - return COLOR_PROFILE_INDEX_NORMAL_MUTED; + return ColorProfileType::NORMAL_MUTED; case LumaRange::LIGHT: - return COLOR_PROFILE_INDEX_LIGHT_MUTED; + return ColorProfileType::LIGHT_MUTED; } } NOTREACHED(); - return COLOR_PROFILE_INDEX_DARK_MUTED; + return ColorProfileType::DARK_MUTED; } } // namespace @@ -173,8 +164,8 @@ SkColor WallpaperController::GetProminentColor( ColorProfile color_profile) const { - ColorProfileIndex index = GetColorProfileIndex(color_profile); - return prominent_colors_[index]; + ColorProfileType type = GetColorProfileType(color_profile); + return prominent_colors_[static_cast<int>(type)]; } wallpaper::WallpaperLayout WallpaperController::GetWallpaperLayout() const { @@ -305,6 +296,14 @@ } } +void WallpaperController::AddObserver( + mojom::WallpaperObserverAssociatedPtrInfo observer) { + mojom::WallpaperObserverAssociatedPtr observer_ptr; + observer_ptr.Bind(std::move(observer)); + observer_ptr->OnWallpaperColorsChanged(prominent_colors_); + mojo_observers_.AddPtr(std::move(observer_ptr)); +} + void WallpaperController::SetWallpaperPicker(mojom::WallpaperPickerPtr picker) { wallpaper_picker_ = std::move(picker); } @@ -317,6 +316,11 @@ SetWallpaperImage(gfx::ImageSkia::CreateFrom1xBitmap(wallpaper), layout); } +void WallpaperController::GetWallpaperColors( + GetWallpaperColorsCallback callback) { + std::move(callback).Run(prominent_colors_); +} + void WallpaperController::OnWallpaperResized() { CalculateWallpaperColors(); compositor_lock_.reset(); @@ -403,6 +407,9 @@ prominent_colors_ = colors; for (auto& observer : observers_) observer.OnWallpaperColorsChanged(); + mojo_observers_.ForAllPtrs([this](mojom::WallpaperObserver* observer) { + observer->OnWallpaperColorsChanged(prominent_colors_); + }); } void WallpaperController::CalculateWallpaperColors() {
diff --git a/ash/wallpaper/wallpaper_controller.h b/ash/wallpaper/wallpaper_controller.h index 74919b2..6c224f65 100644 --- a/ash/wallpaper/wallpaper_controller.h +++ b/ash/wallpaper/wallpaper_controller.h
@@ -19,6 +19,7 @@ #include "components/wallpaper/wallpaper_layout.h" #include "components/wallpaper/wallpaper_resizer_observer.h" #include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/interface_ptr_set.h" #include "ui/compositor/compositor_lock.h" namespace base { @@ -122,9 +123,11 @@ void OpenSetWallpaperPage(); // mojom::WallpaperController overrides: + void AddObserver(mojom::WallpaperObserverAssociatedPtrInfo observer) override; void SetWallpaperPicker(mojom::WallpaperPickerPtr picker) override; void SetWallpaper(const SkBitmap& wallpaper, wallpaper::WallpaperLayout layout) override; + void GetWallpaperColors(GetWallpaperColorsCallback callback) override; // WallpaperResizerObserver: void OnWallpaperResized() override; @@ -195,6 +198,8 @@ base::ObserverList<WallpaperControllerObserver> observers_; + mojo::AssociatedInterfacePtrSet<mojom::WallpaperObserver> mojo_observers_; + std::unique_ptr<wallpaper::WallpaperResizer> current_wallpaper_; // Asynchronous task to extract colors from the wallpaper.
diff --git a/ash/wallpaper/wallpaper_controller_unittest.cc b/ash/wallpaper/wallpaper_controller_unittest.cc index cf8c2d1..f8d1599 100644 --- a/ash/wallpaper/wallpaper_controller_unittest.cc +++ b/ash/wallpaper/wallpaper_controller_unittest.cc
@@ -23,6 +23,7 @@ #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/task_scheduler/task_scheduler.h" +#include "mojo/public/cpp/bindings/associated_binding.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/aura/window.h" @@ -106,6 +107,28 @@ } } +// A test implementation of the WallpaperObserver mojo interface. +class TestWallpaperObserver : public mojom::WallpaperObserver { + public: + TestWallpaperObserver() = default; + ~TestWallpaperObserver() override = default; + + // mojom::WallpaperObserver: + void OnWallpaperColorsChanged( + const std::vector<SkColor>& prominent_colors) override { + ++wallpaper_colors_changed_count_; + } + + int wallpaper_colors_changed_count() const { + return wallpaper_colors_changed_count_; + } + + private: + int wallpaper_colors_changed_count_ = 0; + + DISALLOW_COPY_AND_ASSIGN(TestWallpaperObserver); +}; + } // namespace class WallpaperControllerTest : public test::AshTestBase { @@ -529,4 +552,25 @@ EXPECT_FALSE(ShouldCalculateColors()); } +TEST_F(WallpaperControllerTest, MojoWallpaperObserverTest) { + TestWallpaperObserver observer; + mojom::WallpaperObserverAssociatedPtr observer_ptr; + mojo::AssociatedBinding<mojom::WallpaperObserver> binding( + &observer, mojo::MakeIsolatedRequest(&observer_ptr)); + controller_->AddObserver(observer_ptr.PassInterface()); + + // Mojo observer will asynchronously receive the observed event, thus a run + // loop needs to be spinned. + base::RunLoop().RunUntilIdle(); + // When adding observer, OnWallpaperColorsChanged() is fired so that we start + // with count equals 1. + EXPECT_EQ(1, observer.wallpaper_colors_changed_count()); + + // Enable shelf coloring will set a customized wallpaper image and change + // session state to ACTIVE, which will trigger wallpaper colors calculation. + EnableShelfColoring(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(2, observer.wallpaper_colors_changed_count()); +} + } // namespace ash
diff --git a/ash/wm/maximize_mode/maximize_mode_window_manager.cc b/ash/wm/maximize_mode/maximize_mode_window_manager.cc index 9953ece..f4f2a11 100644 --- a/ash/wm/maximize_mode/maximize_mode_window_manager.cc +++ b/ash/wm/maximize_mode/maximize_mode_window_manager.cc
@@ -86,6 +86,17 @@ SetDeferBoundsUpdates(false); } +void MaximizeModeWindowManager::OnSplitViewModeEnded() { + // Maximize all snapped windows upon exiting split view mode. + for (auto& pair : window_state_map_) { + if (pair.second->GetType() == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED || + pair.second->GetType() == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED) { + wm::WMEvent event(wm::WM_EVENT_MAXIMIZE); + wm::GetWindowState(pair.first)->OnWMEvent(&event); + } + } +} + void MaximizeModeWindowManager::OnWindowDestroying(aura::Window* window) { if (IsContainerWindow(window)) { // container window can be removed on display destruction.
diff --git a/ash/wm/maximize_mode/maximize_mode_window_manager.h b/ash/wm/maximize_mode/maximize_mode_window_manager.h index fbdedccf..d89deec 100644 --- a/ash/wm/maximize_mode/maximize_mode_window_manager.h +++ b/ash/wm/maximize_mode/maximize_mode_window_manager.h
@@ -57,6 +57,7 @@ // ShellObserver overrides: void OnOverviewModeStarting() override; void OnOverviewModeEnded() override; + void OnSplitViewModeEnded() override; // Overridden from WindowObserver: void OnWindowDestroying(aura::Window* window) override;
diff --git a/ash/wm/maximize_mode/maximize_mode_window_state.cc b/ash/wm/maximize_mode/maximize_mode_window_state.cc index 989fff7..260ad80 100644 --- a/ash/wm/maximize_mode/maximize_mode_window_state.cc +++ b/ash/wm/maximize_mode/maximize_mode_window_state.cc
@@ -11,6 +11,7 @@ #include "ash/shell.h" #include "ash/wm/maximize_mode/maximize_mode_window_manager.h" #include "ash/wm/screen_pinning_controller.h" +#include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/window_animation_types.h" #include "ash/wm/window_properties.h" #include "ash/wm/window_state_util.h" @@ -67,11 +68,36 @@ return work_area_in_parent; } +// Returns true if the window can snap in maximized mode. +bool CanSnap(wm::WindowState* window_state) { + // If split view mode is not allowed in maximized mode, do not allow snapping + // windows. + if (!SplitViewController::ShouldAllowSplitView()) + return false; + return window_state->CanSnap(); +} + // Returns the maximized/full screen and/or centered bounds of a window. gfx::Rect GetBoundsInMaximizedMode(wm::WindowState* state_object) { if (state_object->IsFullscreen() || state_object->IsPinned()) return ScreenUtil::GetDisplayBoundsInParent(state_object->window()); + if (state_object->GetStateType() == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED) { + DCHECK(CanSnap(state_object)); + return Shell::Get() + ->split_view_controller() + ->GetSnappedWindowBoundsInParent(state_object->window(), + SplitViewController::LEFT_SNAPPED); + } + + if (state_object->GetStateType() == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED) { + DCHECK(CanSnap(state_object)); + return Shell::Get() + ->split_view_controller() + ->GetSnappedWindowBoundsInParent(state_object->window(), + SplitViewController::RIGHT_SNAPPED); + } + gfx::Rect bounds_in_parent; // Make the window as big as possible. if (state_object->CanMaximize() || state_object->CanResize()) { @@ -169,13 +195,23 @@ case wm::WM_EVENT_CYCLE_SNAP_LEFT: case wm::WM_EVENT_CYCLE_SNAP_RIGHT: case wm::WM_EVENT_CENTER: - case wm::WM_EVENT_SNAP_LEFT: - case wm::WM_EVENT_SNAP_RIGHT: case wm::WM_EVENT_NORMAL: case wm::WM_EVENT_MAXIMIZE: UpdateWindow(window_state, GetMaximizedOrCenteredWindowType(window_state), true); return; + case wm::WM_EVENT_SNAP_LEFT: + UpdateWindow(window_state, + GetSnappedWindowStateType( + window_state, wm::WINDOW_STATE_TYPE_LEFT_SNAPPED), + true); + return; + case wm::WM_EVENT_SNAP_RIGHT: + UpdateWindow(window_state, + GetSnappedWindowStateType( + window_state, wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED), + true); + return; case wm::WM_EVENT_MINIMIZE: UpdateWindow(window_state, wm::WINDOW_STATE_TYPE_MINIMIZED, true); return; @@ -193,7 +229,9 @@ } else if (current_state_type_ != wm::WINDOW_STATE_TYPE_MINIMIZED && current_state_type_ != wm::WINDOW_STATE_TYPE_FULLSCREEN && current_state_type_ != wm::WINDOW_STATE_TYPE_PINNED && - current_state_type_ != wm::WINDOW_STATE_TYPE_TRUSTED_PINNED) { + current_state_type_ != wm::WINDOW_STATE_TYPE_TRUSTED_PINNED && + current_state_type_ != wm::WINDOW_STATE_TYPE_LEFT_SNAPPED && + current_state_type_ != wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED) { // In all other cases (except for minimized windows) we respect the // requested bounds and center it to a fully visible area on the screen. gfx::Rect bounds_in_parent = @@ -274,7 +312,9 @@ target_state == wm::WINDOW_STATE_TYPE_TRUSTED_PINNED || (target_state == wm::WINDOW_STATE_TYPE_NORMAL && !window_state->CanMaximize()) || - target_state == wm::WINDOW_STATE_TYPE_FULLSCREEN); + target_state == wm::WINDOW_STATE_TYPE_FULLSCREEN || + target_state == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED || + target_state == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED); if (current_state_type_ == target_state) { if (target_state == wm::WINDOW_STATE_TYPE_MINIMIZED) @@ -295,6 +335,14 @@ window_state->window()->Hide(); if (window_state->IsActive()) window_state->Deactivate(); + } else if (target_state == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED) { + window_state->SetBoundsDirectAnimated( + Shell::Get()->split_view_controller()->GetSnappedWindowBoundsInParent( + window_state->window(), SplitViewController::LEFT_SNAPPED)); + } else if (target_state == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED) { + window_state->SetBoundsDirectAnimated( + Shell::Get()->split_view_controller()->GetSnappedWindowBoundsInParent( + window_state->window(), SplitViewController::RIGHT_SNAPPED)); } else { UpdateBounds(window_state, animated); } @@ -324,6 +372,15 @@ : wm::WINDOW_STATE_TYPE_NORMAL; } +wm::WindowStateType MaximizeModeWindowState::GetSnappedWindowStateType( + wm::WindowState* window_state, + wm::WindowStateType target_state) { + DCHECK(target_state == wm::WINDOW_STATE_TYPE_LEFT_SNAPPED || + target_state == wm::WINDOW_STATE_TYPE_RIGHT_SNAPPED); + return CanSnap(window_state) ? target_state + : GetMaximizedOrCenteredWindowType(window_state); +} + void MaximizeModeWindowState::UpdateBounds(wm::WindowState* window_state, bool animated) { if (defer_bounds_updates_)
diff --git a/ash/wm/maximize_mode/maximize_mode_window_state.h b/ash/wm/maximize_mode/maximize_mode_window_state.h index 4ab3d5a2..1e43455 100644 --- a/ash/wm/maximize_mode/maximize_mode_window_state.h +++ b/ash/wm/maximize_mode/maximize_mode_window_state.h
@@ -62,6 +62,14 @@ wm::WindowStateType GetMaximizedOrCenteredWindowType( wm::WindowState* window_state); + // If |target_state| is LEFT/RIGHT_SNAPPED and the window can be snapped, + // returns |target_state|. Otherwise depending on the capabilities of the + // window either returns |WINDOW_STATE_TYPE_MAXIMIZED| or + // |WINDOW_STATE_TYPE_NORMAL|. + wm::WindowStateType GetSnappedWindowStateType( + wm::WindowState* window_state, + wm::WindowStateType target_state); + // Updates the bounds to the maximum possible bounds according to the current // window state. If |animated| is set we animate the change. void UpdateBounds(wm::WindowState* window_state, bool animated);
diff --git a/ash/wm/splitview/split_view_controller.cc b/ash/wm/splitview/split_view_controller.cc new file mode 100644 index 0000000..b86b3d5a --- /dev/null +++ b/ash/wm/splitview/split_view_controller.cc
@@ -0,0 +1,339 @@ +// 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/wm/splitview/split_view_controller.h" + +#include "ash/ash_switches.h" +#include "ash/public/cpp/shell_window_ids.h" +#include "ash/screen_util.h" +#include "ash/shell.h" +#include "ash/wm/maximize_mode/maximize_mode_controller.h" +#include "ash/wm/mru_window_tracker.h" +#include "ash/wm/window_state.h" +#include "ash/wm/window_util.h" +#include "ash/wm/wm_event.h" +#include "base/command_line.h" +#include "ui/aura/window.h" +#include "ui/wm/core/coordinate_conversion.h" +#include "ui/wm/public/activation_client.h" + +namespace ash { + +namespace { + +// Returns true if |window| can be activated and snapped. +bool CanSnap(aura::Window* window) { + return wm::CanActivateWindow(window) ? wm::GetWindowState(window)->CanSnap() + : false; +} + +} // namespace + +SplitViewController::SplitViewController() { + Shell::Get()->AddShellObserver(this); + Shell::Get()->activation_client()->AddObserver(this); +} + +SplitViewController::~SplitViewController() { + Shell::Get()->RemoveShellObserver(this); + Shell::Get()->activation_client()->RemoveObserver(this); + EndSplitView(); +} + +// static +bool SplitViewController::ShouldAllowSplitView() { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kAshEnableTabletSplitView)) { + return false; + } + if (!Shell::Get() + ->maximize_mode_controller() + ->IsMaximizeModeWindowManagerEnabled()) { + return false; + } + return true; +} + +bool SplitViewController::IsSplitViewModeActive() const { + return state_ != NO_SNAP; +} + +void SplitViewController::SnapWindow(aura::Window* window, + SnapPosition snap_position) { + DCHECK(window && CanSnap(window)); + + if (state_ == NO_SNAP) + Shell::Get()->NotifySplitViewModeStarting(); + + State previous_state = state_; + if (snap_position == LEFT) { + if (left_window_ != window) { + StopObserving(left_window_); + left_window_ = window; + } + right_window_ = (window == right_window_) ? nullptr : right_window_; + + switch (state_) { + case NO_SNAP: + default_snap_position_ = LEFT; + state_ = LEFT_SNAPPED; + break; + case LEFT_SNAPPED: + state_ = LEFT_SNAPPED; + break; + case RIGHT_SNAPPED: + case BOTH_SNAPPED: + state_ = BOTH_SNAPPED; + break; + } + } else if (snap_position == RIGHT) { + if (right_window_ != window) { + StopObserving(right_window_); + right_window_ = window; + } + left_window_ = (window == left_window_) ? nullptr : left_window_; + + switch (state_) { + case NO_SNAP: + default_snap_position_ = RIGHT; + state_ = RIGHT_SNAPPED; + break; + case RIGHT_SNAPPED: + state_ = RIGHT_SNAPPED; + break; + case LEFT_SNAPPED: + case BOTH_SNAPPED: + state_ = BOTH_SNAPPED; + break; + } + } + + StartObserving(window); + const wm::WMEvent event((snap_position == LEFT) ? wm::WM_EVENT_SNAP_LEFT + : wm::WM_EVENT_SNAP_RIGHT); + wm::GetWindowState(window)->OnWMEvent(&event); + wm::ActivateWindow(window); + + NotifySplitViewStateChanged(previous_state, state_); +} + +aura::Window* SplitViewController::GetDefaultSnappedWindow() { + if (default_snap_position_ == LEFT) + return left_window_; + if (default_snap_position_ == RIGHT) + return right_window_; + return nullptr; +} + +gfx::Rect SplitViewController::GetSnappedWindowBoundsInParent( + aura::Window* window, + State snap_state) { + if (snap_state == LEFT_SNAPPED) + return GetLeftWindowBoundsInParent(window); + else if (snap_state == RIGHT_SNAPPED) + return GetRightWindowBoundsInParent(window); + + NOTREACHED(); + return gfx::Rect(); +} + +gfx::Rect SplitViewController::GetSnappedWindowBoundsInScreen( + aura::Window* window, + State snap_state) { + if (snap_state == LEFT_SNAPPED) + return GetLeftWindowBoundsInScreen(window); + else if (snap_state == RIGHT_SNAPPED) + return GetRightWindowBoundsInScreen(window); + + NOTREACHED(); + return gfx::Rect(); +} + +gfx::Rect SplitViewController::GetDisplayWorkAreaBoundsInParent( + aura::Window* window) { + aura::Window* root_window = window->GetRootWindow(); + return ScreenUtil::GetDisplayWorkAreaBoundsInParent( + root_window->GetChildById(kShellWindowId_DefaultContainer)); +} + +gfx::Rect SplitViewController::GetDisplayWorkAreaBoundsInScreen( + aura::Window* window) { + gfx::Rect bounds = GetDisplayWorkAreaBoundsInParent(window); + ::wm::ConvertRectToScreen(window->GetRootWindow(), &bounds); + return bounds; +} + +void SplitViewController::AddObserver(Observer* observer) { + observers_.AddObserver(observer); +} + +void SplitViewController::RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); +} + +void SplitViewController::OnWindowDestroying(aura::Window* window) { + // If one of the snapped window gets closed, end the split view mode. The + // behavior might change in the future. + DCHECK(window == left_window_ || window == right_window_); + EndSplitView(); +} + +void SplitViewController::OnPostWindowStateTypeChange( + ash::wm::WindowState* window_state, + ash::wm::WindowStateType old_type) { + if (window_state->IsFullscreen() || window_state->IsMinimized() || + window_state->IsMaximized()) { + // TODO(xdai): Decide what to do if one of the snapped windows gets + // minimized /maximized / full-screened. For now we end the split view mode + // for simplicity. + EndSplitView(); + } +} + +void SplitViewController::OnWindowActivated(ActivationReason reason, + aura::Window* gained_active, + aura::Window* lost_active) { + if (!IsSplitViewModeActive()) + return; + + // If |gained_active| was activated as a side effect of a window disposition + // change, do nothing. For example, when a snapped window is closed, another + // window will be activated before OnWindowDestroying() is called. We should + // not try to snap another window in this case. + if (reason == ActivationReason::WINDOW_DISPOSITION_CHANGED) + return; + + // Only snap window that can be snapped but hasn't been snapped. + if (!gained_active || gained_active == left_window_ || + gained_active == right_window_ || !CanSnap(gained_active)) { + return; + } + + // Only window in MRU list can be snapped. + aura::Window::Windows windows = + Shell::Get()->mru_window_tracker()->BuildMruWindowList(); + if (std::find(windows.begin(), windows.end(), gained_active) == windows.end()) + return; + + // Snap the window on the non-default side of the screen if split view mode + // is active. + if (default_snap_position_ == LEFT) + SnapWindow(gained_active, SplitViewController::RIGHT); + else + SnapWindow(gained_active, SplitViewController::LEFT); +} + +void SplitViewController::OnOverviewModeStarting() { + // If split view mode is active, reset |state_| to make it be able to select + // another window from overview window grid. + if (IsSplitViewModeActive()) { + State previous_state = state_; + if (default_snap_position_ == LEFT) { + StopObserving(right_window_); + state_ = LEFT_SNAPPED; + } else { + StopObserving(left_window_); + state_ = RIGHT_SNAPPED; + } + NotifySplitViewStateChanged(previous_state, state_); + } +} + +void SplitViewController::OnOverviewModeEnded() { + // If split view mode is active but only has one snapped window, use the MRU + // window list to auto select another window to snap. + if (IsSplitViewModeActive() && state_ != BOTH_SNAPPED) { + aura::Window::Windows windows = + Shell::Get()->mru_window_tracker()->BuildMruWindowList(); + for (auto* window : windows) { + if (CanSnap(window) && window != GetDefaultSnappedWindow()) { + if (default_snap_position_ == LEFT) + SnapWindow(window, SplitViewController::RIGHT); + else + SnapWindow(window, SplitViewController::LEFT); + break; + } + } + } +} + +void SplitViewController::EndSplitView() { + StopObserving(left_window_); + StopObserving(right_window_); + left_window_ = nullptr; + right_window_ = nullptr; + default_snap_position_ = LEFT; + divider_position_ = -1; + + State previous_state = state_; + state_ = NO_SNAP; + NotifySplitViewStateChanged(previous_state, state_); + + Shell::Get()->NotifySplitViewModeEnded(); +} + +void SplitViewController::StartObserving(aura::Window* window) { + if (window && !window->HasObserver(this)) { + window->AddObserver(this); + wm::GetWindowState(window)->AddObserver(this); + } +} + +void SplitViewController::StopObserving(aura::Window* window) { + if (window && window->HasObserver(this)) { + window->RemoveObserver(this); + wm::GetWindowState(window)->RemoveObserver(this); + } +} + +void SplitViewController::NotifySplitViewStateChanged(State previous_state, + State state) { + if (previous_state == state) + return; + for (Observer& observer : observers_) + observer.OnSplitViewStateChanged(previous_state, state); +} + +gfx::Rect SplitViewController::GetLeftWindowBoundsInParent( + aura::Window* window) { + gfx::Rect bounds = GetLeftWindowBoundsInScreen(window); + ::wm::ConvertRectFromScreen(window->GetRootWindow(), &bounds); + return bounds; +} + +gfx::Rect SplitViewController::GetRightWindowBoundsInParent( + aura::Window* window) { + gfx::Rect bounds = GetRightWindowBoundsInScreen(window); + ::wm::ConvertRectFromScreen(window->GetRootWindow(), &bounds); + return bounds; +} + +gfx::Rect SplitViewController::GetLeftWindowBoundsInScreen( + aura::Window* window) { + const gfx::Rect display_bounds_in_screen = + GetDisplayWorkAreaBoundsInScreen(window); + if (divider_position_ < 0) { + divider_position_ = + display_bounds_in_screen.x() + display_bounds_in_screen.width() * 0.5f; + } + return gfx::Rect(display_bounds_in_screen.x(), display_bounds_in_screen.y(), + divider_position_ - display_bounds_in_screen.x(), + display_bounds_in_screen.height()); +} + +gfx::Rect SplitViewController::GetRightWindowBoundsInScreen( + aura::Window* window) { + const gfx::Rect display_bounds_in_screen = + GetDisplayWorkAreaBoundsInScreen(window); + if (divider_position_ < 0) { + divider_position_ = + display_bounds_in_screen.x() + display_bounds_in_screen.width() * 0.5f; + } + return gfx::Rect(divider_position_, display_bounds_in_screen.y(), + display_bounds_in_screen.x() + + display_bounds_in_screen.width() - divider_position_, + display_bounds_in_screen.height()); +} + +} // namespace ash
diff --git a/ash/wm/splitview/split_view_controller.h b/ash/wm/splitview/split_view_controller.h new file mode 100644 index 0000000..cab2c67 --- /dev/null +++ b/ash/wm/splitview/split_view_controller.h
@@ -0,0 +1,134 @@ +// 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_WM_SPLITSVIEW_SPLIT_VIEW_CONTROLLER_H_ +#define ASH_WM_SPLITSVIEW_SPLIT_VIEW_CONTROLLER_H_ + +#include "ash/ash_export.h" +#include "ash/shell_observer.h" +#include "ash/wm/window_state_observer.h" +#include "base/macros.h" +#include "base/observer_list.h" +#include "ui/aura/window_observer.h" +#include "ui/wm/public/activation_change_observer.h" + +namespace ash { + +class SplitViewControllerTest; + +// The controller for the split view. It snaps a window to left/right side of +// the screen. It also observes the two snapped windows and decides when to exit +// the split view mode. +class ASH_EXPORT SplitViewController : public aura::WindowObserver, + public ash::wm::WindowStateObserver, + public ::wm::ActivationChangeObserver, + public ShellObserver { + public: + enum State { NO_SNAP, LEFT_SNAPPED, RIGHT_SNAPPED, BOTH_SNAPPED }; + enum SnapPosition { LEFT, RIGHT }; + + class Observer { + public: + // Called when split view state changed from |previous_state| to |state|. + virtual void OnSplitViewStateChanged( + SplitViewController::State previous_state, + SplitViewController::State state) {} + }; + + SplitViewController(); + ~SplitViewController() override; + + // Returns true if split view mode is supported. Currently the split view + // mode is only supported in maximized mode (tablet mode). + static bool ShouldAllowSplitView(); + + // Returns true if split view mode is active. + bool IsSplitViewModeActive() const; + + // Snaps window to left/right. + void SnapWindow(aura::Window* window, SnapPosition snap_position); + + // Returns the default snapped window. It's the window that remains open until + // the split mode ends. It's decided by |default_snap_position_|. E.g., If + // |default_snap_position_| equals LEFT, then the default snapped window is + // |left_window_|. All the other window will open on the right side. + aura::Window* GetDefaultSnappedWindow(); + + // Gets the window bounds according to the snap state |snap_state| and the + // separator position |separator_position_|. + gfx::Rect GetSnappedWindowBoundsInParent(aura::Window* window, + State snap_state); + gfx::Rect GetSnappedWindowBoundsInScreen(aura::Window* window, + State snap_state); + gfx::Rect GetDisplayWorkAreaBoundsInParent(aura::Window* window); + gfx::Rect GetDisplayWorkAreaBoundsInScreen(aura::Window* window); + + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + // aura::WindowObserver: + void OnWindowDestroying(aura::Window* window) override; + + // ash::wm::WindowStateObserver: + void OnPostWindowStateTypeChange(ash::wm::WindowState* window_state, + ash::wm::WindowStateType old_type) override; + + // wm::ActivationChangeObserver: + void OnWindowActivated(ActivationReason reason, + aura::Window* gained_active, + aura::Window* lost_active) override; + + // ShellObserver: + void OnOverviewModeStarting() override; + void OnOverviewModeEnded() override; + + aura::Window* left_window() { return left_window_; } + aura::Window* right_window() { return right_window_; } + int divider_position() const { return divider_position_; } + State state() const { return state_; } + + private: + friend class SplitViewControllerTest; + + // Ends the split view mode. + void EndSplitView(); + + // Starts/Stops observing |window|. + void StartObserving(aura::Window* window); + void StopObserving(aura::Window* window); + + // Notify observers that the split view state has been changed. + void NotifySplitViewStateChanged(State previous_state, State state); + + // Gets the window bounds according to the separator position. + gfx::Rect GetLeftWindowBoundsInParent(aura::Window* window); + gfx::Rect GetRightWindowBoundsInParent(aura::Window* window); + gfx::Rect GetLeftWindowBoundsInScreen(aura::Window* window); + gfx::Rect GetRightWindowBoundsInScreen(aura::Window* window); + + // The current left/right snapped window. + aura::Window* left_window_ = nullptr; + aura::Window* right_window_ = nullptr; + + // The x position of the divider between |left_window_| and |right_window_| in + // screen coordinates. + int divider_position_ = -1; + + // Current snap state. + State state_ = NO_SNAP; + + // The default snap position. It's decided by the first snapped window. If the + // first window was snapped left, then |default_snap_position_| equals LEFT, + // i.e., all the other windows will open snapped on the right side - and vice + // versa. + SnapPosition default_snap_position_ = LEFT; + + base::ObserverList<Observer> observers_; + + DISALLOW_COPY_AND_ASSIGN(SplitViewController); +}; + +} // namespace ash + +#endif // ASH_WM_SPLITSVIEW_SPLIT_VIEW_CONTROLLER_H_
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc new file mode 100644 index 0000000..d8f2570 --- /dev/null +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -0,0 +1,163 @@ +// 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/wm/splitview/split_view_controller.h" + +#include "ash/shell.h" +#include "ash/test/ash_test_base.h" +#include "ash/wm/window_state.h" +#include "ash/wm/window_util.h" +#include "ash/wm/wm_event.h" +#include "ui/aura/test/test_window_delegate.h" + +namespace ash { + +class SplitViewControllerTest : public test::AshTestBase { + public: + SplitViewControllerTest() {} + ~SplitViewControllerTest() override {} + + aura::Window* CreateWindow(const gfx::Rect& bounds) { + aura::Window* window = + CreateTestWindowInShellWithDelegate(&delegate_, -1, bounds); + return window; + } + + void EndSplitView() { split_view_controller()->EndSplitView(); } + + SplitViewController* split_view_controller() { + return Shell::Get()->split_view_controller(); + } + + private: + aura::test::TestWindowDelegate delegate_; + + DISALLOW_COPY_AND_ASSIGN(SplitViewControllerTest); +}; + +// Tests the basic functionalities. +TEST_F(SplitViewControllerTest, Basic) { + const gfx::Rect bounds(0, 0, 400, 400); + std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); + std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); + + EXPECT_EQ(split_view_controller()->state(), SplitViewController::NO_SNAP); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + EXPECT_EQ(split_view_controller()->state(), + SplitViewController::LEFT_SNAPPED); + EXPECT_EQ(split_view_controller()->left_window(), window1.get()); + EXPECT_NE(split_view_controller()->left_window(), window2.get()); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + EXPECT_EQ(window1->GetBoundsInScreen(), + split_view_controller()->GetSnappedWindowBoundsInScreen( + window1.get(), SplitViewController::LEFT_SNAPPED)); + + split_view_controller()->SnapWindow(window2.get(), + SplitViewController::RIGHT); + EXPECT_EQ(split_view_controller()->state(), + SplitViewController::BOTH_SNAPPED); + EXPECT_EQ(split_view_controller()->right_window(), window2.get()); + EXPECT_NE(split_view_controller()->right_window(), window1.get()); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + EXPECT_EQ(window2->GetBoundsInScreen(), + split_view_controller()->GetSnappedWindowBoundsInScreen( + window2.get(), SplitViewController::RIGHT_SNAPPED)); + + EndSplitView(); + EXPECT_EQ(split_view_controller()->state(), SplitViewController::NO_SNAP); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); +} + +// Tests that the default snapped window is the first window that gets snapped. +TEST_F(SplitViewControllerTest, DefaultSnappedWindow) { + const gfx::Rect bounds(0, 0, 400, 400); + std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); + std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + split_view_controller()->SnapWindow(window2.get(), + SplitViewController::RIGHT); + EXPECT_EQ(window1.get(), split_view_controller()->GetDefaultSnappedWindow()); + + EndSplitView(); + split_view_controller()->SnapWindow(window2.get(), SplitViewController::LEFT); + split_view_controller()->SnapWindow(window1.get(), + SplitViewController::RIGHT); + EXPECT_EQ(window2.get(), split_view_controller()->GetDefaultSnappedWindow()); +} + +// Tests that closing one of the snapped windows exits the split view mode. +TEST_F(SplitViewControllerTest, EndSplitViewUponWindowClose) { + const gfx::Rect bounds(0, 0, 400, 400); + std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); + std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); + + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + split_view_controller()->SnapWindow(window2.get(), + SplitViewController::RIGHT); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + + window1.reset(); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); +} + +// Tests that if one of the snapped window gets minimized / maximized / full- +// screened, the split view mode ends. +TEST_F(SplitViewControllerTest, WindowStateChangeTest) { + const gfx::Rect bounds(0, 0, 400, 400); + std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + + wm::WMEvent minimize_event(wm::WM_EVENT_MINIMIZE); + wm::GetWindowState(window1.get())->OnWMEvent(&minimize_event); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + + wm::WMEvent maximize_event(wm::WM_EVENT_MAXIMIZE); + wm::GetWindowState(window1.get())->OnWMEvent(&maximize_event); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + + wm::WMEvent fullscreen_event(wm::WM_EVENT_FULLSCREEN); + wm::GetWindowState(window1.get())->OnWMEvent(&fullscreen_event); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); +} + +// Tests that if split view mode is active, activate another window will snap +// the window to the non-default side of the screen. +TEST_F(SplitViewControllerTest, WindowActivationTest) { + const gfx::Rect bounds(0, 0, 400, 400); + std::unique_ptr<aura::Window> window1(CreateWindow(bounds)); + std::unique_ptr<aura::Window> window2(CreateWindow(bounds)); + std::unique_ptr<aura::Window> window3(CreateWindow(bounds)); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), false); + + split_view_controller()->SnapWindow(window1.get(), SplitViewController::LEFT); + EXPECT_EQ(split_view_controller()->IsSplitViewModeActive(), true); + EXPECT_EQ(split_view_controller()->left_window(), window1.get()); + EXPECT_EQ(split_view_controller()->state(), + SplitViewController::LEFT_SNAPPED); + + wm::ActivateWindow(window2.get()); + EXPECT_EQ(split_view_controller()->right_window(), window2.get()); + EXPECT_EQ(split_view_controller()->state(), + SplitViewController::BOTH_SNAPPED); + + wm::ActivateWindow(window3.get()); + EXPECT_EQ(split_view_controller()->right_window(), window3.get()); + EXPECT_EQ(split_view_controller()->state(), + SplitViewController::BOTH_SNAPPED); +} + +} // namespace ash
diff --git a/ash/wm/workspace/backdrop_controller.cc b/ash/wm/workspace/backdrop_controller.cc index 2473771..05b6d94 100644 --- a/ash/wm/workspace/backdrop_controller.cc +++ b/ash/wm/workspace/backdrop_controller.cc
@@ -140,6 +140,19 @@ } void BackdropController::OnOverviewModeEnded() { + if (Shell::Get()->IsSplitViewModeActive()) + return; + + force_hidden_ = false; + UpdateBackdrop(); +} + +void BackdropController::OnSplitViewModeStarting() { + force_hidden_ = true; + Hide(); +} + +void BackdropController::OnSplitViewModeEnded() { force_hidden_ = false; UpdateBackdrop(); }
diff --git a/ash/wm/workspace/backdrop_controller.h b/ash/wm/workspace/backdrop_controller.h index 6bc576b..dc28f198 100644 --- a/ash/wm/workspace/backdrop_controller.h +++ b/ash/wm/workspace/backdrop_controller.h
@@ -63,6 +63,8 @@ // ShellObserver: void OnOverviewModeStarting() override; void OnOverviewModeEnded() override; + void OnSplitViewModeStarting() override; + void OnSplitViewModeEnded() override; // AccessibilityObserver: void OnAccessibilityModeChanged(
diff --git a/base/android/jni_generator/jni_registration_generator.py b/base/android/jni_generator/jni_registration_generator.py index a7ede2db..4b51d09 100755 --- a/base/android/jni_generator/jni_registration_generator.py +++ b/base/android/jni_generator/jni_registration_generator.py
@@ -161,19 +161,20 @@ args = arg_parser.parse_args(build_utils.ExpandFileArgs(argv[1:])) args.sources_files = build_utils.ParseGnList(args.sources_files) - if args.sources_files: - java_file_paths = [] - for f in args.sources_files: - # java_file_paths stores each Java file path as a string. - java_file_paths += build_utils.ReadSourcesList(f) - else: + if not args.sources_files: print '\nError: Must specify --sources_files.' return 1 + + java_file_paths = [] + for f in args.sources_files: + # java_file_paths stores each Java file path as a string. + java_file_paths += build_utils.ReadSourcesList(f) output_file = args.output GenerateJNIHeader(java_file_paths, output_file, args) if args.depfile: - build_utils.WriteDepfile(args.depfile, output_file) + build_utils.WriteDepfile(args.depfile, output_file, + args.sources_files + java_file_paths) if __name__ == '__main__':
diff --git a/base/files/file_enumerator_posix.cc b/base/files/file_enumerator_posix.cc index bc5c3cc5..ce1fe40a 100644 --- a/base/files/file_enumerator_posix.cc +++ b/base/files/file_enumerator_posix.cc
@@ -125,7 +125,7 @@ FileInfo dotdot; dotdot.stat_.st_mode = S_IFDIR; dotdot.filename_ = FilePath(".."); - directory_entries_->push_back(dotdot); + directory_entries_.push_back(dotdot); #endif // OS_FUCHSIA current_directory_entry_ = 0;
diff --git a/base/metrics/histogram.cc b/base/metrics/histogram.cc index 51fddbf6..df44085 100644 --- a/base/metrics/histogram.cc +++ b/base/metrics/histogram.cc
@@ -165,6 +165,8 @@ minimum_ = registered_ranges->range(1); maximum_ = registered_ranges->range(bucket_count_ - 1); } + DCHECK_EQ(minimum_, registered_ranges->range(1)); + DCHECK_EQ(maximum_, registered_ranges->range(bucket_count_ - 1)); // Try to create the histogram using a "persistent" allocator. As of // 2016-02-25, the availability of such is controlled by a base::Feature @@ -359,6 +361,18 @@ return inconsistencies; } +Sample Histogram::declared_min() const { + if (bucket_ranges_->bucket_count() < 2) + return -1; + return bucket_ranges_->range(1); +} + +Sample Histogram::declared_max() const { + if (bucket_ranges_->bucket_count() < 2) + return -1; + return bucket_ranges_->range(bucket_ranges_->bucket_count() - 1); +} + Sample Histogram::ranges(uint32_t i) const { return bucket_ranges_->range(i); } @@ -432,9 +446,9 @@ bool Histogram::HasConstructionArguments(Sample expected_minimum, Sample expected_maximum, uint32_t expected_bucket_count) const { - return ((expected_minimum == declared_min_) && - (expected_maximum == declared_max_) && - (expected_bucket_count == bucket_count())); + return (expected_bucket_count == bucket_count() && + expected_minimum == declared_min() && + expected_maximum == declared_max()); } void Histogram::Add(int value) { @@ -463,7 +477,10 @@ } std::unique_ptr<HistogramSamples> Histogram::SnapshotDelta() { +#if DCHECK_IS_ON() DCHECK(!final_delta_created_); +#endif + // The code below has subtle thread-safety guarantees! All changes to // the underlying SampleVectors use atomic integer operations, which guarantee // eventual consistency, but do not guarantee full synchronization between @@ -484,8 +501,10 @@ } std::unique_ptr<HistogramSamples> Histogram::SnapshotFinalDelta() const { +#if DCHECK_IS_ON() DCHECK(!final_delta_created_); final_delta_created_ = true; +#endif return SnapshotUnloggedSamples(); } @@ -520,14 +539,12 @@ pickle->WriteUInt32(bucket_ranges()->checksum()); } +// TODO(bcwhite): Remove minimum/maximum parameters from here and call chain. Histogram::Histogram(const std::string& name, Sample minimum, Sample maximum, const BucketRanges* ranges) - : HistogramBase(name), - bucket_ranges_(ranges), - declared_min_(minimum), - declared_max_(maximum) { + : HistogramBase(name), bucket_ranges_(ranges) { // TODO(bcwhite): Make this a DCHECK once crbug/734049 is resolved. CHECK(ranges) << name << ": " << minimum << "-" << maximum; unlogged_samples_.reset(new SampleVector(HashMetricName(name), ranges)); @@ -542,10 +559,7 @@ const DelayedPersistentAllocation& logged_counts, HistogramSamples::Metadata* meta, HistogramSamples::Metadata* logged_meta) - : HistogramBase(name), - bucket_ranges_(ranges), - declared_min_(minimum), - declared_max_(maximum) { + : HistogramBase(name), bucket_ranges_(ranges) { // TODO(bcwhite): Make this a DCHECK once crbug/734049 is resolved. CHECK(ranges) << name << ": " << minimum << "-" << maximum; unlogged_samples_.reset(
diff --git a/base/metrics/histogram.h b/base/metrics/histogram.h index 78ab116..6e5821d 100644 --- a/base/metrics/histogram.h +++ b/base/metrics/histogram.h
@@ -173,8 +173,8 @@ //---------------------------------------------------------------------------- // Accessors for factory construction, serialization and testing. //---------------------------------------------------------------------------- - Sample declared_min() const { return declared_min_; } - Sample declared_max() const { return declared_max_; } + Sample declared_min() const; + Sample declared_max() const; virtual Sample ranges(uint32_t i) const; virtual uint32_t bucket_count() const; const BucketRanges* bucket_ranges() const { return bucket_ranges_; } @@ -305,18 +305,17 @@ // Does not own this object. Should get from StatisticsRecorder. const BucketRanges* bucket_ranges_; - Sample declared_min_; // Less than this goes into the first bucket. - Sample declared_max_; // Over this goes into the last bucket. - // Samples that have not yet been logged with SnapshotDelta(). std::unique_ptr<HistogramSamples> unlogged_samples_; // Accumulation of all samples that have been logged with SnapshotDelta(). std::unique_ptr<HistogramSamples> logged_samples_; +#if DCHECK_IS_ON() // Don't waste memory if it won't be used. // Flag to indicate if PrepareFinalDelta has been previously called. It is // used to DCHECK that a final delta is not created multiple times. mutable bool final_delta_created_ = false; +#endif DISALLOW_COPY_AND_ASSIGN(Histogram); };
diff --git a/base/timer/timer.h b/base/timer/timer.h index 651ba39d..a531fdd9 100644 --- a/base/timer/timer.h +++ b/base/timer/timer.h
@@ -41,11 +41,17 @@ // // These APIs are not thread safe. All methods must be called from the same // sequence (not necessarily the construction sequence), except for the -// destructor and SetTaskRunner() which may be called from any sequence when the -// timer is not running (i.e. when Start() has never been called or Stop() has -// been called since the last Start()). By default, the scheduled tasks will be -// run on the same sequence that the Timer was *started on*, but this can be -// changed *prior* to Start() via SetTaskRunner(). +// destructor and SetTaskRunner(). +// - The destructor may be called from any sequence when the timer is not +// running and there is no scheduled task active, i.e. when Start() has never +// been called or after AbandonAndStop() has been called. +// - SetTaskRunner() may be called from any sequence when the timer is not +// running, i.e. when Start() has never been called or Stop() has been called +// since the last Start(). +// +// By default, the scheduled tasks will be run on the same sequence that the +// Timer was *started on*, but this can be changed *prior* to Start() via +// SetTaskRunner(). #ifndef BASE_TIMER_TIMER_H_ #define BASE_TIMER_TIMER_H_ @@ -126,6 +132,14 @@ // is not running. virtual void Stop(); + // Stop running task (if any) and abandon scheduled task (if any). + void AbandonAndStop() { + AbandonScheduledTask(); + + Stop(); + // No more member accesses here: |this| could be deleted at this point. + } + // Call this method to reset the timer delay. The |user_task_| must be set. If // the timer is not running, this will start it by posting a task. virtual void Reset(); @@ -166,14 +180,6 @@ // Called by BaseTimerTaskInternal when the delayed task fires. void RunScheduledTask(); - // Stop running task (if any) and abandon scheduled task (if any). - void AbandonAndStop() { - AbandonScheduledTask(); - - Stop(); - // No more member accesses here: |this| could be deleted at this point. - } - // When non-null, the |scheduled_task_| was posted to call RunScheduledTask() // at |scheduled_run_time_|. BaseTimerTaskInternal* scheduled_task_;
diff --git a/build/android/gyp/package_resources.py b/build/android/gyp/package_resources.py index a8cfcc7..c2ba889 100755 --- a/build/android/gyp/package_resources.py +++ b/build/android/gyp/package_resources.py
@@ -13,10 +13,12 @@ """ # pylint: enable=C0301 +import multiprocessing.pool import optparse import os import re import shutil +import subprocess import sys import zipfile @@ -88,6 +90,10 @@ } +_PNG_TO_WEBP_ARGS = [ + '-mt', '-quiet', '-m', '6', '-q', '100', '-lossless', '-o'] + + def _ParseArgs(args): """Parses command line options. @@ -143,6 +149,10 @@ default='[]', help='GN list of globs that say which xxxhdpi images to ' 'include even when --exclude-xxxhdpi is set.') + parser.add_option('--png-to-webp', action='store_true', + help='Convert png files to webp format.') + parser.add_option('--webp-binary', default='', + help='Path to the cwebp binary.') options, positional_args = parser.parse_args(args) @@ -336,18 +346,41 @@ _ResourceNameFromPath(path) not in non_xxxhdpi_drawables) +def _ConvertToWebP(webp_binary, png_files): + pool = multiprocessing.pool.ThreadPool(10) + def convert_image(png_path): + root = os.path.splitext(png_path)[0] + webp_path = root + '.webp' + args = [webp_binary, png_path] + _PNG_TO_WEBP_ARGS + [webp_path] + subprocess.check_call(args) + os.remove(png_path) + # Android requires pngs for 9-patch images. + pool.map(convert_image, [f for f in png_files if not f.endswith('.9.png')]) + pool.close() + pool.join() + + def _OnStaleMd5(package_command, options): with build_utils.TempDir() as temp_dir: if options.resource_zips: dep_zips = options.resource_zips extract_predicate = _CreateExtractPredicate( dep_zips, options.exclude_xxxhdpi, options.xxxhdpi_whitelist) + png_paths = [] + package_subdirs = [] for z in dep_zips: subdir = os.path.join(temp_dir, os.path.basename(z)) if os.path.exists(subdir): raise Exception('Resource zip name conflict: ' + os.path.basename(z)) - if build_utils.ExtractAll(z, path=subdir, predicate=extract_predicate): - package_command += PackageArgsForExtractedZip(subdir) + extracted_files = build_utils.ExtractAll( + z, path=subdir, predicate=extract_predicate) + if extracted_files: + package_subdirs.append(subdir) + png_paths.extend(f for f in extracted_files if f.endswith('.png')) + if png_paths and options.png_to_webp: + _ConvertToWebP(options.webp_binary, png_paths) + for subdir in package_subdirs: + package_command += PackageArgsForExtractedZip(subdir) build_utils.CheckOutput( package_command, print_stdout=False, print_stderr=False) @@ -379,6 +412,9 @@ input_strings = [options.exclude_xxxhdpi] + options.xxxhdpi_whitelist input_strings.extend(package_command) + if options.png_to_webp: + # This is necessary to ensure conversion if the option is toggled. + input_strings.extend("png_to_webp") # The md5_check.py doesn't count file path in md5 intentionally, # in order to repackage resources when assets' name changed, we need
diff --git a/build/android/pylib/instrumentation/instrumentation_test_instance.py b/build/android/pylib/instrumentation/instrumentation_test_instance.py index c1253d9..0b3fbccc 100644 --- a/build/android/pylib/instrumentation/instrumentation_test_instance.py +++ b/build/android/pylib/instrumentation/instrumentation_test_instance.py
@@ -4,7 +4,6 @@ import collections import copy -import json import logging import os import pickle @@ -21,6 +20,7 @@ from pylib.instrumentation import instrumentation_parser from pylib.utils import dexdump from pylib.utils import proguard +from pylib.utils import shared_preference_utils with host_paths.SysPath(host_paths.BUILD_COMMON_PATH): import unittest_util # pylint: disable=import-error @@ -687,21 +687,8 @@ if not isinstance(args.shared_prefs_file, str): logging.warning("Given non-string for a filepath") return - - # json.load() loads strings as unicode, which causes issues when trying - # to edit string values in preference files, so convert to Python strings - def unicode_to_str(data): - if isinstance(data, dict): - return {unicode_to_str(key): unicode_to_str(value) - for key, value in data.iteritems()} - elif isinstance(data, list): - return [unicode_to_str(element) for element in data] - elif isinstance(data, unicode): - return data.encode('utf-8') - return data - - with open(args.shared_prefs_file) as prefs_file: - self._edit_shared_prefs = unicode_to_str(json.load(prefs_file)) + self._edit_shared_prefs = shared_preference_utils.ExtractSettingsFromJson( + args.shared_prefs_file) @property def additional_apks(self):
diff --git a/build/android/pylib/local/device/local_device_instrumentation_test_run.py b/build/android/pylib/local/device/local_device_instrumentation_test_run.py index 8f2b2e7..7e92909 100644 --- a/build/android/pylib/local/device/local_device_instrumentation_test_run.py +++ b/build/android/pylib/local/device/local_device_instrumentation_test_run.py
@@ -13,7 +13,6 @@ from devil.android import device_errors from devil.android import device_temp_file from devil.android import flag_changer -from devil.android.sdk import shared_prefs from devil.utils import reraiser_thread from pylib import valgrind_tools from pylib.android import logdog_logcat_monitor @@ -24,6 +23,7 @@ from pylib.local.device import local_device_test_run from pylib.utils import google_storage_helper from pylib.utils import logdog_helper +from pylib.utils import shared_preference_utils from py_trace_event import trace_event from py_utils import contextlib_ext from py_utils import tempfile_ext @@ -179,30 +179,11 @@ dev.RunShellCommand(['am', 'set-debug-app', '--persistent', self._test_instance.package_info.package], check_return=True) + @trace_event.traced def edit_shared_prefs(): - for pref in self._test_instance.edit_shared_prefs: - prefs = shared_prefs.SharedPrefs(dev, pref['package'], - pref['filename']) - prefs.Load() - for key in pref.get('remove', []): - try: - prefs.Remove(key) - except KeyError: - logging.warning("Attempted to remove non-existent key %s", key) - for key, value in pref.get('set', {}).iteritems(): - if isinstance(value, bool): - prefs.SetBoolean(key, value) - elif isinstance(value, basestring): - prefs.SetString(key, value) - elif isinstance(value, long) or isinstance(value, int): - prefs.SetLong(key, value) - elif isinstance(value, list): - prefs.SetStringSet(key, value) - else: - raise ValueError("Given invalid value type %s for key %s" % ( - str(type(value)), key)) - prefs.Commit() + shared_preference_utils.ApplySharedPreferenceSettings( + dev, self._test_instance.edit_shared_prefs) @trace_event.traced def push_test_data():
diff --git a/build/android/pylib/utils/shared_preference_utils.py b/build/android/pylib/utils/shared_preference_utils.py new file mode 100644 index 0000000..0541be4 --- /dev/null +++ b/build/android/pylib/utils/shared_preference_utils.py
@@ -0,0 +1,88 @@ +# 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. + +"""Utility functions for modifying an app's settings file using JSON.""" + +import json +import logging + +from devil.android.sdk import shared_prefs + + +def ExtractSettingsFromJson(filepath): + """Extracts the settings data from the given JSON file. + + Args: + filepath: The path to the JSON file to read. + + Return: + The data read from the JSON file with strings converted to Python strings. + """ + # json.load() loads strings as unicode, which causes issues when trying + # to edit string values in preference files, so convert to Python strings + def unicode_to_str(data): + if isinstance(data, dict): + return {unicode_to_str(key): unicode_to_str(value) + for key, value in data.iteritems()} + elif isinstance(data, list): + return [unicode_to_str(element) for element in data] + elif isinstance(data, unicode): + return data.encode('utf-8') + return data + + with open(filepath) as prefs_file: + return unicode_to_str(json.load(prefs_file)) + + +def ApplySharedPreferenceSettings(device, settings): + """Applies the given app settings to the given device. + + Modifies an installed app's settings by modifying its shared preference + settings file. Provided settings data must be a list of settings dictionaries, + where dictionaries are in the following format: + { + "package": "com.example.package", + "filename": "AppSettingsFile.xml", + "set": { + "SomeBoolToSet": true, + "SomeStringToSet": "StringValue", + }, + "remove": [ + "list", + "of", + "keys", + "to", + "remove", + ] + } + + Example JSON files that can be read with ExtractSettingsFromJson and passed to + this function are in //chrome/android/shared_preference_files/test/. + + Args: + device: The devil DeviceUtils object for the device the settings will be + applied to. + settings: A list of settings dictionaries to apply. + """ + for pref in settings: + prefs = shared_prefs.SharedPrefs(device, pref['package'], pref['filename']) + prefs.Load() + for key in pref.get('remove', []): + try: + prefs.Remove(key) + except KeyError: + logging.warning("Attempted to remove non-existent key %s", key) + for key, value in pref.get('set', {}).iteritems(): + if isinstance(value, bool): + prefs.SetBoolean(key, value) + elif isinstance(value, basestring): + prefs.SetString(key, value) + elif isinstance(value, long) or isinstance(value, int): + prefs.SetLong(key, value) + elif isinstance(value, list): + prefs.SetStringSet(key, value) + else: + raise ValueError("Given invalid value type %s for key %s" % ( + str(type(value)), key)) + prefs.Commit()
diff --git a/build/android/test_runner.pydeps b/build/android/test_runner.pydeps index bdf0596..14d58e8 100644 --- a/build/android/test_runner.pydeps +++ b/build/android/test_runner.pydeps
@@ -210,6 +210,7 @@ pylib/utils/logging_utils.py pylib/utils/proguard.py pylib/utils/repo_utils.py +pylib/utils/shared_preference_utils.py pylib/valgrind_tools.py test_runner.py tombstones.py
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 611fda7..3714b1f 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -1710,6 +1710,16 @@ invoker.extensions_to_not_compress, ] } + if (defined(invoker.png_to_webp) && invoker.png_to_webp) { + _webp_target = "//third_party/libwebp:cwebp($host_toolchain)" + deps += [ _webp_target ] + args += [ + "--png-to-webp", + "--webp-binary", + rebase_path(get_label_info(_webp_target, "root_out_dir") + "/cwebp", + root_build_dir), + ] + } if (defined(invoker.exclude_xxxhdpi) && invoker.exclude_xxxhdpi) { args += [ "--exclude-xxxhdpi" ] if (defined(invoker.xxxhdpi_whitelist)) { @@ -1726,6 +1736,7 @@ "aapt_locale_whitelist", "alternative_android_sdk_jar", "android_aapt_path", + "png_to_webp", "exclude_xxxhdpi", "extensions_to_not_compress", "xxxhdpi_whitelist", @@ -1777,6 +1788,7 @@ "aapt_locale_whitelist", "alternative_android_sdk_jar", "android_aapt_path", + "png_to_webp", "exclude_xxxhdpi", "extensions_to_not_compress", "xxxhdpi_whitelist",
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index ceffd06..0b0ce452 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -1522,6 +1522,8 @@ # android_manifest: Path to AndroidManifest.xml. # android_manifest_dep: Target that generates AndroidManifest (if applicable) # chromium_code: If true, extra analysis warning/errors will be enabled. + # png_to_webp: If true, pngs (with the exception of 9-patch) are + # converted to webp during resource packaging. # dist_ijar_path: Path to create "${target_name}_dist_ijar" target # (used by instrumentation_test_apk). # data_deps: List of dependencies needed at runtime. These will be built but @@ -2225,6 +2227,7 @@ "alternative_android_sdk_jar", "android_aapt_path", "app_as_shared_lib", + "png_to_webp", "deps", "exclude_xxxhdpi", "extensions_to_not_compress",
diff --git a/build/config/c++/BUILD.gn b/build/config/c++/BUILD.gn index 21316ba..baad310d 100644 --- a/build/config/c++/BUILD.gn +++ b/build/config/c++/BUILD.gn
@@ -8,6 +8,12 @@ if (use_custom_libcxx) { prefix = "//buildtools/third_party" include = "trunk/include" + if (!is_clang) { + # Gcc has a built-in abs() definition with default visibility. + # If it was not disabled, it would conflict with libc++'s abs() + # with hidden visibility. + cflags = [ "-fno-builtin-abs" ] + } cflags_cc = [ "-nostdinc++", "-isystem" + rebase_path("$prefix/libc++/$include", root_build_dir),
diff --git a/build/config/mac/BuildInfo.plist b/build/config/mac/BuildInfo.plist index b0856e35..d32bf2ea7 100644 --- a/build/config/mac/BuildInfo.plist +++ b/build/config/mac/BuildInfo.plist
@@ -14,13 +14,5 @@ <string>${XCODE_VERSION}</string> <key>DTXcodeBuild</key> <string>${XCODE_BUILD}</string> - <key>CFBundleShortVersionString</key> - <string>${VERSION}</string> - <key>CFBundleVersion</key> - <string>${VERSION_BUILD}</string> - <key>CFBundleIdentifier</key> - <string>org.chromium.${PRODUCT_NAME:rfc1034identifier}</string> - <key>SCM_REVISION</key> - <string>${COMMIT_HASH}</string> </dict> </plist>
diff --git a/build/config/mac/plist_util.py b/build/config/mac/plist_util.py index 0928fa13..dd6fe4c 100644 --- a/build/config/mac/plist_util.py +++ b/build/config/mac/plist_util.py
@@ -21,25 +21,13 @@ IDENT_RE = re.compile(r'[_/\s]') -def InterpolateList(values, substitutions): - """Interpolates variable references into |value| using |substitutions|. +class SubstitutionError(Exception): + def __init__(self, key): + super(SubstitutionError, self).__init__() + self.key = key - Inputs: - values: a list of values - substitutions: a mapping of variable names to values - - Returns: - A new list of values with all variables references ${VARIABLE} replaced - by their value in |substitutions| or None if any of the variable has no - subsitution. - """ - result = [] - for value in values: - interpolated = InterpolateValue(value, substitutions) - if interpolated is None: - return None - result.append(interpolated) - return result + def __str__(self): + return "SubstitutionError: {}".format(self.key) def InterpolateString(value, substitutions): @@ -51,29 +39,28 @@ Returns: A new string with all variables references ${VARIABLES} replaced by their - value in |substitutions| or None if any of the variable has no substitution. + value in |substitutions|. Raises SubstitutionError if a variable has no + substitution. """ - result = value - for match in reversed(list(SUBST_RE.finditer(value))): + def repl(match): variable = match.group('id') if variable not in substitutions: - return None + raise SubstitutionError(variable) # Some values need to be identifier and thus the variables references may # contains :modifier attributes to indicate how they should be converted # to identifiers ("identifier" replaces all invalid characters by '_' and # "rfc1034identifier" replaces them by "-" to make valid URI too). modifier = match.group('modifier') if modifier == ':identifier': - interpolated = IDENT_RE.sub('_', substitutions[variable]) + return IDENT_RE.sub('_', substitutions[variable]) elif modifier == ':rfc1034identifier': - interpolated = IDENT_RE.sub('-', substitutions[variable]) + return IDENT_RE.sub('-', substitutions[variable]) else: - interpolated = substitutions[variable] - result = result[:match.start()] + interpolated + result[match.end():] - return result + return substitutions[variable] + return SUBST_RE.sub(repl, value) -def InterpolateValue(value, substitutions): +def Interpolate(value, substitutions): """Interpolates variable references into |value| using |substitutions|. Inputs: @@ -82,38 +69,18 @@ Returns: A new value with all variables references ${VARIABLES} replaced by their - value in |substitutions| or None if any of the variable has no substitution. + value in |substitutions|. Raises SubstitutionError if a variable has no + substitution. """ if isinstance(value, dict): - return Interpolate(value, substitutions) + return {k: Interpolate(v, substitutions) for k, v in value.iteritems()} if isinstance(value, list): - return InterpolateList(value, substitutions) + return [Interpolate(v, substitutions) for v in value] if isinstance(value, str): return InterpolateString(value, substitutions) return value -def Interpolate(plist, substitutions): - """Interpolates variable references into |value| using |substitutions|. - - Inputs: - plist: a dictionary representing a Property List (.plist) file - substitutions: a mapping of variable names to values - - Returns: - A new plist with all variables references ${VARIABLES} replaced by their - value in |substitutions|. All values that contains references with no - substitutions will be removed and the corresponding key will be cleared - from the plist (not recursively). - """ - result = {} - for key in plist: - value = InterpolateValue(plist[key], substitutions) - if value is not None: - result[key] = value - return result - - def LoadPList(path): """Loads Plist at |path| and returns it as a dictionary.""" fd, name = tempfile.mkstemp() @@ -153,19 +120,12 @@ recursively, otherwise |plist2| value is used. If values are list, they are concatenated. """ - if not isinstance(plist1, dict) or not isinstance(plist2, dict): - if plist2 is not None: - return plist2 - else: - return plist1 - result = {} - for key in set(plist1) | set(plist2): - if key in plist2: - value = plist2[key] - else: - value = plist1[key] + result = plist1.copy() + for key, value in plist2.iteritems(): if isinstance(value, dict): - value = MergePList(plist1.get(key, None), plist2.get(key, None)) + old_value = result.get(key) + if isinstance(old_value, dict): + value = MergePList(old_value, value) if isinstance(value, list): value = plist1.get(key, []) + plist2.get(key, []) result[key] = value
diff --git a/cc/surfaces/BUILD.gn b/cc/surfaces/BUILD.gn index 84dc9c1..a01581e 100644 --- a/cc/surfaces/BUILD.gn +++ b/cc/surfaces/BUILD.gn
@@ -62,6 +62,7 @@ "surface.h", "surface_aggregator.cc", "surface_aggregator.h", + "surface_client.h", "surface_deadline_observer.h", "surface_dependency_deadline.cc", "surface_dependency_deadline.h",
diff --git a/cc/surfaces/compositor_frame_sink_support.cc b/cc/surfaces/compositor_frame_sink_support.cc index ce83947..907a0e8 100644 --- a/cc/surfaces/compositor_frame_sink_support.cc +++ b/cc/surfaces/compositor_frame_sink_support.cc
@@ -25,11 +25,11 @@ const FrameSinkId& frame_sink_id, bool is_root, bool handles_frame_sink_id_invalidation, - bool needs_sync_points) { + bool needs_sync_tokens) { std::unique_ptr<CompositorFrameSinkSupport> support = base::WrapUnique(new CompositorFrameSinkSupport( client, frame_sink_id, is_root, handles_frame_sink_id_invalidation, - needs_sync_points)); + needs_sync_tokens)); support->Init(surface_manager); return support; } @@ -53,6 +53,40 @@ surface_manager_->InvalidateFrameSinkId(frame_sink_id_); } +void CompositorFrameSinkSupport::OnSurfaceActivated(Surface* surface) { + DCHECK(surface->HasActiveFrame()); + const CompositorFrame& frame = surface->GetActiveFrame(); + if (!seen_first_frame_activation_) { + // SurfaceCreated only applies for the first Surface activation. + seen_first_frame_activation_ = true; + + gfx::Size frame_size = frame.render_pass_list.back()->output_rect.size(); + surface_manager_->SurfaceCreated(SurfaceInfo( + surface->surface_id(), frame.metadata.device_scale_factor, frame_size)); + } + // Fire SurfaceCreated first so that a temporary reference is added before it + // is potentially transformed into a real reference by the client. + DCHECK(surface->active_referenced_surfaces()); + UpdateSurfaceReferences(surface->surface_id().local_surface_id(), + *surface->active_referenced_surfaces()); + if (!surface_manager_->SurfaceModified(surface->surface_id(), + frame.metadata.begin_frame_ack)) { + TRACE_EVENT_INSTANT0("cc", "Damage not visible.", TRACE_EVENT_SCOPE_THREAD); + surface->RunDrawCallback(); + } + surface_manager_->SurfaceActivated(surface); +} + +void CompositorFrameSinkSupport::RefResources( + const std::vector<TransferableResource>& resources) { + surface_resource_holder_.RefResources(resources); +} + +void CompositorFrameSinkSupport::UnrefResources( + const std::vector<ReturnedResource>& resources) { + surface_resource_holder_.UnrefResources(resources); +} + void CompositorFrameSinkSupport::ReturnResources( const std::vector<ReturnedResource>& resources) { if (resources.empty()) @@ -66,6 +100,11 @@ std::back_inserter(surface_returned_resources_)); } +void CompositorFrameSinkSupport::ReceiveFromChild( + const std::vector<TransferableResource>& resources) { + surface_resource_holder_.ReceiveFromChild(resources); +} + void CompositorFrameSinkSupport::SetBeginFrameSource( BeginFrameSource* begin_frame_source) { if (begin_frame_source_ && added_frame_observer_) { @@ -252,32 +291,17 @@ surface_manager_->AssignTemporaryReference(surface_id, frame_sink_id_); } -void CompositorFrameSinkSupport::ReceiveFromChild( - const std::vector<TransferableResource>& resources) { - surface_resource_holder_.ReceiveFromChild(resources); -} - -void CompositorFrameSinkSupport::RefResources( - const std::vector<TransferableResource>& resources) { - surface_resource_holder_.RefResources(resources); -} - -void CompositorFrameSinkSupport::UnrefResources( - const std::vector<ReturnedResource>& resources) { - surface_resource_holder_.UnrefResources(resources); -} - CompositorFrameSinkSupport::CompositorFrameSinkSupport( CompositorFrameSinkSupportClient* client, const FrameSinkId& frame_sink_id, bool is_root, bool handles_frame_sink_id_invalidation, - bool needs_sync_points) + bool needs_sync_tokens) : client_(client), frame_sink_id_(frame_sink_id), surface_resource_holder_(this), is_root_(is_root), - needs_sync_points_(needs_sync_points), + needs_sync_tokens_(needs_sync_tokens), handles_frame_sink_id_invalidation_(handles_frame_sink_id_invalidation), weak_factory_(this) {} @@ -305,30 +329,6 @@ void CompositorFrameSinkSupport::OnBeginFrameSourcePausedChanged(bool paused) {} -void CompositorFrameSinkSupport::OnSurfaceActivated(Surface* surface) { - DCHECK(surface->HasActiveFrame()); - const CompositorFrame& frame = surface->GetActiveFrame(); - if (!seen_first_frame_activation_) { - // SurfaceCreated only applies for the first Surface activation. - seen_first_frame_activation_ = true; - - gfx::Size frame_size = frame.render_pass_list.back()->output_rect.size(); - surface_manager_->SurfaceCreated(SurfaceInfo( - surface->surface_id(), frame.metadata.device_scale_factor, frame_size)); - } - // Fire SurfaceCreated first so that a temporary reference is added before it - // is potentially transformed into a real reference by the client. - DCHECK(surface->active_referenced_surfaces()); - UpdateSurfaceReferences(surface->surface_id().local_surface_id(), - *surface->active_referenced_surfaces()); - if (!surface_manager_->SurfaceModified(surface->surface_id(), - frame.metadata.begin_frame_ack)) { - TRACE_EVENT_INSTANT0("cc", "Damage not visible.", TRACE_EVENT_SCOPE_THREAD); - surface->RunDrawCallback(); - } - surface_manager_->SurfaceActivated(surface); -} - void CompositorFrameSinkSupport::UpdateNeedsBeginFramesInternal() { if (!begin_frame_source_) return; @@ -347,7 +347,7 @@ const SurfaceInfo& surface_info) { seen_first_frame_activation_ = false; return surface_manager_->CreateSurface(weak_factory_.GetWeakPtr(), - surface_info); + surface_info, needs_sync_tokens_); } void CompositorFrameSinkSupport::RequestCopyOfSurface( @@ -356,7 +356,6 @@ return; Surface* current_surface = surface_manager_->GetSurfaceForId(current_surface_id_); - DCHECK_EQ(this, current_surface->compositor_frame_sink_support().get()); current_surface->RequestCopyOfOutput(std::move(copy_request)); BeginFrameAck ack; ack.has_damage = true;
diff --git a/cc/surfaces/compositor_frame_sink_support.h b/cc/surfaces/compositor_frame_sink_support.h index 6b84d16..6977020 100644 --- a/cc/surfaces/compositor_frame_sink_support.h +++ b/cc/surfaces/compositor_frame_sink_support.h
@@ -15,6 +15,7 @@ #include "cc/scheduler/begin_frame_source.h" #include "cc/surfaces/frame_sink_manager_client.h" #include "cc/surfaces/referenced_surface_tracker.h" +#include "cc/surfaces/surface_client.h" #include "cc/surfaces/surface_info.h" #include "cc/surfaces/surface_resource_holder.h" #include "cc/surfaces/surface_resource_holder_client.h" @@ -29,7 +30,8 @@ class CC_SURFACES_EXPORT CompositorFrameSinkSupport : public BeginFrameObserver, public SurfaceResourceHolderClient, - public FrameSinkManagerClient { + public FrameSinkManagerClient, + public SurfaceClient { public: static std::unique_ptr<CompositorFrameSinkSupport> Create( CompositorFrameSinkSupportClient* client, @@ -37,17 +39,22 @@ const FrameSinkId& frame_sink_id, bool is_root, bool handles_frame_sink_id_invalidation, - bool needs_sync_points); + bool needs_sync_tokens); ~CompositorFrameSinkSupport() override; const FrameSinkId& frame_sink_id() const { return frame_sink_id_; } SurfaceManager* surface_manager() { return surface_manager_; } - bool needs_sync_points() { return needs_sync_points_; } - // SurfaceResourceHolderClient implementation. + // SurfaceClient implementation. + void OnSurfaceActivated(Surface* surface) override; + void RefResources( + const std::vector<TransferableResource>& resources) override; + void UnrefResources(const std::vector<ReturnedResource>& resources) override; void ReturnResources(const std::vector<ReturnedResource>& resources) override; + void ReceiveFromChild( + const std::vector<TransferableResource>& resources) override; // FrameSinkManagerClient implementation. void SetBeginFrameSource(BeginFrameSource* begin_frame_source) override; @@ -60,12 +67,6 @@ void RequestCopyOfSurface(std::unique_ptr<CopyOutputRequest> request); void ClaimTemporaryReference(const SurfaceId& surface_id); - // TODO(staraz): Move the following 3 methods to private. - void ReceiveFromChild(const std::vector<TransferableResource>& resources); - void RefResources(const std::vector<TransferableResource>& resources); - void UnrefResources(const std::vector<ReturnedResource>& resources); - - void OnSurfaceActivated(Surface* surface); Surface* GetCurrentSurfaceForTesting(); @@ -74,7 +75,7 @@ const FrameSinkId& frame_sink_id, bool is_root, bool handles_frame_sink_id_invalidation, - bool needs_sync_points); + bool needs_sync_tokens); void Init(SurfaceManager* surface_manager); @@ -134,7 +135,7 @@ bool added_frame_observer_ = false; const bool is_root_; - const bool needs_sync_points_; + const bool needs_sync_tokens_; bool seen_first_frame_activation_ = false; // TODO(staraz): Remove this flag once ui::Compositor no longer needs to call
diff --git a/cc/surfaces/display.cc b/cc/surfaces/display.cc index a9c5358e..ead51b6 100644 --- a/cc/surfaces/display.cc +++ b/cc/surfaces/display.cc
@@ -340,9 +340,15 @@ if (have_damage && !size_matches) aggregator_->SetFullDamageForSurface(current_surface_id_); TRACE_EVENT_INSTANT0("cc", "Swap skipped.", TRACE_EVENT_SCOPE_THREAD); - stored_latency_info_.insert(stored_latency_info_.end(), - frame.metadata.latency_info.begin(), - frame.metadata.latency_info.end()); + + // Do not store more that the allowed size. + if (ui::LatencyInfo::Verify(frame.metadata.latency_info, + "Display::DrawAndSwap")) { + stored_latency_info_.insert(stored_latency_info_.end(), + frame.metadata.latency_info.begin(), + frame.metadata.latency_info.end()); + } + if (scheduler_) { scheduler_->DidSwapBuffers(); scheduler_->DidReceiveSwapBuffersAck();
diff --git a/cc/surfaces/display.h b/cc/surfaces/display.h index b96abb6..428b241 100644 --- a/cc/surfaces/display.h +++ b/cc/surfaces/display.h
@@ -87,6 +87,9 @@ bool has_scheduler() const { return !!scheduler_; } DirectRenderer* renderer_for_testing() const { return renderer_.get(); } + size_t stored_latency_info_size_for_testing() const { + return stored_latency_info_.size(); + } void ForceImmediateDrawAndSwapIfPossible();
diff --git a/cc/surfaces/display_unittest.cc b/cc/surfaces/display_unittest.cc index 4bd0f4e..5b16888ce 100644 --- a/cc/surfaces/display_unittest.cc +++ b/cc/surfaces/display_unittest.cc
@@ -435,6 +435,65 @@ TearDownDisplay(); } +// Check LatencyInfo storage is cleaned up if it exceeds the limit. +TEST_F(DisplayTest, MaxLatencyInfoCap) { + RendererSettings settings; + settings.partial_swap_enabled = true; + settings.finish_rendering_on_resize = true; + SetUpDisplay(settings, nullptr); + gfx::ColorSpace color_space_1 = gfx::ColorSpace::CreateXYZD50(); + gfx::ColorSpace color_space_2 = gfx::ColorSpace::CreateSCRGBLinear(); + + StubDisplayClient client; + display_->Initialize(&client, &manager_); + display_->SetColorSpace(color_space_1, color_space_1); + + LocalSurfaceId local_surface_id(id_allocator_.GenerateId()); + display_->SetLocalSurfaceId(local_surface_id, 1.f); + + scheduler_->ResetDamageForTest(); + display_->Resize(gfx::Size(100, 100)); + + RenderPassList pass_list; + std::unique_ptr<RenderPass> pass = RenderPass::Create(); + pass->output_rect = gfx::Rect(0, 0, 100, 100); + pass->damage_rect = gfx::Rect(10, 10, 1, 1); + pass->id = 1u; + pass_list.push_back(std::move(pass)); + + scheduler_->ResetDamageForTest(); + SubmitCompositorFrame(&pass_list, local_surface_id); + + display_->DrawAndSwap(); + + // This is the same as LatencyInfo::kMaxLatencyInfoNumber. + const size_t max_latency_info_count = 100; + for (size_t i = 0; i <= max_latency_info_count; ++i) { + pass = RenderPass::Create(); + pass->output_rect = gfx::Rect(0, 0, 100, 100); + pass->damage_rect = gfx::Rect(10, 10, 0, 0); + pass->id = 1u; + + pass_list.push_back(std::move(pass)); + scheduler_->ResetDamageForTest(); + + CompositorFrame frame = test::MakeCompositorFrame(); + pass_list.swap(frame.render_pass_list); + frame.metadata.latency_info.push_back(ui::LatencyInfo()); + + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); + + display_->DrawAndSwap(); + + if (i < max_latency_info_count) + EXPECT_EQ(i + 1, display_->stored_latency_info_size_for_testing()); + else + EXPECT_EQ(0u, display_->stored_latency_info_size_for_testing()); + } + + TearDownDisplay(); +} + class MockedContext : public TestWebGraphicsContext3D { public: MOCK_METHOD0(shallowFinishCHROMIUM, void());
diff --git a/cc/surfaces/surface.cc b/cc/surfaces/surface.cc index 8703b8a1..29c1be3 100644 --- a/cc/surfaces/surface.cc +++ b/cc/surfaces/surface.cc
@@ -11,25 +11,32 @@ #include "base/stl_util.h" #include "cc/output/copy_output_request.h" -#include "cc/surfaces/compositor_frame_sink_support.h" #include "cc/surfaces/local_surface_id_allocator.h" +#include "cc/surfaces/surface_client.h" #include "cc/surfaces/surface_manager.h" #include "cc/surfaces/surface_resource_holder_client.h" namespace cc { +namespace { // The frame index starts at 2 so that empty frames will be treated as // completely damaged the first time they're drawn from. -static const int kFrameIndexStart = 2; +constexpr int kFrameIndexStart = 2; +} // namespace -Surface::Surface( - const SurfaceInfo& surface_info, - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support) +Surface::Surface(const SurfaceInfo& surface_info, + SurfaceManager* surface_manager, + base::WeakPtr<SurfaceClient> surface_client, + bool needs_sync_tokens) : surface_info_(surface_info), previous_frame_surface_id_(surface_info.id()), - compositor_frame_sink_support_(std::move(compositor_frame_sink_support)), - surface_manager_(compositor_frame_sink_support_->surface_manager()), - frame_index_(kFrameIndexStart) {} + surface_manager_(surface_manager), + surface_client_(std::move(surface_client)), + deadline_(surface_manager_->GetPrimaryBeginFrameSource()), + frame_index_(kFrameIndexStart), + needs_sync_tokens_(needs_sync_tokens) { + deadline_.AddObserver(this); +} Surface::~Surface() { ClearCopyRequests(); @@ -37,6 +44,9 @@ UnrefFrameResourcesAndRunDrawCallback(std::move(pending_frame_data_)); UnrefFrameResourcesAndRunDrawCallback(std::move(active_frame_data_)); + + deadline_.Cancel(); + deadline_.RemoveObserver(this); } void Surface::SetPreviousFrameSurface(Surface* surface) { @@ -49,6 +59,45 @@ surface->TakeLatencyInfoFromPendingFrame(&frame.metadata.latency_info); } +void Surface::RefResources(const std::vector<TransferableResource>& resources) { + if (surface_client_) + surface_client_->RefResources(resources); +} + +void Surface::UnrefResources(const std::vector<ReturnedResource>& resources) { + if (surface_client_) + surface_client_->UnrefResources(resources); +} + +void Surface::RejectCompositorFramesToFallbackSurfaces() { + std::vector<FrameSinkId> frame_sink_ids_for_dependencies; + for (const SurfaceId& surface_id : + GetPendingFrame().metadata.activation_dependencies) { + frame_sink_ids_for_dependencies.push_back(surface_id.frame_sink_id()); + } + + for (const SurfaceId& surface_id : + GetPendingFrame().metadata.referenced_surfaces) { + // A surface ID in |referenced_surfaces| that has a corresponding surface + // ID in |activation_dependencies| with the same frame sink ID is said to + // be a fallback surface that can be used in place of the primary surface + // if the deadline passes before the dependency becomes available. + auto it = std::find(frame_sink_ids_for_dependencies.begin(), + frame_sink_ids_for_dependencies.end(), + surface_id.frame_sink_id()); + bool is_fallback_surface = it != frame_sink_ids_for_dependencies.end(); + if (!is_fallback_surface) + continue; + + Surface* surface = surface_manager_->GetSurfaceForId(surface_id); + // A misbehaving client may report a non-existent surface ID as a + // |referenced_surface|. In that case, |surface| would be nullptr, and + // there is nothing to do here. + if (surface) + surface->Close(); + } +} + void Surface::Close() { closed_ = true; } @@ -56,6 +105,8 @@ bool Surface::QueueFrame(CompositorFrame frame, const base::Closure& callback, const WillDrawCallback& will_draw_callback) { + late_activation_dependencies_.clear(); + gfx::Size frame_size = frame.render_pass_list.back()->output_rect.size(); float device_scale_factor = frame.metadata.device_scale_factor; @@ -69,7 +120,7 @@ if (closed_) { std::vector<ReturnedResource> resources = TransferableResource::ReturnResources(frame.resource_list); - compositor_frame_sink_support_->ReturnResources(resources); + surface_client_->ReturnResources(resources); callback.Run(); return true; } @@ -80,45 +131,24 @@ std::move(pending_frame_data_); pending_frame_data_.reset(); - UpdateBlockingSurfaces(previous_pending_frame_data.has_value(), frame); + UpdateActivationDependencies(frame); // Receive and track the resources referenced from the CompositorFrame // regardless of whether it's pending or active. - compositor_frame_sink_support_->ReceiveFromChild(frame.resource_list); + surface_client_->ReceiveFromChild(frame.resource_list); - bool is_pending_frame = !blocking_surfaces_.empty(); - - if (is_pending_frame) { - // Reject CompositorFrames submitted to surfaces referenced from this - // CompositorFrame as fallbacks. This saves some CPU cycles to allow - // children to catch up to the parent. - base::flat_set<FrameSinkId> frame_sink_ids_for_dependencies; - for (const SurfaceId& surface_id : frame.metadata.activation_dependencies) - frame_sink_ids_for_dependencies.insert(surface_id.frame_sink_id()); - for (const SurfaceId& surface_id : frame.metadata.referenced_surfaces) { - // A surface ID in |referenced_surfaces| that has a corresponding surface - // ID in |activation_dependencies| with the same frame sink ID is said to - // be a fallback surface that can be used in place of the primary surface - // if the deadline passes before the dependency becomes available. - bool is_fallback_surface = - frame_sink_ids_for_dependencies.count(surface_id.frame_sink_id()) > 0; - if (is_fallback_surface) { - Surface* surface = surface_manager_->GetSurfaceForId(surface_id); - // A misbehaving client may report a non-existent surface ID as a - // |referenced_surface|. In that case, |surface| would be nullptr, and - // there is nothing to do here. - if (surface) - surface->Close(); - } - } - pending_frame_data_ = - FrameData(std::move(frame), callback, will_draw_callback); - // Ask the surface manager to inform |this| when its dependencies are - // resolved. - surface_manager_->RequestSurfaceResolution(this); - } else { + if (activation_dependencies_.empty()) { // If there are no blockers, then immediately activate the frame. ActivateFrame(FrameData(std::move(frame), callback, will_draw_callback)); + } else { + pending_frame_data_ = + FrameData(std::move(frame), callback, will_draw_callback); + + RejectCompositorFramesToFallbackSurfaces(); + + // Ask the surface manager to inform |this| when its dependencies are + // resolved. + surface_manager_->RequestSurfaceResolution(this, &deadline_); } // Returns resources for the previous pending frame. @@ -150,14 +180,14 @@ } void Surface::NotifySurfaceIdAvailable(const SurfaceId& surface_id) { - auto it = blocking_surfaces_.find(surface_id); + auto it = activation_dependencies_.find(surface_id); // This surface may no longer have blockers if the deadline has passed. - if (it == blocking_surfaces_.end()) + if (it == activation_dependencies_.end()) return; - blocking_surfaces_.erase(it); + activation_dependencies_.erase(it); - if (!blocking_surfaces_.empty()) + if (!activation_dependencies_.empty()) return; // All blockers have been cleared. The surface can be activated now. @@ -172,7 +202,8 @@ // If a frame is being activated because of a deadline, then clear its set // of blockers. - blocking_surfaces_.clear(); + late_activation_dependencies_ = std::move(activation_dependencies_); + activation_dependencies_.clear(); ActivatePendingFrame(); } @@ -200,7 +231,8 @@ // deadline has hit and the frame was forcibly activated by the display // compositor. void Surface::ActivateFrame(FrameData frame_data) { - DCHECK(compositor_frame_sink_support_); + deadline_.Cancel(); + DCHECK(surface_client_); // Save root pass copy requests. std::vector<std::unique_ptr<CopyOutputRequest>> old_copy_requests; @@ -226,12 +258,12 @@ UnrefFrameResourcesAndRunDrawCallback(std::move(previous_frame_data)); - compositor_frame_sink_support_->OnSurfaceActivated(this); + surface_client_->OnSurfaceActivated(this); } -void Surface::UpdateBlockingSurfaces(bool has_previous_pending_frame, - const CompositorFrame& current_frame) { - base::flat_set<SurfaceId> new_blocking_surfaces; +void Surface::UpdateActivationDependencies( + const CompositorFrame& current_frame) { + base::flat_set<SurfaceId> new_activation_dependencies; for (const SurfaceId& surface_id : current_frame.metadata.activation_dependencies) { @@ -239,33 +271,41 @@ // If a activation dependency does not have a corresponding active frame in // the display compositor, then it blocks this frame. if (!dependency || !dependency->HasActiveFrame()) - new_blocking_surfaces.insert(surface_id); + new_activation_dependencies.insert(surface_id); } // If this Surface has a previous pending frame, then we must determine the // changes in dependencies so that we can update the SurfaceDependencyTracker // map. - if (has_previous_pending_frame) { - base::flat_set<SurfaceId> removed_dependencies; - for (const SurfaceId& surface_id : blocking_surfaces_) { - if (!new_blocking_surfaces.count(surface_id)) - removed_dependencies.insert(surface_id); - } + base::flat_set<SurfaceId> added_dependencies; + base::flat_set<SurfaceId> removed_dependencies; + ComputeChangeInDependencies(activation_dependencies_, + new_activation_dependencies, &added_dependencies, + &removed_dependencies); - base::flat_set<SurfaceId> added_dependencies; - for (const SurfaceId& surface_id : new_blocking_surfaces) { - if (!blocking_surfaces_.count(surface_id)) - added_dependencies.insert(surface_id); - } - - // If there is a change in the dependency set, then inform observers. - if (!added_dependencies.empty() || !removed_dependencies.empty()) { - surface_manager_->SurfaceDependenciesChanged(this, added_dependencies, - removed_dependencies); - } + // If there is a change in the dependency set, then inform SurfaceManager. + if (!added_dependencies.empty() || !removed_dependencies.empty()) { + surface_manager_->SurfaceDependenciesChanged(this, added_dependencies, + removed_dependencies); } - blocking_surfaces_ = std::move(new_blocking_surfaces); + activation_dependencies_ = std::move(new_activation_dependencies); +} + +void Surface::ComputeChangeInDependencies( + const base::flat_set<SurfaceId>& existing_dependencies, + const base::flat_set<SurfaceId>& new_dependencies, + base::flat_set<SurfaceId>* added_dependencies, + base::flat_set<SurfaceId>* removed_dependencies) { + for (const SurfaceId& surface_id : existing_dependencies) { + if (!new_dependencies.count(surface_id)) + removed_dependencies->insert(surface_id); + } + + for (const SurfaceId& surface_id : new_dependencies) { + if (!existing_dependencies.count(surface_id)) + added_dependencies->insert(surface_id); + } } void Surface::TakeCopyOutputRequests(Surface::CopyRequestsMap* copy_requests) { @@ -328,9 +368,13 @@ }); } +void Surface::OnDeadline() { + ActivatePendingFrameForDeadline(); +} + void Surface::UnrefFrameResourcesAndRunDrawCallback( base::Optional<FrameData> frame_data) { - if (!frame_data || !compositor_frame_sink_support_) + if (!frame_data || !surface_client_) return; std::vector<ReturnedResource> resources = @@ -338,7 +382,7 @@ // No point in returning same sync token to sender. for (auto& resource : resources) resource.sync_token.Clear(); - compositor_frame_sink_support_->UnrefResources(resources); + surface_client_->UnrefResources(resources); if (!frame_data->draw_callback.is_null()) frame_data->draw_callback.Run();
diff --git a/cc/surfaces/surface.h b/cc/surfaces/surface.h index 6f4495b..f6532b60 100644 --- a/cc/surfaces/surface.h +++ b/cc/surfaces/surface.h
@@ -21,6 +21,7 @@ #include "cc/output/compositor_frame.h" #include "cc/output/copy_output_request.h" #include "cc/surfaces/frame_sink_id.h" +#include "cc/surfaces/surface_dependency_deadline.h" #include "cc/surfaces/surface_info.h" #include "cc/surfaces/surface_sequence.h" #include "cc/surfaces/surfaces_export.h" @@ -32,18 +33,19 @@ namespace cc { -class CompositorFrameSinkSupport; +class SurfaceClient; class CopyOutputRequest; class SurfaceManager; -class CC_SURFACES_EXPORT Surface { +class CC_SURFACES_EXPORT Surface : public SurfaceDeadlineObserver { public: using WillDrawCallback = base::RepeatingCallback<void(const LocalSurfaceId&, const gfx::Rect&)>; - Surface( - const SurfaceInfo& surface_info, - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support); + Surface(const SurfaceInfo& surface_info, + SurfaceManager* surface_manager, + base::WeakPtr<SurfaceClient> surface_client, + bool needs_sync_tokens); ~Surface(); const SurfaceId& surface_id() const { return surface_info_.id(); } @@ -51,12 +53,32 @@ return previous_frame_surface_id_; } + bool has_deadline() const { return deadline_.has_deadline(); } + const SurfaceDependencyDeadline& deadline() const { return deadline_; } + + bool InheritActivationDeadlineFrom( + const SurfaceDependencyDeadline& deadline) { + return deadline_.InheritFrom(deadline); + } + + void SetActivationDeadline(uint32_t number_of_frames_to_deadline) { + deadline_.Set(number_of_frames_to_deadline); + } + void SetPreviousFrameSurface(Surface* surface); + // Increments the reference count on resources specified by |resources|. + void RefResources(const std::vector<TransferableResource>& resources); + + // Decrements the reference count on resources specified by |resources|. + void UnrefResources(const std::vector<ReturnedResource>& resources); + + bool needs_sync_tokens() const { return needs_sync_tokens_; } + // Returns false if |frame| is invalid. // |draw_callback| is called once to notify the client that the previously // submitted CompositorFrame is processed and that another frame can be - // submitted. + // there is visible damage. // |will_draw_callback| is called when |surface| is scheduled for a draw and // there is visible damage. bool QueueFrame(CompositorFrame frame, @@ -94,10 +116,6 @@ void RunDrawCallback(); void RunWillDrawCallback(const gfx::Rect& damage_rect); - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support() { - return compositor_frame_sink_support_; - } - // Add a SurfaceSequence that must be satisfied before the Surface is // destroyed. void AddDestructionDependency(SurfaceSequence sequence); @@ -117,8 +135,17 @@ : nullptr; } - const base::flat_set<SurfaceId>& blocking_surfaces() const { - return blocking_surfaces_; + // Returns the set of dependencies blocking this surface's pending frame + // that themselves have not yet activated. + const base::flat_set<SurfaceId>& activation_dependencies() const { + return activation_dependencies_; + } + + // Returns the set of activation dependencies that have been ignored because + // the last CompositorFrame was activated due to a deadline. Late dependencies + // activate immediately when they arrive. + const base::flat_set<SurfaceId>& late_activation_dependencies() const { + return late_activation_dependencies_; } bool HasActiveFrame() const { return active_frame_data_.has_value(); } @@ -127,6 +154,9 @@ return HasActiveFrame() && active_frame_data_->draw_callback; } + // SurfaceDeadlineObserver implementation: + void OnDeadline() override; + private: struct FrameData { FrameData(CompositorFrame&& frame, @@ -140,6 +170,11 @@ WillDrawCallback will_draw_callback; }; + // Rejects CompositorFrames submitted to surfaces referenced from this + // CompositorFrame as fallbacks. This saves some CPU cycles to allow + // children to catch up to the parent. + void RejectCompositorFramesToFallbackSurfaces(); + // Called to prevent additional CompositorFrames from being accepted into this // surface. Once a Surface is closed, it cannot accept CompositorFrames again. void Close(); @@ -147,8 +182,12 @@ void ActivatePendingFrame(); // Called when all of the surface's dependencies have been resolved. void ActivateFrame(FrameData frame_data); - void UpdateBlockingSurfaces(bool has_previous_pending_frame, - const CompositorFrame& current_frame); + void UpdateActivationDependencies(const CompositorFrame& current_frame); + void ComputeChangeInDependencies( + const base::flat_set<SurfaceId>& existing_dependencies, + const base::flat_set<SurfaceId>& new_dependencies, + base::flat_set<SurfaceId>* added_dependencies, + base::flat_set<SurfaceId>* removed_dependencies); void UnrefFrameResourcesAndRunDrawCallback( base::Optional<FrameData> frame_data); @@ -162,16 +201,19 @@ SurfaceInfo surface_info_; SurfaceId previous_frame_surface_id_; - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support_; SurfaceManager* const surface_manager_; + base::WeakPtr<SurfaceClient> surface_client_; + SurfaceDependencyDeadline deadline_; base::Optional<FrameData> pending_frame_data_; base::Optional<FrameData> active_frame_data_; int frame_index_; bool closed_ = false; + const bool needs_sync_tokens_; std::vector<SurfaceSequence> destruction_dependencies_; - base::flat_set<SurfaceId> blocking_surfaces_; + base::flat_set<SurfaceId> activation_dependencies_; + base::flat_set<SurfaceId> late_activation_dependencies_; DISALLOW_COPY_AND_ASSIGN(Surface); };
diff --git a/cc/surfaces/surface_aggregator.cc b/cc/surfaces/surface_aggregator.cc index 841286c..ea05182 100644 --- a/cc/surfaces/surface_aggregator.cc +++ b/cc/surfaces/surface_aggregator.cc
@@ -25,8 +25,8 @@ #include "cc/quads/surface_draw_quad.h" #include "cc/quads/texture_draw_quad.h" #include "cc/resources/resource_provider.h" -#include "cc/surfaces/compositor_frame_sink_support.h" #include "cc/surfaces/surface.h" +#include "cc/surfaces/surface_client.h" #include "cc/surfaces/surface_manager.h" #include "cc/trees/blocking_task_runner.h" @@ -122,14 +122,6 @@ return out_clip; } -static void UnrefHelper( - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support, - const std::vector<ReturnedResource>& resources, - BlockingTaskRunner* main_thread_task_runner) { - if (compositor_frame_sink_support) - compositor_frame_sink_support->UnrefResources(resources); -} - RenderPassId SurfaceAggregator::RemapPassId(RenderPassId surface_local_pass_id, const SurfaceId& surface_id) { auto key = std::make_pair(surface_id, surface_local_pass_id); @@ -149,12 +141,9 @@ auto it = surface_id_to_resource_child_id_.find(surface->surface_id()); if (it == surface_id_to_resource_child_id_.end()) { int child_id = provider_->CreateChild( - base::Bind(&UnrefHelper, surface->compositor_frame_sink_support())); - if (surface->compositor_frame_sink_support()) { - provider_->SetChildNeedsSyncTokens( - child_id, - surface->compositor_frame_sink_support()->needs_sync_points()); - } + base::Bind(&SurfaceAggregator::UnrefResources, + weak_factory_.GetWeakPtr(), surface->surface_id())); + provider_->SetChildNeedsSyncTokens(child_id, surface->needs_sync_tokens()); surface_id_to_resource_child_id_[surface->surface_id()] = child_id; return child_id; } else { @@ -186,6 +175,15 @@ return full_rect; } +void SurfaceAggregator::UnrefResources( + const SurfaceId& surface_id, + const std::vector<ReturnedResource>& resources, + BlockingTaskRunner* main_thread_task_runner) { + Surface* surface = manager_->GetSurfaceForId(surface_id); + if (surface) + surface->UnrefResources(resources); +} + void SurfaceAggregator::HandleSurfaceQuad( const SurfaceDrawQuad* surface_quad, const gfx::Transform& target_transform, @@ -614,9 +612,7 @@ // TODO(jbauman): hack for unit tests that don't set up rp if (provider_) { child_id = ChildIdForSurface(surface); - if (surface->compositor_frame_sink_support()) - surface->compositor_frame_sink_support()->RefResources( - frame.resource_list); + surface->RefResources(frame.resource_list); provider_->ReceiveFromChild(child_id, frame.resource_list); } CHECK(debug_weak_this.get());
diff --git a/cc/surfaces/surface_aggregator.h b/cc/surfaces/surface_aggregator.h index 9e7ce6f..fc71284 100644 --- a/cc/surfaces/surface_aggregator.h +++ b/cc/surfaces/surface_aggregator.h
@@ -21,6 +21,7 @@ namespace cc { +class BlockingTaskRunner; class CompositorFrame; class ResourceProvider; class Surface; @@ -138,6 +139,10 @@ const RenderPass& source, const gfx::Rect& full_rect) const; + void UnrefResources(const SurfaceId& surface_id, + const std::vector<ReturnedResource>& resources, + BlockingTaskRunner* main_thread_task_runner); + SurfaceManager* manager_; ResourceProvider* provider_;
diff --git a/cc/surfaces/surface_client.h b/cc/surfaces/surface_client.h new file mode 100644 index 0000000..1087699 --- /dev/null +++ b/cc/surfaces/surface_client.h
@@ -0,0 +1,52 @@ +// 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 CC_SURFACES_SURFACE_CLIENT_H_ +#define CC_SURFACES_SURFACE_CLIENT_H_ + +#include <vector> + +#include "base/macros.h" +#include "cc/surfaces/surfaces_export.h" + +namespace cc { + +class Surface; +struct ReturnedResource; +struct TransferableResource; + +class CC_SURFACES_EXPORT SurfaceClient { + public: + SurfaceClient() = default; + + virtual ~SurfaceClient() = default; + + // Called when |surface| has a new CompositorFrame available for display. + virtual void OnSurfaceActivated(Surface* surface) = 0; + + // Increments the reference count on resources specified by |resources|. + virtual void RefResources( + const std::vector<TransferableResource>& resources) = 0; + + // Decrements the reference count on resources specified by |resources|. + virtual void UnrefResources( + const std::vector<ReturnedResource>& resources) = 0; + + // ReturnResources gets called when the display compositor is done using the + // resources so that the client can use them. + virtual void ReturnResources( + const std::vector<ReturnedResource>& resources) = 0; + + // Increments the reference count of resources received from a child + // compositor. + virtual void ReceiveFromChild( + const std::vector<TransferableResource>& resources) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(SurfaceClient); +}; + +} // namespace cc + +#endif // CC_SURFACES_SURFACE_CLIENT_H_
diff --git a/cc/surfaces/surface_dependency_deadline.cc b/cc/surfaces/surface_dependency_deadline.cc index a641efd..41d7316 100644 --- a/cc/surfaces/surface_dependency_deadline.cc +++ b/cc/surfaces/surface_dependency_deadline.cc
@@ -33,9 +33,34 @@ number_of_frames_to_deadline_.reset(); } +bool SurfaceDependencyDeadline::InheritFrom( + const SurfaceDependencyDeadline& other) { + if (*this == other) + return false; + + Cancel(); + last_begin_frame_args_ = other.last_begin_frame_args_; + begin_frame_source_ = other.begin_frame_source_; + number_of_frames_to_deadline_ = other.number_of_frames_to_deadline_; + if (number_of_frames_to_deadline_) + begin_frame_source_->AddObserver(this); + return true; +} + +bool SurfaceDependencyDeadline::operator==( + const SurfaceDependencyDeadline& other) { + return begin_frame_source_ == other.begin_frame_source_ && + number_of_frames_to_deadline_ == other.number_of_frames_to_deadline_; +} + // BeginFrameObserver implementation. void SurfaceDependencyDeadline::OnBeginFrame(const BeginFrameArgs& args) { last_begin_frame_args_ = args; + // OnBeginFrame might get called immediately after cancellation if some other + // deadline triggered this deadline to be canceled. + if (!number_of_frames_to_deadline_ || args.type == BeginFrameArgs::MISSED) + return; + if (--(*number_of_frames_to_deadline_) > 0) return;
diff --git a/cc/surfaces/surface_dependency_deadline.h b/cc/surfaces/surface_dependency_deadline.h index b5b52b9..fe809e9 100644 --- a/cc/surfaces/surface_dependency_deadline.h +++ b/cc/surfaces/surface_dependency_deadline.h
@@ -31,6 +31,15 @@ return number_of_frames_to_deadline_.has_value(); } + // Takes on the same BeginFrameSource and deadline as |other|. Returns + // false if they're already the same, and true otherwise. + bool InheritFrom(const SurfaceDependencyDeadline& other); + + bool operator==(const SurfaceDependencyDeadline& other); + bool operator!=(const SurfaceDependencyDeadline& other) { + return !(*this == other); + } + // BeginFrameObserver implementation. void OnBeginFrame(const BeginFrameArgs& args) override; const BeginFrameArgs& LastUsedBeginFrameArgs() const override;
diff --git a/cc/surfaces/surface_dependency_tracker.cc b/cc/surfaces/surface_dependency_tracker.cc index 758a2b0..bf7c41c 100644 --- a/cc/surfaces/surface_dependency_tracker.cc +++ b/cc/surfaces/surface_dependency_tracker.cc
@@ -11,51 +11,48 @@ namespace cc { namespace { -constexpr uint32_t kMaxBeginFrameCount = 4; +constexpr uint32_t kDefaultNumberOfFramesToDeadline = 4; } SurfaceDependencyTracker::SurfaceDependencyTracker( - SurfaceManager* surface_manager, - BeginFrameSource* begin_frame_source) - : surface_manager_(surface_manager), deadline_(begin_frame_source) { - deadline_.AddObserver(this); -} + SurfaceManager* surface_manager) + : surface_manager_(surface_manager) {} -SurfaceDependencyTracker::~SurfaceDependencyTracker() { - deadline_.Cancel(); - deadline_.RemoveObserver(this); -} +SurfaceDependencyTracker::~SurfaceDependencyTracker() = default; -void SurfaceDependencyTracker::RequestSurfaceResolution(Surface* surface) { +void SurfaceDependencyTracker::RequestSurfaceResolution( + Surface* surface, + SurfaceDependencyDeadline* deadline) { DCHECK(surface->HasPendingFrame()); const CompositorFrame& pending_frame = surface->GetPendingFrame(); - bool needs_deadline = pending_frame.metadata.can_activate_before_dependencies; - auto late_it = late_surfaces_by_id_.find(surface->surface_id()); - if (needs_deadline && late_it != late_surfaces_by_id_.end()) { - late_surfaces_by_id_.erase(late_it); - surface->ActivatePendingFrameForDeadline(); + if (IsSurfaceLate(surface)) { + ActivateLateSurfaceSubtree(surface); return; } // Activation dependencies that aren't currently known to the surface manager - // or do not have an active CompsotiorFrame block this frame. + // or do not have an active CompositorFrame block this frame. for (const SurfaceId& surface_id : pending_frame.metadata.activation_dependencies) { Surface* dependency = surface_manager_->GetSurfaceForId(surface_id); - if (!dependency || !dependency->HasActiveFrame()) + if (!dependency || !dependency->HasActiveFrame()) { blocked_surfaces_from_dependency_[surface_id].insert( surface->surface_id()); + } } blocked_surfaces_by_id_.insert(surface->surface_id()); - if (needs_deadline && !deadline_.has_deadline()) - deadline_.Set(kMaxBeginFrameCount); + UpdateSurfaceDeadline(surface); } void SurfaceDependencyTracker::OnSurfaceActivated(Surface* surface) { + if (!surface->late_activation_dependencies().empty()) + surfaces_with_missing_dependencies_.insert(surface->surface_id()); + else + surfaces_with_missing_dependencies_.erase(surface->surface_id()); blocked_surfaces_by_id_.erase(surface->surface_id()); NotifySurfaceIdAvailable(surface->surface_id()); } @@ -75,14 +72,11 @@ if (it->second.empty()) blocked_surfaces_from_dependency_.erase(it); } - - // If there are no more dependencies to resolve then we don't need to have a - // deadline. - if (blocked_surfaces_from_dependency_.empty()) - deadline_.Cancel(); } void SurfaceDependencyTracker::OnSurfaceDiscarded(Surface* surface) { + surfaces_with_missing_dependencies_.erase(surface->surface_id()); + // If the surface being destroyed doesn't have a pending frame then we have // nothing to do here. if (!surface->HasPendingFrame()) @@ -108,9 +102,6 @@ } } - if (blocked_surfaces_from_dependency_.empty()) - deadline_.Cancel(); - blocked_surfaces_by_id_.erase(surface->surface_id()); // Pretend that the discarded surface's SurfaceId is now available to unblock @@ -118,33 +109,75 @@ NotifySurfaceIdAvailable(surface->surface_id()); } -void SurfaceDependencyTracker::OnDeadline() { - late_surfaces_by_id_.clear(); +void SurfaceDependencyTracker::ActivateLateSurfaceSubtree(Surface* surface) { + DCHECK(surface->HasPendingFrame()); - // Activate all surfaces that respect the deadline. - // Copy the set of blocked surfaces here because that set can mutate as we - // activate CompositorFrames: an activation can trigger further activations - // which will remove elements from |blocked_surfaces_by_id_|. This - // invalidates the iterator. - base::flat_set<SurfaceId> blocked_surfaces_by_id(blocked_surfaces_by_id_); - for (const SurfaceId& surface_id : blocked_surfaces_by_id) { - Surface* blocked_surface = surface_manager_->GetSurfaceForId(surface_id); - if (!blocked_surface) { - // A blocked surface may have been garbage collected during dependency - // resolution. - DCHECK(!blocked_surfaces_by_id_.count(surface_id)); - continue; - } - // Clear all tracked blockers for |blocked_surface|. - for (const SurfaceId& blocking_surface_id : - blocked_surface->blocking_surfaces()) { - // If we are not activating this blocker now, then it's late. - if (!blocked_surfaces_by_id.count(blocking_surface_id)) - late_surfaces_by_id_.insert(blocking_surface_id); - blocked_surfaces_from_dependency_[blocking_surface_id].erase(surface_id); - } - blocked_surface->ActivatePendingFrameForDeadline(); + const CompositorFrame& pending_frame = surface->GetPendingFrame(); + + for (const SurfaceId& surface_id : + pending_frame.metadata.activation_dependencies) { + Surface* dependency = surface_manager_->GetSurfaceForId(surface_id); + if (dependency && dependency->HasPendingFrame()) + ActivateLateSurfaceSubtree(dependency); } + + surface->ActivatePendingFrameForDeadline(); +} + +void SurfaceDependencyTracker::UpdateSurfaceDeadline(Surface* surface) { + DCHECK(surface->HasPendingFrame()); + + const CompositorFrame& pending_frame = surface->GetPendingFrame(); + + // Determine an activation deadline for the pending CompositorFrame. + bool needs_deadline = pending_frame.metadata.can_activate_before_dependencies; + if (!needs_deadline) + return; + + bool deadline_changed = false; + + // Inherit the deadline from the first parent blocked on this surface. + auto it = blocked_surfaces_from_dependency_.find(surface->surface_id()); + if (it != blocked_surfaces_from_dependency_.end()) { + const base::flat_set<SurfaceId>& dependent_parent_ids = it->second; + for (const SurfaceId& parent_id : dependent_parent_ids) { + Surface* parent = surface_manager_->GetSurfaceForId(parent_id); + if (parent && parent->has_deadline()) { + deadline_changed = + surface->InheritActivationDeadlineFrom(parent->deadline()); + break; + } + } + } + // If there are no CompositorFrames currently blocked on this surface, then + // set a default deadline for this surface. + if (!surface->has_deadline()) { + surface->SetActivationDeadline(kDefaultNumberOfFramesToDeadline); + deadline_changed = true; + } + + if (!deadline_changed) + return; + + // Recursively propagate the newly set deadline to children. + for (const SurfaceId& surface_id : + pending_frame.metadata.activation_dependencies) { + Surface* dependency = surface_manager_->GetSurfaceForId(surface_id); + if (dependency && dependency->HasPendingFrame()) + UpdateSurfaceDeadline(dependency); + } +} + +bool SurfaceDependencyTracker::IsSurfaceLate(Surface* surface) { + for (const SurfaceId& surface_id : surfaces_with_missing_dependencies_) { + Surface* activated_surface = surface_manager_->GetSurfaceForId(surface_id); + DCHECK(activated_surface->HasActiveFrame()); + if (activated_surface->late_activation_dependencies().count( + surface->surface_id())) { + return true; + } + } + return false; } void SurfaceDependencyTracker::NotifySurfaceIdAvailable( @@ -156,10 +189,6 @@ // Unblock surfaces that depend on this |surface_id|. base::flat_set<SurfaceId> blocked_surfaces_by_id(it->second); blocked_surfaces_from_dependency_.erase(it); - // If there are no more blockers in the system, then we no longer need to - // have a deadline. - if (blocked_surfaces_from_dependency_.empty()) - deadline_.Cancel(); // Tell each surface about the availability of its blocker. for (const SurfaceId& blocked_surface_by_id : blocked_surfaces_by_id) {
diff --git a/cc/surfaces/surface_dependency_tracker.h b/cc/surfaces/surface_dependency_tracker.h index 7ce52df..0b31814d 100644 --- a/cc/surfaces/surface_dependency_tracker.h +++ b/cc/surfaces/surface_dependency_tracker.h
@@ -6,12 +6,10 @@ #define CC_SURFACES_SURFACE_DEPENDENCY_TRACKER_H_ #include "cc/surfaces/surface.h" -#include "cc/surfaces/surface_dependency_deadline.h" #include "cc/surfaces/surfaces_export.h" namespace cc { -class BeginFrameSource; class SurfaceManager; // SurfaceDependencyTracker tracks unresolved dependencies blocking @@ -26,24 +24,15 @@ // deadline hits, then SurfaceDependencyTracker will clear then and activate // all pending CompositorFrames. Once there are no more remaining pending // frames, then SurfaceDependencyTracker will stop observing BeginFrames. -// TODO(fsamuel): Deadlines should not be global. They should be scoped to a -// surface subtree. However, that will not be possible until SurfaceReference -// work is complete. -class CC_SURFACES_EXPORT SurfaceDependencyTracker - : public SurfaceDeadlineObserver { +class CC_SURFACES_EXPORT SurfaceDependencyTracker { public: - SurfaceDependencyTracker(SurfaceManager* surface_manager, - BeginFrameSource* begin_frame_source); + explicit SurfaceDependencyTracker(SurfaceManager* surface_manager); ~SurfaceDependencyTracker(); // Called when |surface| has a pending CompositorFrame and it wishes to be // informed when that surface's dependencies are resolved. - void RequestSurfaceResolution(Surface* surface); - - bool has_deadline() const { return deadline_.has_deadline(); } - - // SurfaceDeadlineObserver implementation: - void OnDeadline() override; + void RequestSurfaceResolution(Surface* surface, + SurfaceDependencyDeadline* deadline); void OnSurfaceActivated(Surface* surface); void OnSurfaceDependenciesChanged( @@ -53,6 +42,19 @@ void OnSurfaceDiscarded(Surface* surface); private: + // If |surface| has a dependent embedder frame, then it inherits the parent's + // deadline and propagates that deadline to children. + void UpdateSurfaceDeadline(Surface* surface); + + // Activates this |surface| and its entire dependency tree. + void ActivateLateSurfaceSubtree(Surface* surface); + + // Indicates whether |surface| is late. A surface is late if it hasn't had its + // first activation before a embedder is forced to activate its own + // CompositorFrame. A surface may no longer be considered late if the set of + // activation dependencies for dependent surfaces change. + bool IsSurfaceLate(Surface* surface); + // Informs all Surfaces with pending frames blocked on the provided // |surface_id| that there is now an active frame available in Surface // corresponding to |surface_id|. @@ -60,10 +62,6 @@ SurfaceManager* const surface_manager_; - // This object tracks the deadline when all pending CompositorFrames in the - // system will be activated. - SurfaceDependencyDeadline deadline_; - // A map from a SurfaceId to the set of Surfaces blocked on that SurfaceId. std::unordered_map<SurfaceId, base::flat_set<SurfaceId>, SurfaceIdHash> blocked_surfaces_from_dependency_; @@ -71,6 +69,10 @@ // The set of SurfaceIds corresponding that are known to have blockers. base::flat_set<SurfaceId> blocked_surfaces_by_id_; + // The set of SurfaceIds corresponding to Surfaces that have active + // CompositorFrames with missing dependencies. + base::flat_set<SurfaceId> surfaces_with_missing_dependencies_; + // The set of SurfaceIds to which corresponding CompositorFrames have not // arrived by the time their deadline fired. base::flat_set<SurfaceId> late_surfaces_by_id_;
diff --git a/cc/surfaces/surface_manager.cc b/cc/surfaces/surface_manager.cc index bfcde56af..3268cf0a 100644 --- a/cc/surfaces/surface_manager.cc +++ b/cc/surfaces/surface_manager.cc
@@ -12,11 +12,11 @@ #include <utility> #include "base/logging.h" -#include "cc/surfaces/compositor_frame_sink_support.h" #include "cc/surfaces/direct_surface_reference_factory.h" #include "cc/surfaces/local_surface_id_allocator.h" #include "cc/surfaces/stub_surface_reference_factory.h" #include "cc/surfaces/surface.h" +#include "cc/surfaces/surface_client.h" #include "cc/surfaces/surface_info.h" #if DCHECK_IS_ON() @@ -44,7 +44,7 @@ } SurfaceManager::~SurfaceManager() { - // All CompositorFrameSinkSupports and their surfaces are supposed to be + // All SurfaceClients and their surfaces are supposed to be // destroyed before SurfaceManager. DCHECK_EQ(surfaces_to_destroy_.size(), surface_map_.size()); } @@ -66,26 +66,27 @@ dependency_tracker_ = dependency_tracker; } -void SurfaceManager::RequestSurfaceResolution(Surface* pending_surface) { +void SurfaceManager::RequestSurfaceResolution( + Surface* surface, + SurfaceDependencyDeadline* deadline) { if (dependency_tracker_) - dependency_tracker_->RequestSurfaceResolution(pending_surface); + dependency_tracker_->RequestSurfaceResolution(surface, deadline); } Surface* SurfaceManager::CreateSurface( - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support, - const SurfaceInfo& surface_info) { + base::WeakPtr<SurfaceClient> surface_client, + const SurfaceInfo& surface_info, + bool needs_sync_tokens) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(surface_info.is_valid()); - DCHECK(compositor_frame_sink_support); - DCHECK_EQ(surface_info.id().frame_sink_id(), - compositor_frame_sink_support->frame_sink_id()); + DCHECK(surface_client); // If no surface with this SurfaceId exists, simply create the surface and // return. auto it = surface_map_.find(surface_info.id()); if (it == surface_map_.end()) { - surface_map_[surface_info.id()] = - base::MakeUnique<Surface>(surface_info, compositor_frame_sink_support); + surface_map_[surface_info.id()] = base::MakeUnique<Surface>( + surface_info, this, surface_client, needs_sync_tokens); return surface_map_[surface_info.id()].get(); } @@ -95,8 +96,6 @@ Surface* surface = it->second.get(); DCHECK(IsMarkedForDestruction(surface_info.id())); surfaces_to_destroy_.erase(surface_info.id()); - DCHECK_EQ(compositor_frame_sink_support.get(), - surface->compositor_frame_sink_support().get()); return surface; }
diff --git a/cc/surfaces/surface_manager.h b/cc/surfaces/surface_manager.h index 872faec..adc228f 100644 --- a/cc/surfaces/surface_manager.h +++ b/cc/surfaces/surface_manager.h
@@ -65,14 +65,15 @@ void SetDependencyTracker(SurfaceDependencyTracker* dependency_tracker); SurfaceDependencyTracker* dependency_tracker() { return dependency_tracker_; } - void RequestSurfaceResolution(Surface* pending_surface); + void RequestSurfaceResolution(Surface* surface, + SurfaceDependencyDeadline* deadline); - // Creates a Surface for the given CompositorFrameSinkSupport. The surface - // will be destroyed when DestroySurface is called, all of its destruction + // Creates a Surface for the given SurfaceClient. The surface will be + // destroyed when DestroySurface is called, all of its destruction // dependencies are satisfied, and it is not reachable from the root surface. - Surface* CreateSurface( - base::WeakPtr<CompositorFrameSinkSupport> compositor_frame_sink_support, - const SurfaceInfo& surface_info); + Surface* CreateSurface(base::WeakPtr<SurfaceClient> surface_client, + const SurfaceInfo& surface_info, + bool needs_sync_tokens); // Destroy the Surface once a set of sequence numbers has been satisfied. void DestroySurface(const SurfaceId& surface_id); @@ -96,7 +97,7 @@ // |ack.sequence_number| is only valid if called in response to a BeginFrame. bool SurfaceModified(const SurfaceId& surface_id, const BeginFrameAck& ack); - // Called when a CompositorFrame is submitted to a CompositorFrameSinkSupport + // Called when a CompositorFrame is submitted to a SurfaceClient // for a given |surface_id| for the first time. void SurfaceCreated(const SurfaceInfo& surface_info); @@ -133,8 +134,8 @@ // possibly because a renderer process has crashed. void InvalidateFrameSinkId(const FrameSinkId& frame_sink_id); - // CompositorFrameSinkSupport, hierarchy, and BeginFrameSource can be - // registered and unregistered in any order with respect to each other. + // SurfaceClient, hierarchy, and BeginFrameSource can be registered and + // unregistered in any order with respect to each other. // // This happens in practice, e.g. the relationship to between ui::Compositor / // DelegatedFrameHost is known before ui::Compositor has a surface/client).
diff --git a/cc/surfaces/surface_synchronization_unittest.cc b/cc/surfaces/surface_synchronization_unittest.cc index 1f6a1922..78f87e8 100644 --- a/cc/surfaces/surface_synchronization_unittest.cc +++ b/cc/surfaces/surface_synchronization_unittest.cc
@@ -120,10 +120,13 @@ return begin_frame_source_.get(); } - bool HasDeadline() { - bool has_deadline = dependency_tracker().has_deadline(); - EXPECT_EQ(has_deadline, begin_frame_source_client_.has_observers()); - return has_deadline; + void SendNextBeginFrame() { + // Creep the time forward so that any BeginFrameArgs is not equal to the + // last one otherwise we violate the BeginFrameSource contract. + now_src_->Advance(BeginFrameArgs::DefaultInterval()); + BeginFrameArgs args = begin_frame_source_->CreateBeginFrameArgs( + BEGINFRAME_FROM_HERE, now_src_.get()); + begin_frame_source_->TestOnBeginFrame(args); } FakeSurfaceObserver& surface_observer() { return surface_observer_; } @@ -135,8 +138,9 @@ begin_frame_source_ = base::MakeUnique<FakeExternalBeginFrameSource>(0.f, false); begin_frame_source_->SetClient(&begin_frame_source_client_); - dependency_tracker_ = base::MakeUnique<SurfaceDependencyTracker>( - &surface_manager_, begin_frame_source_.get()); + dependency_tracker_ = + base::MakeUnique<SurfaceDependencyTracker>(&surface_manager_); + now_src_ = base::MakeUnique<base::SimpleTestTickClock>(); surface_manager_.SetDependencyTracker(dependency_tracker_.get()); surface_manager_.AddObserver(&surface_observer_); supports_.push_back(CompositorFrameSinkSupport::Create( @@ -189,6 +193,7 @@ FakeSurfaceObserver surface_observer_; FakeExternalBeginFrameSourceClient begin_frame_source_client_; std::unique_ptr<FakeExternalBeginFrameSource> begin_frame_source_; + std::unique_ptr<base::SimpleTestTickClock> now_src_; std::unique_ptr<SurfaceDependencyTracker> dependency_tracker_; std::vector<std::unique_ptr<CompositorFrameSinkSupport>> supports_; @@ -237,10 +242,10 @@ std::vector<TransferableResource>())); // parent_support is blocked on |child_id1| and |child_id2|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1, child_id2)); // Submit a CompositorFrame without any dependencies to |child_id1|. @@ -248,10 +253,10 @@ child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), MakeCompositorFrame()); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Submit a CompositorFrame without any dependencies to |child_id2|. @@ -259,10 +264,10 @@ child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeCompositorFrame()); - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(child_surface2()->has_deadline()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // The parent Surface is blocked on |child_id2| which is blocked on |child_id3|. @@ -277,10 +282,10 @@ std::vector<TransferableResource>())); // parent_support is blocked on |child_id1|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // The parent should not report damage until it activates. EXPECT_FALSE(surface_observer().IsSurfaceDamaged(parent_id)); @@ -291,17 +296,17 @@ std::vector<TransferableResource>())); // child_support1 should now be blocked on |child_id2|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), + EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent and child should not report damage until they activate. EXPECT_FALSE(surface_observer().IsSurfaceDamaged(parent_id)); EXPECT_FALSE(surface_observer().IsSurfaceDamaged(child_id1)); // The parent should still be blocked on |child_id1| because it's pending. - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // Submit a CompositorFrame without any dependencies to |child_id2|. @@ -311,17 +316,17 @@ MakeCompositorFrame(empty_surface_ids(), empty_surface_ids(), std::vector<TransferableResource>())); - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(child_surface2()->has_deadline()); // child_surface1 should now be active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // parent_surface should now be active. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // All three surfaces |parent_id|, |child_id1|, and |child_id2| should // now report damage. This would trigger a new display frame. @@ -342,10 +347,10 @@ std::vector<TransferableResource>())); // parent_support is blocked on |child_id2|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // child_support1 should now be blocked on |child_id2|. @@ -354,14 +359,14 @@ MakeCompositorFrame({child_id2}, empty_surface_ids(), std::vector<TransferableResource>())); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), + EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent should still be blocked on |child_id2|. - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Submit a CompositorFrame without any dependencies to |child_id2|. @@ -369,17 +374,17 @@ child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), MakeCompositorFrame()); - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(child_surface2()->has_deadline()); // child_surface1 should now be active. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // parent_surface should now be active. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // parent_surface is blocked on |child_id1|, and child_surface2 is blocked on @@ -395,10 +400,10 @@ std::vector<TransferableResource>())); // parent_support is blocked on |child_id1|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); child_support1().SubmitCompositorFrame( @@ -407,85 +412,48 @@ std::vector<TransferableResource>())); // child_support1 should now be blocked on |child_id2|. - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(child_surface1()->has_deadline()); EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), + EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // The parent should still be blocked on |child_id1| because it's pending. - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); - for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); + SendNextBeginFrame(); // There is still a looming deadline! Eeek! - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); // parent_support is still blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // child_support1 is still blocked on |child_id2|. EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), + EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); } - begin_frame_source()->TestOnBeginFrame(args); + SendNextBeginFrame(); // The deadline has passed. - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(parent_surface()->has_deadline()); // parent_surface has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // child_surface1 has been activated. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); -} - -// Verifies that the deadline does not reset if we submit CompositorFrames -// to new Surfaces with unresolved dependencies. -TEST_F(SurfaceSynchronizationTest, FramesSubmittedAfterDeadlineSet) { - const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); - for (int i = 0; i < 3; ++i) { - LocalSurfaceId local_surface_id(1, base::UnguessableToken::Create()); - support(i).SubmitCompositorFrame( - local_surface_id, - MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), - std::vector<TransferableResource>())); - // The deadline has been set. - EXPECT_TRUE(HasDeadline()); - - // support(i) should be blocked on arbitrary_id. - EXPECT_FALSE(surface(i)->HasActiveFrame()); - EXPECT_TRUE(surface(i)->HasPendingFrame()); - EXPECT_THAT(surface(i)->blocking_surfaces(), - UnorderedElementsAre(arbitrary_id)); - - // Issue a BeginFrame to get closer to the deadline. - begin_frame_source()->TestOnBeginFrame(args); - } - - // The deadline hits and all the Surfaces should activate. - begin_frame_source()->TestOnBeginFrame(args); - for (int i = 0; i < 3; ++i) { - EXPECT_TRUE(surface(i)->HasActiveFrame()); - EXPECT_FALSE(surface(i)->HasPendingFrame()); - EXPECT_THAT(surface(i)->blocking_surfaces(), IsEmpty()); - } + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); } // This test verifies at the Surface activates once a CompositorFrame is @@ -503,7 +471,7 @@ // Verify that the CompositorFrame is blocked on |arbitrary_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(arbitrary_id)); // Submit a CompositorFrame that has no dependencies. @@ -513,7 +481,7 @@ // Verify that the CompositorFrame has been activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that a pending CompositorFrame does not affect surface @@ -534,7 +502,7 @@ // Verify that the child surface is not blocked. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that there's a temporary reference for |child_id1|. EXPECT_TRUE(HasTemporaryReference(child_id1)); @@ -551,7 +519,7 @@ std::vector<TransferableResource>())); EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); testing::Mock::VerifyAndClearExpectations(&support_client_); @@ -571,13 +539,13 @@ // Verify that the child surface is not blocked. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent surface's CompositorFrame has activated and that the // temporary reference has been replaced by a permanent one. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); EXPECT_FALSE(HasTemporaryReference(child_id1)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); } @@ -605,7 +573,7 @@ // Verify that the CompositorFrame is blocked on |child_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id)); child_support1().SubmitCompositorFrame( @@ -616,12 +584,12 @@ // Verify that the child CompositorFrame activates immediately. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); std::vector<ReturnedResource> returned_resources = { resource.ToReturnedResource()}; @@ -637,7 +605,7 @@ std::vector<TransferableResource>())); EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); } // The parent Surface is blocked on |child_id2| which is blocked on |child_id3|. @@ -657,7 +625,7 @@ // Verify that the CompositorFrame is blocked on |child_id1|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); // Submit a CompositorFrame that depends on |child_id2|. @@ -669,7 +637,7 @@ // Verify that the CompositorFrame is blocked on |child_id2|. EXPECT_FALSE(child_surface1()->HasActiveFrame()); EXPECT_TRUE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), + EXPECT_THAT(child_surface1()->activation_dependencies(), UnorderedElementsAre(child_id2)); // Evict child_support1's current Surface. @@ -679,8 +647,8 @@ // The parent Surface should immediately activate. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); - EXPECT_FALSE(HasDeadline()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); + EXPECT_FALSE(parent_surface()->has_deadline()); } // This test verifies that if a surface has both a pending and active @@ -704,7 +672,7 @@ // Verify that the CompositorFrame is blocked on |child_id|. EXPECT_FALSE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id1)); testing::Mock::VerifyAndClearExpectations(&support_client_); @@ -721,12 +689,12 @@ // Verify that the child CompositorFrame activates immediately. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(child_surface1()->activation_dependencies(), IsEmpty()); // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Submit a new parent CompositorFrame to add a reference. parent_support().SubmitCompositorFrame( @@ -737,7 +705,7 @@ // Verify that the parent Surface has activated. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // Verify that there is no temporary reference for the child and that // the reference from the parent to the child still exists. @@ -758,7 +726,7 @@ // |parent_id| are only from the active CompositorFrame. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), + EXPECT_THAT(parent_surface()->activation_dependencies(), UnorderedElementsAre(child_id2)); EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); @@ -770,7 +738,7 @@ // reference of |parent_id|. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(parent_surface()->activation_dependencies(), IsEmpty()); // The parent will not immediately refer to the child until it submits a new // CompositorFrame with the reference. EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); @@ -1115,18 +1083,15 @@ MakeCompositorFrame({parent_id1}, empty_surface_ids(), std::vector<TransferableResource>())); - EXPECT_TRUE(HasDeadline()); - - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); + EXPECT_TRUE(parent_surface()->has_deadline()); // Advance BeginFrames to trigger a deadline. for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_TRUE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_TRUE(display_surface()->has_deadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); } - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_FALSE(HasDeadline()); + SendNextBeginFrame(); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_FALSE(display_surface()->HasPendingFrame()); @@ -1179,20 +1144,21 @@ MakeCompositorFrame({parent_id1}, {parent_id1}, std::vector<TransferableResource>())); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(display_surface()->has_deadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); // Advance BeginFrames to trigger a deadline. This activates the // CompositorFrame submitted above. - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_TRUE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_TRUE(display_surface()->has_deadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); } - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_FALSE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_FALSE(display_surface()->has_deadline()); + EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); @@ -1203,12 +1169,15 @@ display_id.local_surface_id(), MakeCompositorFrame({parent_id2}, empty_surface_ids(), std::vector<TransferableResource>())); + EXPECT_TRUE(display_surface()->has_deadline()); // Now |parent_id1| is only kept alive by the active |display_id| frame. parent_support().SubmitCompositorFrame( parent_id2.local_surface_id(), MakeCompositorFrame({child_id}, empty_surface_ids(), std::vector<TransferableResource>())); + EXPECT_TRUE(display_surface()->has_deadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); // SurfaceDependencyTracker should now be tracking |display_id|, |parent_id1| // and |parent_id2|. By activating the pending |display_id| frame by deadline, @@ -1216,11 +1185,11 @@ // SurfaceDependencyTracker is in the process of activating surfaces. This // should not cause a crash or use-after-free. for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_TRUE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_TRUE(display_surface()->has_deadline()); } - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_FALSE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_FALSE(display_surface()->has_deadline()); } // This test verifies that a CompositorFrame will only blocked on embedded @@ -1242,11 +1211,11 @@ EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(display_surface()->has_deadline()); // Verify that the display CompositorFrame will only block on |parent_id1| but // not |parent_id2|. - EXPECT_THAT(display_surface()->blocking_surfaces(), + EXPECT_THAT(display_surface()->activation_dependencies(), UnorderedElementsAre(parent_id1)); // Verify that the display surface holds no references while its // CompositorFrame is pending. @@ -1257,10 +1226,10 @@ parent_support().SubmitCompositorFrame(parent_id1.local_surface_id(), MakeCompositorFrame()); - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); - EXPECT_THAT(display_surface()->blocking_surfaces(), IsEmpty()); + EXPECT_THAT(display_surface()->activation_dependencies(), IsEmpty()); } // This test verifies that a late arriving CompositorFrame activates immediately @@ -1277,18 +1246,16 @@ EXPECT_TRUE(display_surface()->HasPendingFrame()); EXPECT_FALSE(display_surface()->HasActiveFrame()); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(display_surface()->has_deadline()); // Advance BeginFrames to trigger a deadline. This activates the // CompositorFrame submitted above. - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_TRUE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_TRUE(display_surface()->has_deadline()); } - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_FALSE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_FALSE(display_surface()->has_deadline()); EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); @@ -1298,11 +1265,65 @@ parent_id1.local_surface_id(), MakeCompositorFrame({child_id1}, empty_surface_ids(), std::vector<TransferableResource>())); - EXPECT_FALSE(HasDeadline()); + EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); } +// This test verifies that a late arriving CompositorFrame activates immediately +// along with its subtree and does not trigger a new deadline. +TEST_F(SurfaceSynchronizationTest, MultiLevelLateArrivingDependency) { + const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); + const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); + const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); + const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); + + display_support().SubmitCompositorFrame( + display_id.local_surface_id(), + MakeCompositorFrame({parent_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(display_surface()->HasPendingFrame()); + EXPECT_FALSE(display_surface()->HasActiveFrame()); + EXPECT_TRUE(display_surface()->has_deadline()); + + // Issue some BeginFrames to trigger the deadline and activate the display's + // surface. |parent_id| is now late. Advance BeginFrames to trigger a + // deadline. + for (int i = 0; i < 4; ++i) { + EXPECT_TRUE(display_surface()->has_deadline()); + SendNextBeginFrame(); + } + EXPECT_FALSE(display_surface()->HasPendingFrame()); + EXPECT_TRUE(display_surface()->HasActiveFrame()); + EXPECT_FALSE(display_surface()->has_deadline()); + + // The child surface is not currently causally linked to the display's + // surface and so it gets a separate deadline. + child_support1().SubmitCompositorFrame( + child_id.local_surface_id(), + MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(child_surface1()->HasPendingFrame()); + EXPECT_FALSE(child_surface1()->HasActiveFrame()); + EXPECT_TRUE(child_surface1()->has_deadline()); + + // Submitting a CompositorFrame to the parent surface creates a dependency + // chain from the display to the parent to the child, allowing them all to + // assume the same deadline. Both the parent and the child are determined to + // be late and activate immediately. + parent_support().SubmitCompositorFrame( + parent_id.local_surface_id(), + MakeCompositorFrame({child_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_FALSE(parent_surface()->HasPendingFrame()); + EXPECT_TRUE(parent_surface()->HasActiveFrame()); + EXPECT_FALSE(parent_surface()->has_deadline()); + + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + EXPECT_FALSE(child_surface1()->has_deadline()); +} + // This test verifies that CompositorFrames submitted to a surface referenced // by a parent CompositorFrame as a fallback will be rejected and ACK'ed // immediately. @@ -1331,6 +1352,7 @@ child_id1.local_surface_id(), MakeCompositorFrame(empty_surface_ids(), empty_surface_ids(), {resource})); + EXPECT_FALSE(child_surface1()->has_deadline()); testing::Mock::VerifyAndClearExpectations(&support_client_); // The parent is blocked on |child_id2| and references |child_id1|. The @@ -1340,7 +1362,7 @@ parent_id1.local_surface_id(), MakeCompositorFrame({child_id2}, {child_id1}, std::vector<TransferableResource>())); - EXPECT_TRUE(HasDeadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_FALSE(parent_surface()->HasActiveFrame()); @@ -1363,14 +1385,12 @@ // Advance BeginFrames to trigger a deadline. This activates the // CompositorFrame submitted to the parent. - BeginFrameArgs args = - CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE, 0, 1); for (int i = 0; i < 3; ++i) { - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_TRUE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_TRUE(parent_surface()->has_deadline()); } - begin_frame_source()->TestOnBeginFrame(args); - EXPECT_FALSE(HasDeadline()); + SendNextBeginFrame(); + EXPECT_FALSE(parent_surface()->has_deadline()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_TRUE(parent_surface()->HasActiveFrame()); @@ -1385,5 +1405,193 @@ testing::Mock::VerifyAndClearExpectations(&support_client_); } +// This test verifies that two surface subtrees have independent deadlines. +TEST_F(SurfaceSynchronizationTest, IndependentDeadlines) { + const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); + const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); + const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); + const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); + + child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), + MakeCompositorFrame()); + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + + child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), + MakeCompositorFrame()); + EXPECT_FALSE(child_surface2()->HasPendingFrame()); + EXPECT_TRUE(child_surface2()->HasActiveFrame()); + + parent_support().SubmitCompositorFrame( + parent_id1.local_surface_id(), + MakeCompositorFrame({child_id1, child_id2}, empty_surface_ids(), + std::vector<TransferableResource>())); + + EXPECT_FALSE(parent_surface()->HasPendingFrame()); + EXPECT_TRUE(parent_surface()->HasActiveFrame()); + EXPECT_FALSE(parent_surface()->has_deadline()); + + // Submit another CompositorFrame to |child_id1| that blocks on + // |arbitrary_id|. + child_support1().SubmitCompositorFrame( + child_id1.local_surface_id(), + MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + EXPECT_TRUE(child_surface1()->has_deadline()); + + // Advance to the next BeginFrame. |child_id1|'s pending Frame should activate + // after 3 frames. + SendNextBeginFrame(); + + // Submit another CompositorFrame to |child_id2| that blocks on + // |arbitrary_id|. + child_support2().SubmitCompositorFrame( + child_id2.local_surface_id(), + MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(child_surface2()->HasPendingFrame()); + EXPECT_TRUE(child_surface2()->HasActiveFrame()); + EXPECT_TRUE(child_surface2()->has_deadline()); + + // If we issue another two BeginFrames both children should remain blocked. + for (int i = 0; i < 2; ++i) { + SendNextBeginFrame(); + EXPECT_TRUE(child_surface1()->has_deadline()); + EXPECT_TRUE(child_surface2()->has_deadline()); + } + + // Issuing another BeginFrame should activate the frame in |child_id1| but not + // |child_id2|. This verifies that |child_id1| and |child_id2| have different + // deadlines. + SendNextBeginFrame(); + + EXPECT_FALSE(child_surface1()->has_deadline()); + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + + EXPECT_TRUE(child_surface2()->has_deadline()); + EXPECT_TRUE(child_surface2()->HasPendingFrame()); + EXPECT_TRUE(child_surface2()->HasActiveFrame()); + + // Issuing another BeginFrame should activate the frame in |child_id2|. + SendNextBeginFrame(); + + EXPECT_FALSE(child_surface2()->has_deadline()); + EXPECT_FALSE(child_surface2()->HasPendingFrame()); + EXPECT_TRUE(child_surface2()->HasActiveFrame()); +} + +// This test verifies that a child inherits its deadline from its dependent +// parent (embedder) surface. +TEST_F(SurfaceSynchronizationTest, DeadlineInheritance) { + const SurfaceId parent_id1 = MakeSurfaceId(kParentFrameSink, 1); + const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); + const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); + + parent_support().SubmitCompositorFrame( + parent_id1.local_surface_id(), + MakeCompositorFrame({child_id1}, empty_surface_ids(), + std::vector<TransferableResource>())); + + EXPECT_TRUE(parent_surface()->HasPendingFrame()); + EXPECT_FALSE(parent_surface()->HasActiveFrame()); + EXPECT_TRUE(parent_surface()->has_deadline()); + + // Advance to the next BeginFrame. The parent surface will activate in 3 + // frames. + SendNextBeginFrame(); + + child_support1().SubmitCompositorFrame( + child_id1.local_surface_id(), + MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(child_surface1()->HasPendingFrame()); + EXPECT_FALSE(child_surface1()->HasActiveFrame()); + EXPECT_TRUE(child_surface1()->has_deadline()); + + // If we issue another three BeginFrames then both the parent and the child + // should activate, verifying that the child's deadline is inherited from the + // parent. + for (int i = 0; i < 3; ++i) { + EXPECT_TRUE(parent_surface()->has_deadline()); + EXPECT_TRUE(child_surface1()->has_deadline()); + SendNextBeginFrame(); + } + + // Verify that both the parent and child have activated. + EXPECT_FALSE(parent_surface()->HasPendingFrame()); + EXPECT_TRUE(parent_surface()->HasActiveFrame()); + EXPECT_FALSE(parent_surface()->has_deadline()); + + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + EXPECT_FALSE(child_surface1()->has_deadline()); +} + +// This test verifies that all surfaces within a dependency chain will +// ultimately inherit the same deadline even if the grandchild is available +// before the child. +TEST_F(SurfaceSynchronizationTest, MultiLevelDeadlineInheritance) { + const SurfaceId display_id = MakeSurfaceId(kDisplayFrameSink, 1); + const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); + const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); + const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); + + display_support().SubmitCompositorFrame( + display_id.local_surface_id(), + MakeCompositorFrame({parent_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(display_surface()->HasPendingFrame()); + EXPECT_FALSE(display_surface()->HasActiveFrame()); + EXPECT_TRUE(display_surface()->has_deadline()); + + // Issue a BeginFrame to move closer to the display's deadline. + SendNextBeginFrame(); + + // The child surface is not currently causally linked to the display's + // surface and so it gets a separate deadline. + child_support1().SubmitCompositorFrame( + child_id.local_surface_id(), + MakeCompositorFrame({arbitrary_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(child_surface1()->HasPendingFrame()); + EXPECT_FALSE(child_surface1()->HasActiveFrame()); + EXPECT_TRUE(child_surface1()->has_deadline()); + + // Submitting a CompositorFrame to the parent frame creates a dependency + // chain from the display to the parent to the child, allowing them all to + // assume the same deadline. + parent_support().SubmitCompositorFrame( + parent_id.local_surface_id(), + MakeCompositorFrame({child_id}, empty_surface_ids(), + std::vector<TransferableResource>())); + EXPECT_TRUE(parent_surface()->HasPendingFrame()); + EXPECT_FALSE(parent_surface()->HasActiveFrame()); + EXPECT_TRUE(parent_surface()->has_deadline()); + + // Advancing the time by three BeginFrames should activate all the surfaces. + for (int i = 0; i < 3; ++i) { + EXPECT_TRUE(display_surface()->has_deadline()); + EXPECT_TRUE(parent_surface()->has_deadline()); + EXPECT_TRUE(child_surface1()->has_deadline()); + SendNextBeginFrame(); + } + + // Verify that all the CompositorFrames have activated. + EXPECT_FALSE(display_surface()->HasPendingFrame()); + EXPECT_TRUE(display_surface()->HasActiveFrame()); + EXPECT_FALSE(display_surface()->has_deadline()); + + EXPECT_FALSE(parent_surface()->HasPendingFrame()); + EXPECT_TRUE(parent_surface()->HasActiveFrame()); + EXPECT_FALSE(parent_surface()->has_deadline()); + + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + EXPECT_FALSE(child_surface1()->has_deadline()); +} + } // namespace test } // namespace cc
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 1c3aa01..7cd13b9 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -1766,7 +1766,6 @@ if (is_android && is_component_build) { deps += [ "//device/gamepad", - "//device/generic_sensor", "//device/sensors", ] }
diff --git a/chrome/VERSION b/chrome/VERSION index fb47ad7b..f73397dc 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=61 MINOR=0 -BUILD=3150 +BUILD=3151 PATCH=0
diff --git a/chrome/android/java/AndroidManifest.xml b/chrome/android/java/AndroidManifest.xml index 9262ecb..f243f11 100644 --- a/chrome/android/java/AndroidManifest.xml +++ b/chrome/android/java/AndroidManifest.xml
@@ -397,6 +397,7 @@ <activity android:name="org.chromium.chrome.browser.FullscreenWebContentsActivity" android:theme="@style/MainTheme" android:exported="false" + android:noHistory="true" {{ self.chrome_activity_common() }} {{ self.supports_video_persistence() }} > </activity>
diff --git a/chrome/android/java/res/layout/tabular_context_menu_page.xml b/chrome/android/java/res/layout/tabular_context_menu_page.xml index bb290a2..ab0cbc9 100644 --- a/chrome/android/java/res/layout/tabular_context_menu_page.xml +++ b/chrome/android/java/res/layout/tabular_context_menu_page.xml
@@ -54,7 +54,8 @@ <ListView android:id="@+id/selectable_items" android:layout_width="match_parent" - android:layout_height="wrap_content" + android:layout_height="0dp" + android:layout_weight="1" android:paddingTop="8dp" android:paddingBottom="8dp" android:dividerHeight="0dp"
diff --git a/chrome/android/java/res/layout/tabular_context_menu_row.xml b/chrome/android/java/res/layout/tabular_context_menu_row.xml index b638933..fa3d95d 100644 --- a/chrome/android/java/res/layout/tabular_context_menu_row.xml +++ b/chrome/android/java/res/layout/tabular_context_menu_row.xml
@@ -2,13 +2,16 @@ <!-- 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. --> -<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" +<org.chromium.chrome.browser.widget.BoundedLinearLayout + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:chrome="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingStart="15dp" android:minHeight="40dp" + chrome:maxHeight="40dp" tools:ignore="UseCompoundDrawables"> <ImageView android:id="@+id/context_menu_icon" @@ -42,4 +45,4 @@ android:id="@+id/context_menu_right_padding" android:layout_width="15dp" android:layout_height="wrap_content"/> -</LinearLayout> +</org.chromium.chrome.browser.widget.BoundedLinearLayout>
diff --git a/chrome/android/java/res/values/dimens.xml b/chrome/android/java/res/values/dimens.xml index 8f2718c..f3318fa 100644 --- a/chrome/android/java/res/values/dimens.xml +++ b/chrome/android/java/res/values/dimens.xml
@@ -473,6 +473,7 @@ <dimen name="context_menu_header_image_min_size">56dp</dimen> <dimen name="context_menu_header_image_max_size">56dp</dimen> <dimen name="context_menu_max_width">500dp</dimen> + <dimen name="context_menu_min_padding">20dp</dimen> <!-- Divider Dimensions --> <dimen name="divider_height">1dp</dimen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java index f7e35b8f..53004273 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java
@@ -9,6 +9,7 @@ import android.os.Handler; import android.os.Looper; +import org.chromium.base.BuildInfo; import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.VisibleForTesting; @@ -283,7 +284,7 @@ */ @CalledByNative public boolean shouldDetectVideoFullscreen() { - return false; + return BuildInfo.isAtLeastO(); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/FullscreenWebContentsActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/FullscreenWebContentsActivity.java index 560788568..f764672 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/FullscreenWebContentsActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/FullscreenWebContentsActivity.java
@@ -8,23 +8,29 @@ import android.content.ComponentName; import android.content.Intent; import android.provider.Browser; +import android.view.View; +import android.view.ViewGroup; import org.chromium.base.Log; import org.chromium.chrome.R; +import org.chromium.chrome.browser.compositor.layouts.LayoutManagerDocument; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.AsyncTabParamsManager; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabReparentingParams; import org.chromium.chrome.browser.util.IntentUtils; -import org.chromium.chrome.browser.webapps.FullScreenActivity; +import org.chromium.chrome.browser.widget.ControlContainer; +import org.chromium.content_public.browser.WebContentsObserver; /** * An Activity used to display fullscreen WebContents. */ -public class FullscreenWebContentsActivity extends FullScreenActivity { +public class FullscreenWebContentsActivity extends SingleTabActivity { private static final String TAG = "FullWebConActivity"; + private WebContentsObserver mWebContentsObserver; + @Override protected Tab createTab() { assert getIntent().hasExtra(IntentHandler.EXTRA_TAB_ID); @@ -33,7 +39,7 @@ getIntent(), IntentHandler.EXTRA_TAB_ID, Tab.INVALID_TAB_ID); TabReparentingParams params = (TabReparentingParams) AsyncTabParamsManager.remove(tabId); - Tab tab; + final Tab tab; if (params != null) { tab = params.getTabToReparent(); tab.attachAndFinishReparenting(this, createTabDelegateFactory(), params); @@ -43,10 +49,37 @@ TabLaunchType.FROM_CHROME_UI, null, null); tab.initialize(null, getTabContentManager(), createTabDelegateFactory(), false, false); } + mWebContentsObserver = new WebContentsObserver(tab.getWebContents()) { + @Override + public void didFinishNavigation(String url, boolean isInMainFrame, boolean isErrorPage, + boolean hasCommitted, boolean isSameDocument, boolean isFragmentNavigation, + Integer pageTransition, int errorCode, String errorDescription, + int httpStatusCode) { + if (hasCommitted && isInMainFrame) { + // Notify the renderer to permanently hide the top controls since they do + // not apply to fullscreen content views. + tab.updateBrowserControlsState(tab.getBrowserControlsStateConstraints(), true); + } + } + }; return tab; } @Override + public void finishNativeInitialization() { + ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); + initializeCompositorContent(new LayoutManagerDocument(getCompositorViewHolder()), + (View) controlContainer, (ViewGroup) findViewById(android.R.id.content), + controlContainer); + + if (getFullscreenManager() != null) getFullscreenManager().setTab(getActivityTab()); + super.finishNativeInitialization(); + } + + @Override + protected void initializeToolbar() {} + + @Override protected int getControlContainerLayoutId() { // TODO(peconn): Determine if there's something more suitable to use here. return R.layout.webapp_control_container; @@ -91,7 +124,6 @@ intent.setClass(tab.getActivity(), FullscreenWebContentsActivity.class); intent.putExtra(IntentHandler.EXTRA_PARENT_COMPONENT, activity.getComponentName()); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // In multiwindow mode we want both activities to be able to launch independent // FullscreenWebContentsActivity's. intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); @@ -107,6 +139,16 @@ // has none. } + ChromeActivity tabActivity = tab.getActivity(); + if (tabActivity instanceof FullscreenWebContentsActivity) { + FullscreenWebContentsActivity fullscreenActivity = + (FullscreenWebContentsActivity) tabActivity; + if (fullscreenActivity.mWebContentsObserver != null) { + fullscreenActivity.mWebContentsObserver.destroy(); + fullscreenActivity.mWebContentsObserver = null; + } + } + // TODO(peconn): Deal with tricky multiwindow scenarios. } intent.putExtra(Browser.EXTRA_APPLICATION_ID, activity.getPackageName());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/OWNERS index 31ee0a7..b6fc493 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/OWNERS
@@ -1,4 +1,5 @@ per-file ShortcutHelper.java=dominickn@chromium.org +per-file SingleTabActivity.java=dominickn@chromium.org # This is For simple changes of adding/removing features. For more structural # changes, use the normal OWNERS rules.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/SingleTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/SingleTabActivity.java new file mode 100644 index 0000000..140c3e6 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/SingleTabActivity.java
@@ -0,0 +1,140 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser; + +import android.content.Intent; +import android.util.Pair; + +import org.chromium.base.annotations.SuppressFBWarnings; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabDelegateFactory; +import org.chromium.chrome.browser.tab.TabUma.TabCreationState; +import org.chromium.chrome.browser.tabmodel.SingleTabModelSelector; +import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; +import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; +import org.chromium.chrome.browser.tabmodel.TabModelSelector; +import org.chromium.chrome.browser.tabmodel.document.TabDelegate; +import org.chromium.content_public.browser.LoadUrlParams; + +import java.io.File; + +/** + * Base class for task-focused activities that need to display a single tab. + * + * Example applications that might use this Activity would be webapps and streaming media + * activities - anything where maintaining multiple tabs is unnecessary. + */ +@SuppressFBWarnings("URF_UNREAD_FIELD") +public abstract class SingleTabActivity extends ChromeActivity { + protected static final String BUNDLE_TAB_ID = "tabId"; + protected static final String BUNDLE_TAB_URL = "tabUrl"; + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + setIntent(intent); + } + + @Override + protected TabModelSelector createTabModelSelector() { + return new SingleTabModelSelector(this, false, false) { + @Override + public Tab openNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent, + boolean incognito) { + getTabCreator(incognito).createNewTab(loadUrlParams, type, parent); + return null; + } + }; + } + + @Override + protected Pair<TabDelegate, TabDelegate> createTabCreators() { + return Pair.create(createTabDelegate(false), createTabDelegate(true)); + } + + /** Creates TabDelegates for opening new Tabs. */ + protected TabDelegate createTabDelegate(boolean incognito) { + return new TabDelegate(incognito); + } + + @Override + public void initializeState() { + super.initializeState(); + + Tab tab = createTab(); + getTabModelSelector().setTab(tab); + tab.show(TabSelectionType.FROM_NEW); + } + + @Override + public SingleTabModelSelector getTabModelSelector() { + return (SingleTabModelSelector) super.getTabModelSelector(); + } + + /** + * Creates the {@link Tab} used by the {@link SingleTabActivity}. + * If the {@code savedInstanceState} exists, then the user did not intentionally close the app + * by swiping it away in the recent tasks list. In that case, we try to restore the tab from + * disk. + */ + protected Tab createTab() { + Tab tab = null; + boolean unfreeze = false; + + int tabId = Tab.INVALID_TAB_ID; + String tabUrl = null; + if (getSavedInstanceState() != null) { + tabId = getSavedInstanceState().getInt(BUNDLE_TAB_ID, Tab.INVALID_TAB_ID); + tabUrl = getSavedInstanceState().getString(BUNDLE_TAB_URL); + } + + if (tabId != Tab.INVALID_TAB_ID && tabUrl != null && getActivityDirectory() != null) { + // Restore the tab. + TabState tabState = TabState.restoreTabState(getActivityDirectory(), tabId); + tab = new Tab(tabId, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), + TabLaunchType.FROM_RESTORE, TabCreationState.FROZEN_ON_RESTORE, tabState); + unfreeze = true; + } + + if (tab == null) { + tab = new Tab(Tab.INVALID_TAB_ID, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), + TabLaunchType.FROM_CHROME_UI, null, null); + } + + tab.initialize(null, getTabContentManager(), createTabDelegateFactory(), false, unfreeze); + return tab; + } + + /** + * @return {@link TabDelegateFactory} to be used while creating the associated {@link Tab}. + */ + protected TabDelegateFactory createTabDelegateFactory() { + return new TabDelegateFactory(); + } + + /** + * @return {@link File} pointing at a directory specific for this class. + */ + protected File getActivityDirectory() { + return null; + } + + @Override + protected boolean handleBackPressed() { + Tab tab = getActivityTab(); + if (tab == null) return false; + + if (exitFullscreenIfShowing()) return true; + + if (tab.canGoBack()) { + tab.goBack(); + return true; + } + return false; + } + + @Override + public void onCheckForUpdate(boolean updateAvailable) {} +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java index 42f3af6..52bec84 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulator.java
@@ -68,13 +68,13 @@ @IntDef({ NORMAL_MODE, /* Default mode */ CUSTOM_TAB_MODE, /* Custom tab mode */ - FULLSCREEN_TAB_MODE /* Full screen mode */ + WEB_APP_MODE /* Full screen mode */ }) public @interface ContextMenuMode {} public static final int NORMAL_MODE = 0; public static final int CUSTOM_TAB_MODE = 1; - public static final int FULLSCREEN_TAB_MODE = 2; + public static final int WEB_APP_MODE = 2; // Items that are included in all context menus. private static final Set<? extends ContextMenuItem> BASE_WHITELIST = @@ -103,7 +103,7 @@ ChromeContextMenuItem.OPEN_IN_BROWSER_ID)); // Additional items for fullscreen tabs mode. - private static final Set<? extends ContextMenuItem> FULLSCREEN_TAB_MODE_WHITELIST = + private static final Set<? extends ContextMenuItem> WEB_APP_MODE_WHITELIST = Collections.unmodifiableSet( CollectionUtil.newHashSet(ChromeContextMenuItem.OPEN_IN_CHROME)); @@ -285,8 +285,8 @@ Set<ContextMenuItem> supportedOptions = new HashSet<>(); if (FirstRunStatus.getFirstRunFlowComplete()) { supportedOptions.addAll(BASE_WHITELIST); - if (mMode == FULLSCREEN_TAB_MODE) { - supportedOptions.addAll(FULLSCREEN_TAB_MODE_WHITELIST); + if (mMode == WEB_APP_MODE) { + supportedOptions.addAll(WEB_APP_MODE_WHITELIST); } else if (mMode == CUSTOM_TAB_MODE) { supportedOptions.addAll(CUSTOM_TAB_MODE_WHITELIST); } else {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/TabularContextMenuViewPager.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/TabularContextMenuViewPager.java index 55a3ad5..dd76948c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/TabularContextMenuViewPager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/TabularContextMenuViewPager.java
@@ -16,7 +16,8 @@ * pager. */ public class TabularContextMenuViewPager extends ViewPager { - private static final double MAX_WIDTH_PROPORTION = 0.75; + private final int mContextMenuMinimumPaddingPx = + getResources().getDimensionPixelSize(R.dimen.context_menu_min_padding); public TabularContextMenuViewPager(Context context) { super(context); @@ -38,13 +39,19 @@ // getCurrentItem() does not take into account the tab layout unlike getChildCount(). int currentItemsIndex = getCurrentItem() + 1; - // TODO(injae): Fix sizing on orientation changes (crbug.com/731173) - int contextMenuWidth = (int) Math.min( - getResources().getDisplayMetrics().widthPixels * MAX_WIDTH_PROPORTION, + // The width of the context menu is defined so that it leaves space between itself and the + // screen's edges. It is also bounded to a max size to prevent the menu from stretching + // across a large display (e.g. a tablet screen). + int deviceWidthPx = getResources().getDisplayMetrics().widthPixels; + int contextMenuWidth = Math.min(deviceWidthPx - 2 * mContextMenuMinimumPaddingPx, getResources().getDimensionPixelSize(R.dimen.context_menu_max_width)); widthMeasureSpec = MeasureSpec.makeMeasureSpec(contextMenuWidth, MeasureSpec.EXACTLY); + // The height of the context menu is calculated as the sum of: + // 1. The tab bar's height, which is only visible when the context menu requires it + // (i.e. an ImageLink is clicked) + // 2. The height of the View being displayed for the current tab. for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); @@ -61,7 +68,12 @@ break; } } + + // Cap the height of the context menu so that it fits on the screen without touching the + // screen's edges. int fullHeight = menuHeight + tabHeight; + int deviceHeightPx = getResources().getDisplayMetrics().heightPixels; + fullHeight = Math.min(fullHeight, deviceHeightPx - 2 * mContextMenuMinimumPaddingPx); heightMeasureSpec = MeasureSpec.makeMeasureSpec(fullHeight, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index 709dcc6..7d83ded 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -537,7 +537,7 @@ } DataUseTabUIManager.onCustomTabInitialNavigation(mMainTab, packageName, url); - if (!mHasCreatedTabEarly && !successfulStateRestore) { + if (!mHasCreatedTabEarly && !successfulStateRestore && !mMainTab.isLoading()) { loadUrlInTab(mMainTab, new LoadUrlParams(url), IntentHandler.getTimestampFromIntent(getIntent())); } @@ -611,6 +611,7 @@ webContents = takeAsyncWebContents(); if (webContents != null) { webContentsStateOnLaunch = WEBCONTENTS_STATE_TRANSFERRED_WEBCONTENTS; + webContents.resumeLoadingCreatedWebContents(); } else { webContents = WarmupManager.getInstance().takeSpareWebContents(false, false); if (webContents != null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/OWNERS index 5700d9b..906bc109 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/invalidation/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/invalidation/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org zea@chromium.org
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 d62de3bf..96f253f 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
@@ -201,7 +201,8 @@ * Rule 1: Non-autofill before autofill. * Rule 2: Complete instruments before incomplete intsruments. * Rule 3: Exact type matching instruments before non-exact type matching instruments. - * Rule 4: Frequently and recently used instruments before rarely and non-recently used + * Rule 4: Preselectable instruments before non-preselectable instruments. + * Rule 5: Frequently and recently used instruments before rarely and non-recently used * instruments. */ private static final Comparator<PaymentInstrument> PAYMENT_INSTRUMENT_COMPARATOR = @@ -222,6 +223,14 @@ - (a.isExactlyMatchingMerchantRequest() ? 1 : 0); if (typeMatch != 0) return typeMatch; + // Preselectable instruments before non-preselectable instruments. + // Note that this only affects service worker payment apps' instruments for now + // since autofill payment instruments have already been sorted by preselect + // after sorting by completeness and typeMatch. And the other payment apps' + // instruments can always be preselected. + int canPreselect = (b.canPreselect() ? 1 : 0) - (a.canPreselect() ? 1 : 0); + if (canPreselect != 0) return canPreselect; + // More frequently and recently used instruments first. return compareInstrumentsByFrecency(b, a); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentApp.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentApp.java index 7a73a7e..6447d6a1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentApp.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentApp.java
@@ -4,18 +4,24 @@ package org.chromium.chrome.browser.payments; +import android.graphics.drawable.Drawable; import android.os.Handler; +import android.text.TextUtils; import org.chromium.content_public.browser.WebContents; +import org.chromium.payments.mojom.PaymentDetailsModifier; import org.chromium.payments.mojom.PaymentItem; import org.chromium.payments.mojom.PaymentMethodData; +import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import javax.annotation.Nullable; + /** * This app class represents a service worker based payment app. * @@ -24,26 +30,39 @@ * * @see https://w3c.github.io/webpayments-payment-handler/ */ -public class ServiceWorkerPaymentApp implements PaymentApp { +public class ServiceWorkerPaymentApp extends PaymentInstrument implements PaymentApp { private final WebContents mWebContents; - private final List<PaymentInstrument> mInstruments; + private final long mRegistrationId; + private final Drawable mIcon; private final Set<String> mMethodNames; + private final boolean mCanPreselect; /** * Build a service worker payment app instance per origin. * * @see https://w3c.github.io/webpayments-payment-handler/#structure-of-a-web-payment-app * - * @param webContents The web contents where PaymentRequest was invoked. - * @param instruments A list of payment instruments supported by the payment app. + * @param webContents The web contents where PaymentRequest was invoked. + * @param registrationId The registration id of the corresponding service worker payment app. + * @param label The label of the payment app. + * @param sublabel The sublabel of the payment app. + * @param icon The drawable icon of the payment app. + * @param methodNames A set of payment method names supported by the payment app. */ - public ServiceWorkerPaymentApp(WebContents webContents, List<PaymentInstrument> instruments) { + public ServiceWorkerPaymentApp(WebContents webContents, long registrationId, String label, + @Nullable String sublabel, @Nullable Drawable icon, String[] methodNames) { + super(label + sublabel, label, sublabel, icon); mWebContents = webContents; - mInstruments = instruments; + mRegistrationId = registrationId; + mIcon = icon; + + // Sublabel and/or icon are set to null if fetching or processing the corresponding web app + // manifest failed. Then do not preselect this payment app. + mCanPreselect = !TextUtils.isEmpty(sublabel) && icon != null; mMethodNames = new HashSet<>(); - for (PaymentInstrument instrument : instruments) { - mMethodNames.addAll(instrument.getInstrumentMethodNames()); + for (int i = 0; i < methodNames.length; i++) { + mMethodNames.add(methodNames[i]); } } @@ -54,8 +73,9 @@ new Handler().post(new Runnable() { @Override public void run() { - callback.onInstrumentsReady( - ServiceWorkerPaymentApp.this, Collections.unmodifiableList(mInstruments)); + List<PaymentInstrument> instruments = new ArrayList(); + instruments.add(ServiceWorkerPaymentApp.this); + callback.onInstrumentsReady(ServiceWorkerPaymentApp.this, instruments); } }); } @@ -67,17 +87,41 @@ @Override public boolean supportsMethodsAndData(Map<String, PaymentMethodData> methodsAndData) { - // TODO(tommyt): crbug.com/669876. Implement this for Service Worker Payment Apps. - return true; + Set<String> methodNames = new HashSet<>(methodsAndData.keySet()); + methodNames.retainAll(mMethodNames); + return !methodNames.isEmpty(); } @Override public String getAppIdentifier() { - return "Chrome_Service_Worker_Payment_App"; + return getIdentifier(); } @Override public int getAdditionalAppTextResourceId() { return 0; } + + @Override + public Set<String> getInstrumentMethodNames() { + return getAppMethodNames(); + } + + @Override + public void invokePaymentApp(String id, String merchantName, String origin, String iframeOrigin, + byte[][] unusedCertificateChain, Map<String, PaymentMethodData> methodData, + PaymentItem total, List<PaymentItem> displayItems, + Map<String, PaymentDetailsModifier> modifiers, InstrumentDetailsCallback callback) { + ServiceWorkerPaymentAppBridge.invokePaymentApp(mWebContents, mRegistrationId, origin, + iframeOrigin, id, new HashSet<>(methodData.values()), total, + new HashSet<>(modifiers.values()), callback); + } + + @Override + public void dismissInstrument() {} + + @Override + public boolean canPreselect() { + return mCanPreselect; + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java index 99c8d7c..721fd36 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java
@@ -16,9 +16,6 @@ import org.chromium.payments.mojom.PaymentItem; import org.chromium.payments.mojom.PaymentMethodData; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; import java.util.Set; import javax.annotation.Nullable; @@ -50,38 +47,15 @@ * app. * @param total The PaymentItem that represents the total cost of the payment. * @param modifiers Payment method specific modifiers to the payment items and the total. - * @param instrumentId The ID of the PaymentInstrument that was selected by the user. * @param callback Called after the payment app is finished running. */ public static void invokePaymentApp(WebContents webContents, long registrationId, String origin, String iframeOrigin, String paymentRequestId, Set<PaymentMethodData> methodData, - PaymentItem total, Set<PaymentDetailsModifier> modifiers, String instrumentId, + PaymentItem total, Set<PaymentDetailsModifier> modifiers, PaymentInstrument.InstrumentDetailsCallback callback) { nativeInvokePaymentApp(webContents, registrationId, origin, iframeOrigin, paymentRequestId, methodData.toArray(new PaymentMethodData[0]), total, - modifiers.toArray(new PaymentDetailsModifier[0]), instrumentId, callback); - } - - @CalledByNative - private static List<PaymentInstrument> createInstrumentList() { - return new ArrayList<PaymentInstrument>(); - } - - @CalledByNative - private static void addInstrument(List<PaymentInstrument> instruments, WebContents webContents, - long swRegistrationId, String instrumentId, String label, String[] methodNameArray, - @Nullable Bitmap icon) { - Context context = ChromeActivity.fromWebContents(webContents); - if (context == null) return; - - Set<String> methodNames = new HashSet<String>(); - for (int i = 0; i < methodNameArray.length; i++) { - methodNames.add(methodNameArray[i]); - } - - instruments.add(new ServiceWorkerPaymentInstrument(webContents, swRegistrationId, - instrumentId, label, methodNames, - icon == null ? null : new BitmapDrawable(context.getResources(), icon))); + modifiers.toArray(new PaymentDetailsModifier[0]), callback); } @CalledByNative @@ -120,11 +94,17 @@ } @CalledByNative - private static void onPaymentAppCreated( - List<PaymentInstrument> instruments, WebContents webContents, Object callback) { + private static void onPaymentAppCreated(long registrationId, String label, + @Nullable String sublabel, @Nullable Bitmap icon, String[] methodNameArray, + WebContents webContents, Object callback) { assert callback instanceof PaymentAppFactory.PaymentAppCreatedCallback; + Context context = ChromeActivity.fromWebContents(webContents); + if (context == null) return; ((PaymentAppFactory.PaymentAppCreatedCallback) callback) - .onPaymentAppCreated(new ServiceWorkerPaymentApp(webContents, instruments)); + .onPaymentAppCreated(new ServiceWorkerPaymentApp(webContents, registrationId, label, + sublabel, + icon == null ? null : new BitmapDrawable(context.getResources(), icon), + methodNameArray)); } @CalledByNative @@ -160,5 +140,5 @@ private static native void nativeInvokePaymentApp(WebContents webContents, long registrationId, String topLevelOrigin, String paymentRequestOrigin, String paymentRequestId, PaymentMethodData[] methodData, PaymentItem total, PaymentDetailsModifier[] modifiers, - String instrumentKey, Object callback); + Object callback); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentInstrument.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentInstrument.java deleted file mode 100644 index 8f0cfe7..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentInstrument.java +++ /dev/null
@@ -1,75 +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. - -package org.chromium.chrome.browser.payments; - -import android.graphics.drawable.Drawable; - -import org.chromium.content_public.browser.WebContents; -import org.chromium.payments.mojom.PaymentDetailsModifier; -import org.chromium.payments.mojom.PaymentItem; -import org.chromium.payments.mojom.PaymentMethodData; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -/** - * This instrument class represents a single payment instrument for a service - * worker based payment app. - * - * @see org.chromium.chrome.browser.payments.ServiceWorkerPaymentApp - * - * @see https://w3c.github.io/webpayments-payment-handler/ - */ -public class ServiceWorkerPaymentInstrument extends PaymentInstrument { - private final WebContents mWebContents; - private final long mSWRegistrationId; - private final String mInstrumentId; - private final Set<String> mMethodNames; - - /** - * Build a service worker based payment instrument. - * - * @see https://w3c.github.io/webpayments-payment-apps-api/#payment-app-options - * - * @param webContents The web contents where PaymentRequest was invoked. - * @param swRegistrationId The registration id of the corresponding service worker payment app. - * @param instrumentId The unique id of the payment instrument. - * @param label The label of the payment instrument. - * @param methodNames A set of payment method names supported by the payment instrument. - * @param icon The drawable icon of the payment instrument. - */ - public ServiceWorkerPaymentInstrument(WebContents webContents, long swRegistrationId, - String instrumentId, String label, Set<String> methodNames, @Nullable Drawable icon) { - super(Long.toString(swRegistrationId) + "#" + instrumentId, label, null /* sublabel */, - icon); - mWebContents = webContents; - mSWRegistrationId = swRegistrationId; - mInstrumentId = instrumentId; - mMethodNames = methodNames; - } - - @Override - public Set<String> getInstrumentMethodNames() { - return Collections.unmodifiableSet(mMethodNames); - } - - @Override - public void invokePaymentApp(String id, String merchantName, String origin, String iframeOrigin, - byte[][] unusedCertificateChain, Map<String, PaymentMethodData> methodData, - PaymentItem total, List<PaymentItem> displayItems, - Map<String, PaymentDetailsModifier> modifiers, InstrumentDetailsCallback callback) { - ServiceWorkerPaymentAppBridge.invokePaymentApp(mWebContents, mSWRegistrationId, origin, - iframeOrigin, id, new HashSet<>(methodData.values()), total, - new HashSet<>(modifiers.values()), mInstrumentId, callback); - } - - @Override - public void dismissInstrument() {} -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/signin/OWNERS index 21dc744..f5f6e7ea 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/OWNERS
@@ -1,2 +1 @@ gogerald@chromium.org -maxbogue@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/ImageFetcher.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/ImageFetcher.java index cc54812..6b3a0f32 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/ImageFetcher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/ImageFetcher.java
@@ -253,7 +253,7 @@ */ private void ensureIconIsAvailable(String pageUrl, String iconUrl, boolean isLargeIcon, boolean isTemporary, FaviconHelper.IconAvailabilityCallback callback) { - if (mHost.getActiveTab().getWebContents() != null) { + if (mHost.getActiveTab() != null && mHost.getActiveTab().getWebContents() != null) { getFaviconHelper().ensureIconIsAvailable(mProfile, mHost.getActiveTab().getWebContents(), pageUrl, iconUrl, isLargeIcon, isTemporary, callback);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/sync/OWNERS index 91e7103..4171a3fc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org zea@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenActivity.java deleted file mode 100644 index a68604a0..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenActivity.java +++ /dev/null
@@ -1,215 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.webapps; - -import android.content.Intent; -import android.util.Pair; -import android.view.View; -import android.view.ViewGroup; - -import org.chromium.base.annotations.SuppressFBWarnings; -import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeActivity; -import org.chromium.chrome.browser.TabState; -import org.chromium.chrome.browser.compositor.layouts.LayoutManagerDocument; -import org.chromium.chrome.browser.tab.EmptyTabObserver; -import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.tab.TabDelegateFactory; -import org.chromium.chrome.browser.tab.TabUma.TabCreationState; -import org.chromium.chrome.browser.tabmodel.SingleTabModelSelector; -import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; -import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; -import org.chromium.chrome.browser.tabmodel.TabModelSelector; -import org.chromium.chrome.browser.tabmodel.document.TabDelegate; -import org.chromium.chrome.browser.widget.ControlContainer; -import org.chromium.content.browser.ContentViewCore; -import org.chromium.content_public.browser.LoadUrlParams; -import org.chromium.content_public.browser.WebContents; -import org.chromium.content_public.browser.WebContentsObserver; - -import java.io.File; - -/** - * Base class for task-focused activities that need to display web content in a nearly UI-less - * Chrome (InfoBars still appear). - * - * This is vaguely analogous to a WebView, but in Chrome. Example applications that might use this - * Activity would be webapps and streaming media activities - anything where user interaction with - * the regular browser's UI is either unnecessary or undesirable. - * Subclasses can override {@link #createUI()} if they need something more exotic. - */ -@SuppressFBWarnings("URF_UNREAD_FIELD") -public abstract class FullScreenActivity extends ChromeActivity { - protected static final String BUNDLE_TAB_ID = "tabId"; - protected static final String BUNDLE_TAB_URL = "tabUrl"; - private static final String TAG = "FullScreenActivity"; - - private WebContents mWebContents; - @SuppressWarnings("unused") // Reference needed to prevent GC. - private WebContentsObserver mWebContentsObserver; - - @Override - protected void onNewIntent(Intent intent) { - super.onNewIntent(intent); - setIntent(intent); - } - - @Override - protected TabModelSelector createTabModelSelector() { - return new SingleTabModelSelector(this, false, false) { - @Override - public Tab openNewTab(LoadUrlParams loadUrlParams, TabLaunchType type, Tab parent, - boolean incognito) { - getTabCreator(incognito).createNewTab(loadUrlParams, type, parent); - return null; - } - }; - } - - @Override - protected Pair<TabDelegate, TabDelegate> createTabCreators() { - return Pair.create(createTabDelegate(false), createTabDelegate(true)); - } - - /** Creates TabDelegates for opening new Tabs. */ - protected TabDelegate createTabDelegate(boolean incognito) { - return new TabDelegate(incognito); - } - - @Override - public void initializeState() { - super.initializeState(); - - Tab tab = createTab(); - getTabModelSelector().setTab(tab); - handleTabContentChanged(); - tab.show(TabSelectionType.FROM_NEW); - } - - @Override - public void finishNativeInitialization() { - ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); - initializeCompositorContent(new LayoutManagerDocument(getCompositorViewHolder()), - (View) controlContainer, (ViewGroup) findViewById(android.R.id.content), - controlContainer); - - if (getFullscreenManager() != null) getFullscreenManager().setTab(getActivityTab()); - super.finishNativeInitialization(); - } - - @Override - protected void initializeToolbar() { } - - @Override - public SingleTabModelSelector getTabModelSelector() { - return (SingleTabModelSelector) super.getTabModelSelector(); - } - - /** - * Creates the {@link Tab} used by the FullScreenActivity. - * If the {@code savedInstanceState} exists, then the user did not intentionally close the app - * by swiping it away in the recent tasks list. In that case, we try to restore the tab from - * disk. - */ - protected Tab createTab() { - Tab tab = null; - boolean unfreeze = false; - - int tabId = Tab.INVALID_TAB_ID; - String tabUrl = null; - if (getSavedInstanceState() != null) { - tabId = getSavedInstanceState().getInt(BUNDLE_TAB_ID, Tab.INVALID_TAB_ID); - tabUrl = getSavedInstanceState().getString(BUNDLE_TAB_URL); - } - - if (tabId != Tab.INVALID_TAB_ID && tabUrl != null && getActivityDirectory() != null) { - // Restore the tab. - TabState tabState = TabState.restoreTabState(getActivityDirectory(), tabId); - tab = new Tab(tabId, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), - TabLaunchType.FROM_RESTORE, - TabCreationState.FROZEN_ON_RESTORE, tabState); - unfreeze = true; - } - - if (tab == null) { - tab = new Tab(Tab.INVALID_TAB_ID, Tab.INVALID_TAB_ID, false, this, getWindowAndroid(), - TabLaunchType.FROM_CHROME_UI, null, null); - } - - tab.initialize(null, getTabContentManager(), createTabDelegateFactory(), false, unfreeze); - tab.addObserver(new EmptyTabObserver() { - @Override - public void onContentChanged(Tab tab) { - assert tab == getActivityTab(); - handleTabContentChanged(); - } - }); - return tab; - } - - private void handleTabContentChanged() { - final Tab tab = getActivityTab(); - assert tab != null; - - WebContents webContents = tab.getWebContents(); - if (mWebContents == webContents) return; - - // Clean up any old references to the previous WebContents. - if (mWebContentsObserver != null) { - mWebContentsObserver.destroy(); - mWebContentsObserver = null; - } - - mWebContents = webContents; - if (mWebContents == null) return; - - ContentViewCore.fromWebContents(webContents).setFullscreenRequiredForOrientationLock(false); - mWebContentsObserver = new WebContentsObserver(webContents) { - @Override - public void didFinishNavigation(String url, boolean isInMainFrame, boolean isErrorPage, - boolean hasCommitted, boolean isSameDocument, boolean isFragmentNavigation, - Integer pageTransition, int errorCode, String errorDescription, - int httpStatusCode) { - if (hasCommitted && isInMainFrame) { - // Notify the renderer to permanently hide the top controls since they do - // not apply to fullscreen content views. - tab.updateBrowserControlsState(tab.getBrowserControlsStateConstraints(), true); - } - } - }; - } - - /** - * @return {@link TabDelegateFactory} to be used while creating the associated {@link Tab}. - */ - protected TabDelegateFactory createTabDelegateFactory() { - return new FullScreenDelegateFactory(); - } - - /** - * @return {@link File} pointing at a directory specific for this class. - */ - protected File getActivityDirectory() { - return null; - } - - @Override - protected boolean handleBackPressed() { - Tab tab = getActivityTab(); - if (tab == null) return false; - - if (exitFullscreenIfShowing()) return true; - - if (tab.canGoBack()) { - tab.goBack(); - return true; - } - return false; - } - - @Override - public void onCheckForUpdate(boolean updateAvailable) { - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenDelegateFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenDelegateFactory.java deleted file mode 100644 index a91116a..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/FullScreenDelegateFactory.java +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.webapps; - -import org.chromium.chrome.browser.contextmenu.ChromeContextMenuPopulator; -import org.chromium.chrome.browser.contextmenu.ContextMenuPopulator; -import org.chromium.chrome.browser.tab.BrowserControlsVisibilityDelegate; -import org.chromium.chrome.browser.tab.Tab; -import org.chromium.chrome.browser.tab.TabContextMenuItemDelegate; -import org.chromium.chrome.browser.tab.TabDelegateFactory; -import org.chromium.chrome.browser.tab.TabStateBrowserControlsVisibilityDelegate; - -/** - * A {@link TabDelegateFactory} class to be used in all {@link Tab} instances owned - * by a {@link FullScreenActivity}. - */ -public class FullScreenDelegateFactory extends TabDelegateFactory { - @Override - public ContextMenuPopulator createContextMenuPopulator(Tab tab) { - return new ChromeContextMenuPopulator(new TabContextMenuItemDelegate(tab), - ChromeContextMenuPopulator.FULLSCREEN_TAB_MODE); - } - - @Override - public BrowserControlsVisibilityDelegate createBrowserControlsVisibilityDelegate(Tab tab) { - return new TabStateBrowserControlsVisibilityDelegate(tab) { - @Override - public boolean canAutoHideBrowserControls() { - return false; - } - }; - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkVersionManager.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkVersionManager.java index 6fe56ec..9cdf2c4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkVersionManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkVersionManager.java
@@ -7,6 +7,7 @@ import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; +import android.os.Build; import org.chromium.base.CommandLine; import org.chromium.base.ContextUtils; @@ -30,6 +31,13 @@ "org.chromium.chrome.browser.webapps.extracted_dex_version"; /** + * Name of the shared preference for the Android OS version at the time that the dex was last + * extracted from Chrome's assets and optimized. + */ + private static final String LAST_SDK_VERSION_PREF = + "org.chromium.chrome.browser.webapps.last_sdk_version"; + + /** * Tries to extract the WebAPK runtime dex from the Chrome APK if it has not tried already. * Should not be called on UI thread. */ @@ -38,19 +46,19 @@ public static void updateWebApksIfNeeded() { assert !ThreadUtils.runningOnUiThread(); - // TODO(pkotwicz|hanxi): Detect whether the manifest of installed APKs needs to be updated. - // (crbug.com/604513) - SharedPreferences preferences = ContextUtils.getAppSharedPreferences(); int extractedDexVersion = preferences.getInt(EXTRACTED_DEX_VERSION_PREF, -1); + int lastSdkVersion = preferences.getInt(LAST_SDK_VERSION_PREF, -1); if (!CommandLine.getInstance().hasSwitch( ChromeSwitches.ALWAYS_EXTRACT_WEBAPK_RUNTIME_DEX_ON_STARTUP) - && extractedDexVersion == WebApkVersion.CURRENT_RUNTIME_DEX_VERSION) { + && extractedDexVersion == WebApkVersion.CURRENT_RUNTIME_DEX_VERSION + && lastSdkVersion == Build.VERSION.SDK_INT) { return; } SharedPreferences.Editor editor = preferences.edit(); editor.putInt(EXTRACTED_DEX_VERSION_PREF, WebApkVersion.CURRENT_RUNTIME_DEX_VERSION); + editor.putInt(LAST_SDK_VERSION_PREF, Build.VERSION.SDK_INT); editor.apply(); Context context = ContextUtils.getApplicationContext();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java index 5e7d270..278044d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappActivity.java
@@ -27,7 +27,9 @@ import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.R; import org.chromium.chrome.browser.IntentHandler; +import org.chromium.chrome.browser.SingleTabActivity; import org.chromium.chrome.browser.TabState; +import org.chromium.chrome.browser.compositor.layouts.LayoutManagerDocument; import org.chromium.chrome.browser.document.DocumentUtils; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.tab.EmptyTabObserver; @@ -37,8 +39,12 @@ import org.chromium.chrome.browser.tabmodel.document.TabDelegate; import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.chrome.browser.util.UrlUtilities; +import org.chromium.chrome.browser.widget.ControlContainer; +import org.chromium.content.browser.ContentViewCore; import org.chromium.content.browser.ScreenOrientationProvider; import org.chromium.content_public.browser.LoadUrlParams; +import org.chromium.content_public.browser.WebContents; +import org.chromium.content_public.browser.WebContentsObserver; import org.chromium.net.NetworkChangeNotifier; import org.chromium.ui.base.PageTransition; @@ -48,7 +54,7 @@ /** * Displays a webapp in a nearly UI-less Chrome (InfoBars still appear). */ -public class WebappActivity extends FullScreenActivity { +public class WebappActivity extends SingleTabActivity { public static final String WEBAPP_SCHEME = "webapp"; private static final String TAG = "WebappActivity"; @@ -66,6 +72,9 @@ private final WebappDirectoryManager mDirectoryManager; + private WebContents mWebContents; + private WebContentsObserver mWebContentsObserver; + protected WebappInfo mWebappInfo; private WebappSplashScreenController mSplashController; @@ -166,12 +175,21 @@ } initializeUI(getSavedInstanceState()); + ControlContainer controlContainer = (ControlContainer) findViewById(R.id.control_container); + initializeCompositorContent(new LayoutManagerDocument(getCompositorViewHolder()), + (View) controlContainer, (ViewGroup) findViewById(android.R.id.content), + controlContainer); + + if (getFullscreenManager() != null) getFullscreenManager().setTab(getActivityTab()); mSplashController.onFinishedNativeInit(getActivityTab()); super.finishNativeInitialization(); mIsInitialized = true; } @Override + protected void initializeToolbar() {} + + @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (getActivityTab() != null) { @@ -412,6 +430,13 @@ }; } + @Override + protected Tab createTab() { + Tab tab = super.createTab(); + handleTabContentChanged(tab); + return tab; + } + protected TabObserver createTabObserver() { return new EmptyTabObserver() { @@ -495,6 +520,46 @@ public void onDidDetachInterstitialPage(Tab tab) { updateUrlBar(); } + + // TODO(piotrs): Remove this and clean up handleTabContentChanged() once pre-rendering + // is disabled and WebContents swapping can no longer happen + // (crbug.com/678332). + @Override + public void onContentChanged(Tab tab) { + assert tab == getActivityTab(); + handleTabContentChanged(tab); + } + }; + } + + private void handleTabContentChanged(final Tab tab) { + assert tab != null; + + WebContents webContents = tab.getWebContents(); + if (mWebContents == webContents) return; + + // Clean up any old references to the previous WebContents. + if (mWebContentsObserver != null) { + mWebContentsObserver.destroy(); + mWebContentsObserver = null; + } + + mWebContents = webContents; + if (mWebContents == null) return; + + ContentViewCore.fromWebContents(webContents).setFullscreenRequiredForOrientationLock(false); + mWebContentsObserver = new WebContentsObserver(webContents) { + @Override + public void didFinishNavigation(String url, boolean isInMainFrame, boolean isErrorPage, + boolean hasCommitted, boolean isSameDocument, boolean isFragmentNavigation, + Integer pageTransition, int errorCode, String errorDescription, + int httpStatusCode) { + if (hasCommitted && isInMainFrame) { + // Notify the renderer to permanently hide the top controls since they do + // not apply to fullscreen content views. + tab.updateBrowserControlsState(tab.getBrowserControlsStateConstraints(), true); + } + } }; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDelegateFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDelegateFactory.java index 5b9fd31..a6121a9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDelegateFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebappDelegateFactory.java
@@ -9,9 +9,13 @@ import org.chromium.base.ContextUtils; import org.chromium.chrome.browser.ShortcutHelper; +import org.chromium.chrome.browser.SingleTabActivity; +import org.chromium.chrome.browser.contextmenu.ChromeContextMenuPopulator; +import org.chromium.chrome.browser.contextmenu.ContextMenuPopulator; import org.chromium.chrome.browser.tab.BrowserControlsVisibilityDelegate; import org.chromium.chrome.browser.tab.InterceptNavigationDelegateImpl; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tab.TabContextMenuItemDelegate; import org.chromium.chrome.browser.tab.TabDelegateFactory; import org.chromium.chrome.browser.tab.TabWebContentsDelegateAndroid; import org.chromium.chrome.browser.util.IntentUtils; @@ -19,9 +23,9 @@ /** * A {@link TabDelegateFactory} class to be used in all {@link Tab} instances owned by a - * {@link FullScreenActivity}. + * {@link SingleTabActivity}. */ -public class WebappDelegateFactory extends FullScreenDelegateFactory { +public class WebappDelegateFactory extends TabDelegateFactory { private static class WebappWebContentsDelegateAndroid extends TabWebContentsDelegateAndroid { private final WebappActivity mActivity; @@ -65,6 +69,12 @@ } @Override + public ContextMenuPopulator createContextMenuPopulator(Tab tab) { + return new ChromeContextMenuPopulator( + new TabContextMenuItemDelegate(tab), ChromeContextMenuPopulator.WEB_APP_MODE); + } + + @Override public TabWebContentsDelegateAndroid createWebContentsDelegate(Tab tab) { return new WebappWebContentsDelegateAndroid(mActivity, tab); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageButton.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageButton.java index 3678694..b1c05d8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageButton.java
@@ -20,15 +20,21 @@ private ImageViewTinter mTinter; public TintedImageButton(Context context) { - this(context, null); + super(context); + init(null, 0); } public TintedImageButton(Context context, AttributeSet attrs) { - this(context, attrs, 0); + super(context, attrs); + init(attrs, 0); } public TintedImageButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); + init(attrs, defStyle); + } + + private void init(AttributeSet attrs, int defStyle) { mTinter = new ImageViewTinter(this, attrs, defStyle); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageView.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageView.java index 02713e0b..fcd4e267 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/TintedImageView.java
@@ -20,15 +20,21 @@ private ImageViewTinter mTinter; public TintedImageView(Context context) { - this(context, null); + super(context); + init(null, 0); } public TintedImageView(Context context, AttributeSet attrs) { - this(context, attrs, 0); + super(context, attrs, 0); + init(attrs, 0); } public TintedImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); + init(attrs, defStyle); + } + + private void init(AttributeSet attrs, int defStyle) { mTinter = new ImageViewTinter(this, attrs, defStyle); }
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index f1475f1..8b1fadd 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -58,6 +58,7 @@ "java/src/org/chromium/chrome/browser/RepostFormWarningDialog.java", "java/src/org/chromium/chrome/browser/SearchGeolocationDisclosureTabHelper.java", "java/src/org/chromium/chrome/browser/ServiceTabLauncher.java", + "java/src/org/chromium/chrome/browser/SingleTabActivity.java", "java/src/org/chromium/chrome/browser/SnackbarActivity.java", "java/src/org/chromium/chrome/browser/SSLClientCertificateRequest.java", "java/src/org/chromium/chrome/browser/ShortcutHelper.java", @@ -773,7 +774,6 @@ "java/src/org/chromium/chrome/browser/payments/PaymentResponseHelper.java", "java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentApp.java", "java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java", - "java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentInstrument.java", "java/src/org/chromium/chrome/browser/payments/ShippingStrings.java", "java/src/org/chromium/chrome/browser/payments/SslValidityChecker.java", "java/src/org/chromium/chrome/browser/payments/ui/BillingAddressAdapter.java", @@ -1168,8 +1168,6 @@ "java/src/org/chromium/chrome/browser/webapps/AddToHomescreenManager.java", "java/src/org/chromium/chrome/browser/webapps/ChromeWebApkHost.java", "java/src/org/chromium/chrome/browser/webapps/ChromeWebApkHostSignature.java", - "java/src/org/chromium/chrome/browser/webapps/FullScreenActivity.java", - "java/src/org/chromium/chrome/browser/webapps/FullScreenDelegateFactory.java", "java/src/org/chromium/chrome/browser/webapps/GooglePlayWebApkInstallDelegate.java", "java/src/org/chromium/chrome/browser/webapps/WebApkActivity.java", "java/src/org/chromium/chrome/browser/webapps/WebApkActivity0.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/FullscreenWebContentsActivityTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/FullscreenWebContentsActivityTest.java index d8071cc..3ca622f9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/FullscreenWebContentsActivityTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/FullscreenWebContentsActivityTest.java
@@ -129,15 +129,25 @@ @Test @MediumTest public void testFullscreen() throws Throwable { + Activity original = mActivity; + FullscreenWebContentsActivity fullscreenActivity = enterFullscreen(); DOMUtils.exitFullscreen(fullscreenActivity.getCurrentContentViewCore().getWebContents()); - waitForActivity(ChromeTabbedActivity.class); + ChromeTabbedActivity activity = waitForActivity(ChromeTabbedActivity.class); + + // Ensure we haven't started a new ChromeTabbedActivity, https://crbug.com/729805, + // https://crbug.com/729932. + Assert.assertSame(original, activity); } + /** + * Enters fullscreen then presses the back button to exit. + */ @Test @MediumTest public void testExitOnBack() throws Throwable { + Activity original = mActivity; final FullscreenWebContentsActivity fullscreenActivity = enterFullscreen(); mUiThreadTestRule.runOnUiThread(new Runnable() { @Override @@ -146,7 +156,11 @@ } }); - waitForActivity(ChromeTabbedActivity.class); + ChromeTabbedActivity activity = waitForActivity(ChromeTabbedActivity.class); + + // Ensure we haven't started a new ChromeTabbedActivity, https://crbug.com/729805, + // https://crbug.com/729932. + Assert.assertSame(original, activity); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java index 458c1d6..ef77ed49 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestServiceWorkerPaymentAppTest.java
@@ -17,10 +17,6 @@ import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.WebContents; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; @@ -38,49 +34,23 @@ public PaymentRequestTestRule mPaymentRequestTestRule = new PaymentRequestTestRule("payment_request_bobpay_test.html"); - /** Flag for installing a service worker payment app without any payment options. */ - private static final int NO_OPTIONS = 0; - - /** Flag for installing a service worker payment app with one payment option. */ - private static final int ONE_OPTION = 1; - - /** Flag for installing a service worker payment app with two options. */ - private static final int TWO_OPTIONS = 2; - /** * Installs a mock service worker based payment app for testing. * - * @param instrumentPresence Whether the manifest has any payment options. Either NO_OPTIONS - * ONE_OPTION or TWO_OPTIONS + * @param hasSupportedMethods Whether the mock payment app has supported payment methods. */ - private void installMockServiceWorkerPaymentApp(final int instrumentPresence) { + private void installMockServiceWorkerPaymentApp(final boolean hasSupportedMethods) { PaymentAppFactory.getInstance().addAdditionalFactory( new PaymentAppFactory.PaymentAppFactoryAddition() { @Override public void create(WebContents webContents, Set<String> methodNames, PaymentAppFactory.PaymentAppCreatedCallback callback) { - List<PaymentInstrument> instruments = new ArrayList<PaymentInstrument>(); - - if (instrumentPresence != NO_OPTIONS) { - instruments.add(new ServiceWorkerPaymentInstrument(webContents, - 0 /* swRegistrationId */, "new" /* instrumentId */, - "Create BobPay account" /* label */, - new HashSet<String>(Arrays.asList( - "https://bobpay.com", "basic-card")) /* methodNames */, - null /* icon*/)); - } - - if (instrumentPresence == TWO_OPTIONS) { - instruments.add(new ServiceWorkerPaymentInstrument(webContents, - 0 /* swRegistrationId */, "existing" /* instrumentId */, - "Existing BobPay account" /* label */, - new HashSet<String>(Arrays.asList( - "https://bobpay.com", "basic-card")) /* methodNames */, - null /* icon */)); - } - - callback.onPaymentAppCreated( - new ServiceWorkerPaymentApp(webContents, instruments)); + String[] supportedMethodNames = {"https://bobpay.com", "basic-card"}; + callback.onPaymentAppCreated(new ServiceWorkerPaymentApp(webContents, + 0 /* registrationId */, "BobPay" /* label */, + "https://bobpay.com" /* sublabel */, null /* icon */, + hasSupportedMethods ? supportedMethodNames + : new String[0] /* methodNames */)); callback.onAllPaymentAppsCreated(); } }); @@ -89,8 +59,9 @@ @Test @MediumTest @Feature({"Payments"}) - public void testNoOptions() throws InterruptedException, ExecutionException, TimeoutException { - installMockServiceWorkerPaymentApp(NO_OPTIONS); + public void testNoSupportedPaymentMethods() + throws InterruptedException, ExecutionException, TimeoutException { + installMockServiceWorkerPaymentApp(false); mPaymentRequestTestRule.openPageAndClickBuyAndWait(mPaymentRequestTestRule.getShowFailed()); mPaymentRequestTestRule.expectResultContains( new String[] {"show() rejected", "The payment method is not supported"}); @@ -99,18 +70,9 @@ @Test @MediumTest @Feature({"Payments"}) - public void testOneOption() throws InterruptedException, ExecutionException, TimeoutException { - installMockServiceWorkerPaymentApp(ONE_OPTION); - mPaymentRequestTestRule.triggerUIAndWait(mPaymentRequestTestRule.getReadyForInput()); - // TODO(tommyt): crbug.com/669876. Expand this test as we implement more - // service worker based payment app functionality. - } - - @Test - @MediumTest - @Feature({"Payments"}) - public void testTwoOptions() throws InterruptedException, ExecutionException, TimeoutException { - installMockServiceWorkerPaymentApp(TWO_OPTIONS); + public void testHasSupportedPaymentMethods() + throws InterruptedException, ExecutionException, TimeoutException { + installMockServiceWorkerPaymentApp(true); mPaymentRequestTestRule.triggerUIAndWait(mPaymentRequestTestRule.getReadyForInput()); // TODO(tommyt): crbug.com/669876. Expand this test as we implement more // service worker based payment app functionality.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OWNERS index 21dc744..f5f6e7ea 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OWNERS +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OWNERS
@@ -1,2 +1 @@ gogerald@chromium.org -maxbogue@chromium.org
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/sync/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/sync/OWNERS index 91e7103..4171a3fc 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/sync/OWNERS +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/sync/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org zea@chromium.org
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrTabTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrTabTest.java index 29c0e760..1c5bce9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrTabTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/WebVrTabTest.java
@@ -14,7 +14,6 @@ import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; -import org.chromium.base.test.util.FlakyTest; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.test.ChromeActivityTestRule; @@ -36,7 +35,6 @@ */ @Test @MediumTest - @FlakyTest(message = "crbug.com/738148") public void testPoseDataUnfocusedTab() throws InterruptedException { mVrTestRule.loadUrlAndAwaitInitialization( VrTestRule.getHtmlTestFile("test_pose_data_unfocused_tab"), PAGE_LOAD_TIMEOUT_S);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappNavigationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappNavigationTest.java index edf54da8..e7e96e3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappNavigationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebappNavigationTest.java
@@ -39,7 +39,7 @@ public class WebappNavigationTest { private static final String OFF_ORIGIN_URL = "https://www.google.com/"; private static final String WEB_APP_PATH = "/chrome/test/data/banners/manifest_test_page.html"; - private static final String OTHER_PAGE_PATH = + private static final String IN_SCOPE_PAGE_PATH = "/chrome/test/data/banners/manifest_no_service_worker.html"; @Rule @@ -97,7 +97,7 @@ @Test @SmallTest @Feature({"Webapps"}) - public void testNewTabLinkOpensInCct() throws Exception { + public void testOffScopeNewTabLinkOpensInCct() throws Exception { runWebappActivityAndWaitForIdle(mActivityTestRule.createIntent().putExtra( ShortcutHelper.EXTRA_THEME_COLOR, (long) Color.CYAN)); addAnchor("testId", OFF_ORIGIN_URL, "_blank"); @@ -114,6 +114,22 @@ @Test @SmallTest @Feature({"Webapps"}) + public void testInScopeNewTabLinkOpensInCct() throws Exception { + runWebappActivityAndWaitForIdle(mActivityTestRule.createIntent().putExtra( + ShortcutHelper.EXTRA_THEME_COLOR, (long) Color.CYAN)); + addAnchor("testId", mTestServer.getURL(IN_SCOPE_PAGE_PATH), "_blank"); + DOMUtils.clickNode( + mActivityTestRule.getActivity().getActivityTab().getContentViewCore(), "testId"); + CustomTabActivity customTab = activityListener.waitFor(CustomTabActivity.class); + mActivityTestRule.waitUntilIdle(customTab); + Assert.assertTrue( + mActivityTestRule.runJavaScriptCodeInCurrentTab("document.body.textContent") + .contains("Do-nothing page with a service worker")); + } + + @Test + @SmallTest + @Feature({"Webapps"}) public void testWindowOpenInCct() throws Exception { runWebappActivityAndWaitForIdle(mActivityTestRule.createIntent()); // Executing window.open() through a click on a link, @@ -141,10 +157,10 @@ @Test @SmallTest @Feature({"Webapps"}) - public void testInOriginNavigationStaysInWebapp() throws Exception { + public void testInScopeNavigationStaysInWebapp() throws Exception { runWebappActivityAndWaitForIdle(mActivityTestRule.createIntent()); - String otherPageUrl = mTestServer.getURL(OTHER_PAGE_PATH); + String otherPageUrl = mTestServer.getURL(IN_SCOPE_PAGE_PATH); mActivityTestRule.loadUrlInTab(otherPageUrl, PageTransition.LINK, mActivityTestRule.getActivity().getActivityTab());
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java index 21b36d1d..85d7f58a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuPopulatorTest.java
@@ -84,7 +84,7 @@ enabledItems = getEnabledItems(contextMenuParams); Assert.assertThat(enabledItems, Matchers.contains(ChromeContextMenuItem.COPY_LINK_ADDRESS)); - initializePopulator(ChromeContextMenuPopulator.FULLSCREEN_TAB_MODE); + initializePopulator(ChromeContextMenuPopulator.WEB_APP_MODE); enabledItems = getEnabledItems(contextMenuParams); Assert.assertThat(enabledItems, Matchers.contains(ChromeContextMenuItem.COPY_LINK_ADDRESS)); } @@ -102,7 +102,7 @@ enabledItems = getEnabledItems(contextMenuParams); Assert.assertThat(enabledItems, Matchers.empty()); - initializePopulator(ChromeContextMenuPopulator.FULLSCREEN_TAB_MODE); + initializePopulator(ChromeContextMenuPopulator.WEB_APP_MODE); enabledItems = getEnabledItems(contextMenuParams); Assert.assertThat(enabledItems, Matchers.empty()); } @@ -122,7 +122,7 @@ Assert.assertThat( enabledItems, Matchers.containsInAnyOrder(ChromeContextMenuItem.COPY_LINK_ADDRESS)); - initializePopulator(ChromeContextMenuPopulator.FULLSCREEN_TAB_MODE); + initializePopulator(ChromeContextMenuPopulator.WEB_APP_MODE); enabledItems = getEnabledItems(contextMenuParams); Assert.assertThat( enabledItems, Matchers.containsInAnyOrder(ChromeContextMenuItem.COPY_LINK_ADDRESS));
diff --git a/chrome/android/sync_shell/OWNERS b/chrome/android/sync_shell/OWNERS index 91e7103..4171a3fc 100644 --- a/chrome/android/sync_shell/OWNERS +++ b/chrome/android/sync_shell/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org zea@chromium.org
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index 712f8cf0..e0646f85 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -6093,10 +6093,25 @@ <message name="IDS_ARC_MIGRATE_ENCRYPTION_SUCCESS_MESSAGE" desc="Message of the toast shown on the first sign-in after the successfully completed migration needed for using Android apps."> Update successful. You can now use Android apps. </message> - <message name="IDS_VOICE_INTERACTION_VALUE_PROP_NO_THANKS_BUTTON" desc="Button label for skipping voice interaction value proposition"> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_LOADING" desc="Loading message of the voice interaction value prop dialog."> + Loading Google Assistant... + </message> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_TITLE" desc="Load error title of the voice interaction value prop dialog."> + Google Assistant + </message> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_MESSAGE" desc="Load error message of the voice interaction value prop dialog."> + Google Assistant was unable to load, please retry. + </message> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_SKIP_BUTTON" desc="Button label for skipping voice interaction value prop upon error."> + Skip + </message> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON" desc="Button label for retry loading voice interaction value prop."> + Retry + </message> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_NO_THANKS_BUTTON" desc="Button label for skipping voice interaction value proposition."> No thanks </message> - <message name="IDS_VOICE_INTERACTION_VALUE_PROP_CONTINUE_BUTTION" desc="Button label for accepting voice interaction value proposition"> + <message name="IDS_VOICE_INTERACTION_VALUE_PROP_CONTINUE_BUTTION" desc="Button label for accepting voice interaction value proposition."> Continue </message> <message name="IDS_WAIT_FOR_CONTAINER_READY_TITLE" desc="Title of the wait for container ready OOBE screen.">
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index e787e8d..4803f42 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd
@@ -959,21 +959,8 @@ </message> <!-- User pod remove sync warning text --> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles, with all statistics loaded correctly. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete $1 item from this device. To retrieve your data later, sign in to Chromium as $2.} - other {This will permanently delete $1 items from this device. To retrieve your data later, sign in to Chromium as $2.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_WITH_ERRORS" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles, with some statistics failed to load. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete at least $1 item from this device. To retrieve your data later, sign in to Chromium as $2.} - other {This will permanently delete at least $1 items from this device. To retrieve your data later, sign in to Chromium as $2.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_NOSTATS" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles with statistics unavailable. (Possible case: Chromium decided not to load the statistics of closed profiles.)"> - This will permanently delete your browsing data from this device. To retrieve your data later, sign in to Chromium as $2. - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_CALCULATING" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles when the statistics is still loading. $1 is always replaced by localized version of the ellipsis (...)."> - This will permanently delete at least <ph name="TOTAL_COUNT">$1<ex>...</ex></ph> items from this device. To retrieve your data later, sign in to Chromium as $2. + <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC" desc="Main text shown as a warning when attempting to remove an user."> + This person's browsing data will be deleted from this device. To recover the data, sign in to Chrome as $2. </message> <!-- Tutorial -->
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 82a8b4eb..45483c7b 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -10989,22 +10989,9 @@ <message name="IDS_USER_MANAGER_ADD_PROFILE_PROFILES_LOCKED_ERROR" desc="Error message displayed when trying to add a profile while all profiles are locked."> Please unlock your profile before adding a person. </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles, with all statistics loaded correctly. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete $1 item from this device.} - other {This will permanently delete $1 items from this device.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_WITH_ERRORS" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles, with some statistics failed to load. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete at least $1 item from this device.} - other {This will permanently delete at least $1 items from this device.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_NOSTATS" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles with statistics unavailable. (Possible case: Chromium decided not to load the statistics of closed profiles.)"> + <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC" desc="Main text shown as a warning when attempting to remove an user."> This will permanently delete your browsing data from this device. </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_CALCULATING" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles when the statistics is still loading. $1 is always replaced by localized version of the ellipsis (...)."> - This will permanently delete <ph name="TOTAL_COUNT">$1<ex>...</ex></ph> items from this device. - </message> <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_HISTORY" desc="The title of a statistic (browsing history) shown inside a table below the warning text when attempting to remove an user. A number is displayed next to it."> Browsing history </message>
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd index c49a0f1..6a45782 100644 --- a/chrome/app/google_chrome_strings.grd +++ b/chrome/app/google_chrome_strings.grd
@@ -963,21 +963,8 @@ </message> <!-- User pod remove sync warning text --> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles, with all statistics loaded correctly. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete $1 item from this device. To retrieve your data later, sign in to Chrome as $2.} - other {This will permanently delete $1 items from this device. To retrieve your data later, sign in to Chrome as $2.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_WITH_ERRORS" desc="Main text shown as a warning when attempting to remove an user. This case is for non-synced profiles, with some statistics failed to load. The symbol $1 will be substituted with custom JS code, so it should not be replaced by a #."> - {NUM_ITEMS, plural, - =1 {This will permanently delete at least $1 item from this device. To retrieve your data later, sign in to Chrome as $2.} - other {This will permanently delete at least $1 items from this device. To retrieve your data later, sign in to Chrome as $2.}} - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_NOSTATS" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles with statistics unavailable. (Possible case: Chrome decided not to load the statistics of closed profiles.)"> - This will permanently delete your browsing data from this device. To retrieve your data later, sign in to Chrome as $2. - </message> - <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_CALCULATING" desc="Main text shown as a warning when attempting to remove an user. This case is for synced profiles when the statistics is still loading. $1 is always replaced by localized version of the ellipsis (...)."> - This will permanently delete at least <ph name="TOTAL_COUNT">$1<ex>...</ex></ph> items from this device. To retrieve your data later, sign in to Chrome as $2. + <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC" desc="Main text shown as a warning when attempting to remove an user."> + This person's browsing data will be deleted from this device. To recover the data, sign in to Chrome as $2. </message> <!-- Tutorial -->
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 9196b25..19e685be 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1348,8 +1348,6 @@ "task_profiler/task_profiler_data_serializer.h", "themes/theme_service_win.cc", "themes/theme_service_win.h", - "thumbnails/simple_thumbnail_crop.cc", - "thumbnails/simple_thumbnail_crop.h", "thumbnails/thumbnail_list_source.cc", "thumbnails/thumbnail_list_source.h", "thumbnails/thumbnail_service.h", @@ -1359,7 +1357,8 @@ "thumbnails/thumbnail_service_impl.h", "thumbnails/thumbnail_tab_helper.cc", "thumbnails/thumbnail_tab_helper.h", - "thumbnails/thumbnailing_algorithm.h", + "thumbnails/thumbnail_utils.cc", + "thumbnails/thumbnail_utils.h", "thumbnails/thumbnailing_context.cc", "thumbnails/thumbnailing_context.h", "tracing/background_tracing_field_trial.cc", @@ -3923,7 +3922,10 @@ ] deps += [ "//media/mojo/interfaces" ] if (mojo_media_host == "browser") { - deps += [ "//media/mojo/services" ] + deps += [ + "//media/mojo/interfaces:constants", + "//media/mojo/services", + ] } }
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index 26e5f878..91b43b1 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS
@@ -47,6 +47,7 @@ "+services/data_decoder/public/cpp", "+services/device/public/cpp/device_features.h", "+services/identity/public", + "+services/metrics/public", "+services/preferences/public/cpp", "+services/preferences/public/interfaces", "+services/resource_coordinator/public/cpp",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9bfe576a..f75a00d 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -2486,6 +2486,9 @@ {"offline-pages-ct", flag_descriptions::kOfflinePagesCtName, flag_descriptions::kOfflinePagesCtDescription, kOsAndroid, FEATURE_VALUE_TYPE(offline_pages::kOfflinePagesCTFeature)}, + {"offline-pages-ct-v2", flag_descriptions::kOfflinePagesCtV2Name, + flag_descriptions::kOfflinePagesCtV2Description, kOsAndroid, + FEATURE_VALUE_TYPE(offline_pages::kOfflinePagesCTV2Feature)}, #endif // OS_ANDROID {"protect-sync-credential", flag_descriptions::kProtectSyncCredentialName, flag_descriptions::kProtectSyncCredentialDescription, kOsAll, @@ -3018,10 +3021,11 @@ SINGLE_VALUE_TYPE(switches::kShowCertLink)}, #endif - {"omnibox-ui-hide-suggestion-url-path", - flag_descriptions::kOmniboxUIHideSuggestionUrlPathName, - flag_descriptions::kOmniboxUIHideSuggestionUrlPathDescription, kOsDesktop, - FEATURE_VALUE_TYPE(omnibox::kUIExperimentHideSuggestionUrlPath)}, + {"omnibox-ui-elide-suggestion-url-after-host", + flag_descriptions::kOmniboxUIElideSuggestionUrlAfterHostName, + flag_descriptions::kOmniboxUIElideSuggestionUrlAfterHostDescription, + kOsDesktop, + FEATURE_VALUE_TYPE(omnibox::kUIExperimentElideSuggestionUrlAfterHost)}, {"omnibox-ui-hide-suggestion-url-scheme", flag_descriptions::kOmniboxUIHideSuggestionUrlSchemeName,
diff --git a/chrome/browser/android/bottombar/overlay_panel_content.cc b/chrome/browser/android/bottombar/overlay_panel_content.cc index 38e3fdeb..667a5656 100644 --- a/chrome/browser/android/bottombar/overlay_panel_content.cc +++ b/chrome/browser/android/bottombar/overlay_panel_content.cc
@@ -20,13 +20,12 @@ #include "components/navigation_interception/intercept_navigation_delegate.h" #include "components/variations/variations_associated_data.h" #include "components/web_contents_delegate_android/web_contents_delegate_android.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents.h" #include "jni/OverlayPanelContent_jni.h" #include "net/url_request/url_fetcher_impl.h" +#include "ui/android/view_android.h" using base::android::JavaParamRef; -using content::ContentViewCore; namespace {
diff --git a/chrome/browser/android/bottombar/overlay_panel_content.h b/chrome/browser/android/bottombar/overlay_panel_content.h index e7d71b39..67357ec 100644 --- a/chrome/browser/android/bottombar/overlay_panel_content.h +++ b/chrome/browser/android/bottombar/overlay_panel_content.h
@@ -55,12 +55,6 @@ const base::android::JavaParamRef<jobject>& jweb_contents, const base::android::JavaParamRef<jobject>& jweb_contents_delegate); - // Associate an Android View with the WebContents. - void SetViewAndroid( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj, - const base::android::JavaParamRef<jobject>& jcontent_view_core); - // Destroys the WebContents. void DestroyWebContents(JNIEnv* env, const base::android::JavaParamRef<jobject>& jobj);
diff --git a/chrome/browser/android/compositor/compositor_view.cc b/chrome/browser/android/compositor/compositor_view.cc index 4b525711..51019ae 100644 --- a/chrome/browser/android/compositor/compositor_view.cc +++ b/chrome/browser/android/compositor/compositor_view.cc
@@ -26,7 +26,6 @@ #include "chrome/browser/android/compositor/scene_layer/scene_layer.h" #include "chrome/browser/android/compositor/tab_content_manager.h" #include "content/public/browser/android/compositor.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/child_process_data.h" #include "content/public/browser/web_contents.h" #include "content/public/common/process_type.h"
diff --git a/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.h b/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.h index 72b21cb..4c156ef 100644 --- a/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.h +++ b/chrome/browser/android/compositor/scene_layer/contextual_search_scene_layer.h
@@ -54,7 +54,7 @@ jfloat dp_to_px, jfloat base_page_brightness, jfloat base_page_offset, - const base::android::JavaParamRef<jobject>& jcontent_view_core, + const base::android::JavaParamRef<jobject>& jweb_contents, jboolean search_promo_visible, jfloat search_promo_height, jfloat search_promo_opacity,
diff --git a/chrome/browser/android/compositor/scene_layer/toolbar_scene_layer.cc b/chrome/browser/android/compositor/scene_layer/toolbar_scene_layer.cc index 0ef559db..ea8b28e 100644 --- a/chrome/browser/android/compositor/scene_layer/toolbar_scene_layer.cc +++ b/chrome/browser/android/compositor/scene_layer/toolbar_scene_layer.cc
@@ -9,7 +9,6 @@ #include "cc/layers/solid_color_layer.h" #include "chrome/browser/android/compositor/layer/toolbar_layer.h" #include "content/public/browser/android/compositor.h" -#include "content/public/browser/android/content_view_core.h" #include "jni/ToolbarSceneLayer_jni.h" #include "ui/android/resources/resource_manager_impl.h" #include "ui/gfx/android/java_bitmap.h"
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc index 57845ce6d..3c691113 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc
@@ -34,7 +34,6 @@ #include "net/url_request/url_fetcher.h" #include "url/gurl.h" -using content::ContentViewCore; using content::RenderFrameHost; namespace {
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate.h b/chrome/browser/android/contextualsearch/contextual_search_delegate.h index e98bf1d..234f399 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate.h +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate.h
@@ -17,7 +17,6 @@ #include "base/values.h" #include "chrome/browser/android/contextualsearch/contextual_search_context.h" #include "chrome/browser/android/contextualsearch/resolved_search_term.h" -#include "content/public/browser/android/content_view_core.h" #include "net/url_request/url_fetcher_delegate.h" namespace content {
diff --git a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc index 932ec7c..ba3b811 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.cc
@@ -9,9 +9,9 @@ #include "base/metrics/metrics_hashes.h" #include "chrome/browser/browser_process.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" #include "jni/ContextualSearchRankerLoggerImpl_jni.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" ContextualSearchRankerLoggerImpl::ContextualSearchRankerLoggerImpl(JNIEnv* env, jobject obj)
diff --git a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h index 351b26c5..2561e3a 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h +++ b/chrome/browser/android/contextualsearch/contextual_search_ranker_logger_impl.h
@@ -6,7 +6,7 @@ #define CHROME_BROWSER_ANDROID_CONTEXTUALSEARCH_CONTEXTUAL_SEARCH_RANKER_LOGGER_IMPL_H_ #include "base/android/jni_android.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/gurl.h" class GURL;
diff --git a/chrome/browser/android/logo_service.cc b/chrome/browser/android/logo_service.cc index 5ef34a3..1e007e36 100644 --- a/chrome/browser/android/logo_service.cc +++ b/chrome/browser/android/logo_service.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/android/logo_service.h" +#include "base/command_line.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/threading/sequenced_worker_pool.h" @@ -13,6 +14,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" +#include "chrome/common/chrome_switches.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/search_engines/template_url_service.h" #include "components/search_provider_logos/fixed_logo_api.h" @@ -115,7 +117,15 @@ if (!template_url) return; - const bool use_fixed_logo = !template_url->logo_url().is_empty(); + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + GURL logo_url; + if (command_line->HasSwitch(switches::kSearchProviderLogoURL)) { + logo_url = GURL( + command_line->GetSwitchValueASCII(switches::kSearchProviderLogoURL)); + } else { + logo_url = template_url->logo_url(); + } + const bool use_fixed_logo = logo_url.is_valid(); if (!template_url->url_ref().HasGoogleBaseURLs( template_url_service->search_terms_data()) && @@ -131,8 +141,7 @@ base::MakeUnique<ChromeLogoDelegate>()); } - GURL url = - use_fixed_logo ? template_url->logo_url() : GetGoogleDoodleURL(profile_); + GURL url = use_fixed_logo ? logo_url : GetGoogleDoodleURL(profile_); auto parse_logo_response_callback = use_fixed_logo ? base::Bind(&search_provider_logos::ParseFixedLogoResponse)
diff --git a/chrome/browser/android/metrics/uma_session_stats.cc b/chrome/browser/android/metrics/uma_session_stats.cc index 6f266f0..bc80487b 100644 --- a/chrome/browser/android/metrics/uma_session_stats.cc +++ b/chrome/browser/android/metrics/uma_session_stats.cc
@@ -115,7 +115,7 @@ // created, or deleted, depending on consent. Starting up metrics services // will ensure that the consent file contains the ClientID. The ID is passed // to the renderer for crash reporting when things go wrong. - content::BrowserThread::GetBlockingPool()->PostTask( + GoogleUpdateSettings::CollectStatsConsentTaskRunner()->PostTask( FROM_HERE, base::Bind(base::IgnoreResult( GoogleUpdateSettings::SetCollectStatsConsent), consent));
diff --git a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc index 0c005766..8222388 100644 --- a/chrome/browser/android/payments/service_worker_payment_app_bridge.cc +++ b/chrome/browser/android/payments/service_worker_payment_app_bridge.cc
@@ -12,7 +12,6 @@ #include "chrome/browser/profiles/profile_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/payment_app_provider.h" -#include "content/public/browser/stored_payment_instrument.h" #include "content/public/browser/web_contents.h" #include "jni/ServiceWorkerPaymentAppBridge_jni.h" #include "third_party/WebKit/public/platform/modules/payments/payment_app.mojom.h" @@ -42,24 +41,19 @@ content::PaymentAppProvider::PaymentApps apps) { JNIEnv* env = AttachCurrentThread(); - // TODO(gogerald): Present payment app instead of instruments to user, - // crbug.com/735063. for (const auto& app_info : apps) { - ScopedJavaLocalRef<jobject> java_instruments = - Java_ServiceWorkerPaymentAppBridge_createInstrumentList(env); - for (const auto& instrument : app_info.second->instruments) { - Java_ServiceWorkerPaymentAppBridge_addInstrument( - env, java_instruments, jweb_contents, - app_info.second->registration_id, - ConvertUTF8ToJavaString(env, instrument->instrument_key), - ConvertUTF8ToJavaString(env, instrument->name), - ToJavaArrayOfStrings(env, instrument->enabled_methods), - instrument->icon == nullptr - ? nullptr - : gfx::ConvertToJavaBitmap(instrument->icon.get())); - } Java_ServiceWorkerPaymentAppBridge_onPaymentAppCreated( - env, java_instruments, jweb_contents, jcallback); + env, app_info.second->registration_id, + ConvertUTF8ToJavaString(env, app_info.second->name), + // Do not show duplicate information. + app_info.second->name.compare(app_info.second->origin.Serialize()) == 0 + ? nullptr + : ConvertUTF8ToJavaString(env, app_info.second->origin.Serialize()), + app_info.second->icon == nullptr + ? nullptr + : gfx::ConvertToJavaBitmap(app_info.second->icon.get()), + ToJavaArrayOfStrings(env, app_info.second->enabled_methods), + jweb_contents, jcallback); } Java_ServiceWorkerPaymentAppBridge_onAllPaymentAppsCreated(env, jcallback); } @@ -103,7 +97,6 @@ const JavaParamRef<jobjectArray>& jmethod_data, const JavaParamRef<jobject>& jtotal, const JavaParamRef<jobjectArray>& jmodifiers, - const JavaParamRef<jstring>& jinstrument_key, const JavaParamRef<jobject>& jcallback) { content::WebContents* web_contents = content::WebContents::FromJavaWebContents(jweb_contents); @@ -183,8 +176,6 @@ event_data->modifiers.push_back(std::move(modifier)); } - event_data->instrument_key = ConvertJavaStringToUTF8(env, jinstrument_key); - content::PaymentAppProvider::GetInstance()->InvokePaymentApp( web_contents->GetBrowserContext(), registration_id, std::move(event_data), base::Bind(&OnPaymentAppInvoked,
diff --git a/chrome/browser/android/signin/OWNERS b/chrome/browser/android/signin/OWNERS index 21dc744..f5f6e7ea 100644 --- a/chrome/browser/android/signin/OWNERS +++ b/chrome/browser/android/signin/OWNERS
@@ -1,2 +1 @@ gogerald@chromium.org -maxbogue@chromium.org
diff --git a/chrome/browser/android/signin/signin_manager_android.cc b/chrome/browser/android/signin/signin_manager_android.cc index a42225df..5fd3e001 100644 --- a/chrome/browser/android/signin/signin_manager_android.cc +++ b/chrome/browser/android/signin/signin_manager_android.cc
@@ -115,10 +115,11 @@ username_ = base::android::ConvertJavaStringToUTF8(env, username); policy::UserPolicySigninService* service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); - service->RegisterForPolicy( - username_, AccountTrackerServiceFactory::GetForProfile(profile_) - ->FindAccountInfoByEmail(username_) - .account_id, + service->RegisterForPolicyWithAccountId( + username_, + AccountTrackerServiceFactory::GetForProfile(profile_) + ->FindAccountInfoByEmail(username_) + .account_id, base::Bind(&SigninManagerAndroid::OnPolicyRegisterDone, weak_factory_.GetWeakPtr())); } @@ -341,10 +342,11 @@ base::android::ConvertJavaStringToUTF8(env, j_username); policy::UserPolicySigninService* service = policy::UserPolicySigninServiceFactory::GetForProfile(profile); - service->RegisterForPolicy( - username, AccountTrackerServiceFactory::GetForProfile(profile) - ->FindAccountInfoByEmail(username) - .account_id, + service->RegisterForPolicyWithAccountId( + username, + AccountTrackerServiceFactory::GetForProfile(profile) + ->FindAccountInfoByEmail(username) + .account_id, base::Bind(&UserManagementDomainFetched, callback)); }
diff --git a/chrome/browser/android/vr_shell/textures/render_text_wrapper.cc b/chrome/browser/android/vr_shell/textures/render_text_wrapper.cc index 487c67b..4576bed4 100644 --- a/chrome/browser/android/vr_shell/textures/render_text_wrapper.cc +++ b/chrome/browser/android/vr_shell/textures/render_text_wrapper.cc
@@ -29,4 +29,8 @@ render_text_->ApplyStyle(style, value, range); } +void RenderTextWrapper::SetStrikeThicknessFactor(SkScalar factor) { + render_text_->set_strike_thickness_factor(factor); +} + } // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/textures/render_text_wrapper.h b/chrome/browser/android/vr_shell/textures/render_text_wrapper.h index 2c2e5fbe..c959f4d6 100644 --- a/chrome/browser/android/vr_shell/textures/render_text_wrapper.h +++ b/chrome/browser/android/vr_shell/textures/render_text_wrapper.h
@@ -25,6 +25,8 @@ bool value, const gfx::Range& range); + virtual void SetStrikeThicknessFactor(SkScalar factor); + private: gfx::RenderText* render_text_ = nullptr;
diff --git a/chrome/browser/android/vr_shell/textures/url_bar_texture.cc b/chrome/browser/android/vr_shell/textures/url_bar_texture.cc index e4e8111..30cc4440 100644 --- a/chrome/browser/android/vr_shell/textures/url_bar_texture.cc +++ b/chrome/browser/android/vr_shell/textures/url_bar_texture.cc
@@ -33,6 +33,7 @@ static constexpr float kUrlRightMargin = 0.02; static constexpr float kSeparatorWidth = 0.002; static constexpr float kChipTextLineMargin = kHeight * 0.3; +static constexpr SkScalar kStrikeThicknessFactor = (SK_Scalar1 / 9); using security_state::SecurityLevel; @@ -403,6 +404,7 @@ render_text->ApplyColor(GetSchemeColor(security_level, color_scheme), scheme_range); if (security_level == SecurityLevel::DANGEROUS) { + render_text->SetStrikeThicknessFactor(kStrikeThicknessFactor); render_text->ApplyStyle(gfx::TextStyle::STRIKE, true, scheme_range); } }
diff --git a/chrome/browser/android/vr_shell/textures/url_bar_texture_unittest.cc b/chrome/browser/android/vr_shell/textures/url_bar_texture_unittest.cc index 452a5920..bd68de9 100644 --- a/chrome/browser/android/vr_shell/textures/url_bar_texture_unittest.cc +++ b/chrome/browser/android/vr_shell/textures/url_bar_texture_unittest.cc
@@ -36,8 +36,7 @@ static const SkColor kIncognitoSecureColor = 0xFFEDEDED; static const SkColor kIncognitoWarningColor = 0xFFEDEDED; -static constexpr int kUrlWidth = 400; -static constexpr int kUrlHeight = 30; +static constexpr int kUrlWidthPixels = 1024; class TestUrlBarTexture : public UrlBarTexture { public: @@ -46,14 +45,15 @@ void DrawURL(const GURL& gurl) { unsupported_mode_ = UiUnsupportedMode::kCount; - ToolbarState state(gurl, SecurityLevel::HTTP_SHOW_WARNING, + ToolbarState state(gurl, SecurityLevel::DANGEROUS, &toolbar::kHttpsInvalidIcon, base::UTF8ToUTF16("Not secure"), true); ASSERT_TRUE(state.should_display_url); SetToolbarState(state); + gfx::Size texture_size = GetPreferredTextureSize(kUrlWidthPixels); sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul( - texture_size_.width(), texture_size_.height()); - DrawAndLayout(surface->getCanvas(), texture_size_); + texture_size.width(), texture_size.height()); + DrawAndLayout(surface->getCanvas(), texture_size); } static void TestUrlStyling(const base::string16& formatted_url, @@ -75,8 +75,9 @@ gurl, url_formatter::kFormatUrlOmitAll, net::UnescapeRule::NORMAL, &parsed, nullptr, nullptr); + gfx::Size texture_size = GetPreferredTextureSize(kUrlWidthPixels); gfx::FontList font_list; - if (!GetFontList(kUrlHeight, text, &font_list)) + if (!GetFontList(texture_size.height(), text, &font_list)) return 0; return font_list.GetFonts().size(); @@ -94,17 +95,13 @@ unsupported_mode_ = mode; } - gfx::Size texture_size_; - gfx::Rect bounds_; UiUnsupportedMode unsupported_mode_ = UiUnsupportedMode::kCount; }; TestUrlBarTexture::TestUrlBarTexture() : UrlBarTexture(false, base::Bind(&TestUrlBarTexture::OnUnsupportedFeature, - base::Unretained(this))), - texture_size_(kUrlWidth, kUrlHeight), - bounds_(kUrlWidth, kUrlHeight) { + base::Unretained(this))) { gfx::FontList::SetDefaultFontDescription("Arial, Times New Roman, 15px"); } @@ -118,6 +115,7 @@ MOCK_METHOD2(SetStyle, void(gfx::TextStyle style, bool value)); MOCK_METHOD3(ApplyStyle, void(gfx::TextStyle style, bool value, const gfx::Range& range)); + MOCK_METHOD1(SetStrikeThicknessFactor, void(SkScalar)); private: DISALLOW_COPY_AND_ASSIGN(MockRenderText); @@ -188,11 +186,13 @@ EXPECT_CALL(mock_, SetColor(kDeemphasizedColor)); EXPECT_CALL(mock_, ApplyColor(kEmphasizedColor, gfx::Range(8, 16))); EXPECT_CALL(mock_, ApplyColor(kWarningColor, gfx::Range(0, 5))); + EXPECT_CALL(mock_, SetStrikeThicknessFactor(testing::_)); EXPECT_CALL(mock_, ApplyStyle(gfx::TextStyle::STRIKE, true, gfx::Range(0, 5))); EXPECT_CALL(mock_, SetColor(kIncognitoDeemphasizedColor)); EXPECT_CALL(mock_, ApplyColor(kIncognitoEmphasizedColor, gfx::Range(8, 16))); EXPECT_CALL(mock_, ApplyColor(kIncognitoWarningColor, gfx::Range(0, 5))); + EXPECT_CALL(mock_, SetStrikeThicknessFactor(testing::_)); EXPECT_CALL(mock_, ApplyStyle(gfx::TextStyle::STRIKE, true, gfx::Range(0, 5))); Verify("https://host.com/page", SecurityLevel::DANGEROUS,
diff --git a/chrome/browser/android/vr_shell/ui_elements/ui_element.h b/chrome/browser/android/vr_shell/ui_elements/ui_element.h index a45bed6..140677b9 100644 --- a/chrome/browser/android/vr_shell/ui_elements/ui_element.h +++ b/chrome/browser/android/vr_shell/ui_elements/ui_element.h
@@ -172,6 +172,13 @@ float opacity() const { return opacity_; } void set_opacity(float opacity) { opacity_ = opacity; } + // The corner radius of the object. Analogous to CSS's border-radius. This is + // in meters (same units as |size|). + float corner_radius() const { return corner_radius_; } + void set_corner_radius(float corner_radius) { + corner_radius_ = corner_radius; + } + // The computed opacity, incorporating opacity of parent objects. float computed_opacity() const { return computed_opacity_; } void set_computed_opacity(float computed_opacity) { @@ -282,6 +289,8 @@ // The opacity of the object (between 0.0 and 1.0). float opacity_ = 1.0f; + float corner_radius_ = 0.0f; + // The computed opacity, incorporating opacity of parent objects. float computed_opacity_ = 1.0f;
diff --git a/chrome/browser/android/vr_shell/ui_scene_manager.cc b/chrome/browser/android/vr_shell/ui_scene_manager.cc index dca383c..5e756c6 100644 --- a/chrome/browser/android/vr_shell/ui_scene_manager.cc +++ b/chrome/browser/android/vr_shell/ui_scene_manager.cc
@@ -46,6 +46,7 @@ static constexpr float kContentWidth = 0.96 * kContentDistance; static constexpr float kContentHeight = 0.64 * kContentDistance; static constexpr float kContentVerticalOffset = -0.1 * kContentDistance; +static constexpr float kContentCornerRadius = 0.005 * kContentWidth; static constexpr float kBackplaneSize = 1000.0; static constexpr float kBackgroundDistanceMultiplier = 1.414; @@ -271,6 +272,7 @@ element->set_size({kContentWidth, kContentHeight, 1}); element->set_translation({0, kContentVerticalOffset, -kContentDistance}); element->set_visible(false); + element->set_corner_radius(kContentCornerRadius); main_content_ = element.get(); content_elements_.push_back(element.get()); scene_->AddUiElement(std::move(element));
diff --git a/chrome/browser/android/vr_shell/vr_shell_gl.cc b/chrome/browser/android/vr_shell/vr_shell_gl.cc index 990c281..6501e15e 100644 --- a/chrome/browser/android/vr_shell/vr_shell_gl.cc +++ b/chrome/browser/android/vr_shell/vr_shell_gl.cc
@@ -1302,10 +1302,10 @@ break; } case Fill::CONTENT: { - gfx::RectF copy_rect(0, 0, 1, 1); vr_shell_renderer_->GetExternalTexturedQuadRenderer()->Draw( - content_texture_id_, transform, copy_rect, - element.computed_opacity()); + content_texture_id_, transform, render_size_vrshell_, + gfx::SizeF(element.size().x(), element.size().y()), + element.computed_opacity(), element.corner_radius()); break; } case Fill::SELF: {
diff --git a/chrome/browser/android/vr_shell/vr_shell_renderer.cc b/chrome/browser/android/vr_shell/vr_shell_renderer.cc index cde75103..64fec5c 100644 --- a/chrome/browser/android/vr_shell/vr_shell_renderer.cc +++ b/chrome/browser/android/vr_shell/vr_shell_renderer.cc
@@ -12,7 +12,9 @@ #include "base/memory/ptr_util.h" #include "base/trace_event/trace_event.h" #include "chrome/browser/android/vr_shell/vr_gl_util.h" +#include "ui/gfx/geometry/point3_f.h" #include "ui/gfx/geometry/rect_f.h" +#include "ui/gfx/geometry/vector3d_f.h" namespace { @@ -28,10 +30,102 @@ }; static constexpr GLushort kTexturedQuadIndices[6] = { 0, 1, 2, 1, 3, 2 }; + +// A rounded rect is subdivided into a number of triangles. +// _______________ +// | / _,-' \ | +// |/_,,-'______\| +// | /| +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// | / | +// |/____________| +// |\ _,-'' /| +// |_\ ,-'____ /_| +// +// Most of these do not contain an arc. To simplify the rendering of those +// that do, we include a "corner position" attribute. The corner position is +// the distance from the center of the nearest "corner circle". Only those +// triangles containing arcs have a non-zero corner position set. The result +// is that for interior triangles, their corner position is uniformly (0, 0). +// I.e., they are always deemed "inside". +// +// A further complication is that different corner radii will require these +// various triangles to be sized differently relative to one another. We +// would prefer not no continually recreate our vertex buffer, so we include +// another attribute, the "offset scalars". These scalars are only ever 1.0, +// 0.0, or -1.0 and control the addition or subtraction of the horizontal +// and vertical corner offset. This lets the corners of the triangles be +// computed in the vertex shader dynamically. It also happens that the +// texture coordinates can also be easily computed in the vertex shader. +// +// So if the the corner offsets are vr and hr where +// vr = corner_radius / height; +// hr = corner_radius / width; +// +// Then the full position is then given by +// p = (x + osx * hr, y + osy * vr, 0.0, 1.0) +// +// And the full texture coordinate is given by +// (0.5 + p[0], 0.5 - p[1]) +// +static constexpr float kRRectVertices[120] = { + // x y osx osy cpx cpy + -kHalfSize, kHalfSize, 0.0, -1.0, 0.0, 0.0, + -kHalfSize, kHalfSize, 1.0, 0.0, 0.0, 0.0, + kHalfSize, kHalfSize, -1.0, 0.0, 0.0, 0.0, + kHalfSize, kHalfSize, 0.0, -1.0, 0.0, 0.0, + -kHalfSize, -kHalfSize, 0.0, 1.0, 0.0, 0.0, + kHalfSize, -kHalfSize, 0.0, 1.0, 0.0, 0.0, + -kHalfSize, -kHalfSize, 1.0, 0.0, 0.0, 0.0, + kHalfSize, -kHalfSize, -1.0, 0.0, 0.0, 0.0, + -kHalfSize, kHalfSize, 0.0, -1.0, 1.0, 0.0, + -kHalfSize, kHalfSize, 0.0, 0.0, 1.0, 1.0, + -kHalfSize, kHalfSize, 1.0, 0.0, 0.0, 1.0, + kHalfSize, kHalfSize, -1.0, 0.0, 0.0, 1.0, + kHalfSize, kHalfSize, 0.0, 0.0, 1.0, 1.0, + kHalfSize, kHalfSize, 0.0, -1.0, 1.0, 0.0, + -kHalfSize, -kHalfSize, 0.0, 0.0, 1.0, 1.0, + -kHalfSize, -kHalfSize, 0.0, 1.0, 1.0, 0.0, + -kHalfSize, -kHalfSize, 1.0, 0.0, 0.0, 1.0, + kHalfSize, -kHalfSize, -1.0, 0.0, 0.0, 1.0, + kHalfSize, -kHalfSize, 0.0, 1.0, 1.0, 0.0, + kHalfSize, -kHalfSize, 0.0, 0.0, 1.0, 1.0, +}; + +static constexpr GLushort kRRectIndices[30] = { + 0, 2, 1, + 0, 3, 2, + 4, 3, 0, + 4, 5, 3, + 4, 6, 5, + 6, 7, 5, + 8, 10, 9, + 11, 13, 12, + 14, 16, 15, + 17, 19, 18, +}; + /* clang-format on */ static constexpr int kTexturedQuadPositionDataSize = 2; +static constexpr int kRRectPositionDataSize = 2; +static constexpr size_t kRRectPositionDataOffset = 0; +static constexpr int kRRectOffsetScaleDataSize = 2; +static constexpr size_t kRRectOffsetScaleDataOffset = 2 * sizeof(float); +static constexpr int kRRectCornerPositionDataSize = 2; +static constexpr size_t kRRectCornerPositionDataOffset = 4 * sizeof(float); +static constexpr size_t kRRectDataStride = 6 * sizeof(float); + // Reticle constants static constexpr float kRingDiameter = 1.0f; static constexpr float kInnerHole = 0.0f; @@ -70,7 +164,6 @@ const char* GetShaderSource(vr_shell::ShaderID shader) { switch (shader) { - case vr_shell::ShaderID::EXTERNAL_TEXTURED_QUAD_VERTEX_SHADER: case vr_shell::ShaderID::RETICLE_VERTEX_SHADER: case vr_shell::ShaderID::LASER_VERTEX_SHADER: case vr_shell::ShaderID::TEXTURED_QUAD_VERTEX_SHADER: @@ -115,22 +208,45 @@ gl_Position = u_ModelViewProjMatrix * a_Position; } /* clang-format on */); + case vr_shell::ShaderID::EXTERNAL_TEXTURED_QUAD_VERTEX_SHADER: + return SHADER( + /* clang-format off */ + precision mediump float; + uniform mat4 u_ModelViewProjMatrix; + uniform vec2 u_CornerOffset; + attribute vec4 a_Position; + attribute vec2 a_CornerPosition; + attribute vec2 a_OffsetScale; + varying vec2 v_TexCoordinate; + varying vec2 v_CornerPosition; + + void main() { + v_CornerPosition = a_CornerPosition; + vec4 position = vec4( + a_Position[0] + u_CornerOffset[0] * a_OffsetScale[0], + a_Position[1] + u_CornerOffset[1] * a_OffsetScale[1], + a_Position[2], + a_Position[3]); + v_TexCoordinate = vec2(0.5 + position[0], 0.5 - position[1]); + gl_Position = u_ModelViewProjMatrix * position; + } + /* clang-format on */); case vr_shell::ShaderID::EXTERNAL_TEXTURED_QUAD_FRAGMENT_SHADER: return OEIE_SHADER( /* clang-format off */ precision highp float; uniform samplerExternalOES u_Texture; - uniform vec4 u_CopyRect; // rectangle varying vec2 v_TexCoordinate; - uniform lowp vec4 color; - uniform mediump float opacity; + varying vec2 v_CornerPosition; + uniform float u_CornerScale; + uniform mediump float u_Opacity; void main() { - vec2 scaledTex = - vec2(u_CopyRect[0] + v_TexCoordinate.x * u_CopyRect[2], - u_CopyRect[1] + v_TexCoordinate.y * u_CopyRect[3]); - lowp vec4 color = texture2D(u_Texture, scaledTex); - gl_FragColor = color * opacity; + lowp vec4 color = texture2D(u_Texture, v_TexCoordinate); + float mask = smoothstep(1.0 + u_CornerScale, + 1.0 - u_CornerScale, + length(v_CornerPosition)); + gl_FragColor = color * u_Opacity * mask; } /* clang-format on */); case vr_shell::ShaderID::TEXTURED_QUAD_FRAGMENT_SHADER: @@ -155,13 +271,12 @@ return SHADER( /* clang-format off */ precision mediump float; - attribute vec3 a_Position; - attribute vec2 a_TexCoordinate; - varying highp vec2 v_TexCoordinate; + attribute vec4 a_Position; + varying vec2 v_TexCoordinate; void main() { - v_TexCoordinate = a_TexCoordinate; - gl_Position = vec4(a_Position * 2.0, 1.0); + v_TexCoordinate = vec2(0.5 + a_Position[0], 0.5 - a_Position[1]); + gl_Position = vec4(a_Position.xyz * 2.0, 1.0); } /* clang-format on */); case vr_shell::ShaderID::WEBVR_FRAGMENT_SHADER: @@ -382,22 +497,86 @@ kTexturedQuadIndices, GL_STATIC_DRAW); } +GLuint ExternalTexturedQuadRenderer::vertex_buffer_ = 0; +GLuint ExternalTexturedQuadRenderer::index_buffer_ = 0; + +void ExternalTexturedQuadRenderer::SetVertexBuffer() { + GLuint buffers[2]; + glGenBuffersARB(2, buffers); + vertex_buffer_ = buffers[0]; + index_buffer_ = buffers[1]; + + glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); + glBufferData(GL_ARRAY_BUFFER, arraysize(kRRectVertices) * sizeof(float), + kRRectVertices, GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer_); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, + arraysize(kRRectIndices) * sizeof(GLushort), kRRectIndices, + GL_STATIC_DRAW); +} + ExternalTexturedQuadRenderer::ExternalTexturedQuadRenderer() - : BaseQuadRenderer(EXTERNAL_TEXTURED_QUAD_VERTEX_SHADER, - EXTERNAL_TEXTURED_QUAD_FRAGMENT_SHADER) { + : BaseRenderer(EXTERNAL_TEXTURED_QUAD_VERTEX_SHADER, + EXTERNAL_TEXTURED_QUAD_FRAGMENT_SHADER) { model_view_proj_matrix_handle_ = glGetUniformLocation(program_handle_, "u_ModelViewProjMatrix"); - tex_uniform_handle_ = glGetUniformLocation(program_handle_, "u_Texture"); - copy_rect_uniform_handle_ = - glGetUniformLocation(program_handle_, "u_CopyRect"); - opacity_handle_ = glGetUniformLocation(program_handle_, "opacity"); + corner_offset_handle_ = + glGetUniformLocation(program_handle_, "u_CornerOffset"); + corner_scale_handle_ = glGetUniformLocation(program_handle_, "u_CornerScale"); + opacity_handle_ = glGetUniformLocation(program_handle_, "u_Opacity"); + texture_handle_ = glGetUniformLocation(program_handle_, "u_Texture"); + + corner_position_handle_ = + glGetAttribLocation(program_handle_, "a_CornerPosition"); + offset_scale_handle_ = glGetAttribLocation(program_handle_, "a_OffsetScale"); } void ExternalTexturedQuadRenderer::Draw(int texture_data_handle, const gfx::Transform& view_proj_matrix, - const gfx::RectF& copy_rect, - float opacity) { - PrepareToDraw(model_view_proj_matrix_handle_, view_proj_matrix); + const gfx::Size& surface_size, + const gfx::SizeF& element_size, + float opacity, + float corner_radius) { + if (element_size.IsEmpty()) + return; + + glUseProgram(program_handle_); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + // Pass in model view project matrix. + glUniformMatrix4fv(model_view_proj_matrix_handle_, 1, false, + MatrixToGLArray(view_proj_matrix).data()); + + gfx::Point3F top_left(-0.5, 0.5, 0.0); + gfx::Point3F top_right(0.5, 0.5, 0.0); + view_proj_matrix.TransformPoint(&top_left); + view_proj_matrix.TransformPoint(&top_right); + gfx::Vector3dF top_vector = top_right - top_left; + float physical_width = top_vector.Length(); + physical_width *= corner_radius / element_size.width(); + physical_width *= 0.5 * surface_size.width(); + + glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_); + + // Set up position attribute. + glVertexAttribPointer(position_handle_, kRRectPositionDataSize, GL_FLOAT, + false, kRRectDataStride, + VOID_OFFSET(kRRectPositionDataOffset)); + glEnableVertexAttribArray(position_handle_); + + // Set up offset scale attribute. + glVertexAttribPointer(offset_scale_handle_, kRRectOffsetScaleDataSize, + GL_FLOAT, false, kRRectDataStride, + VOID_OFFSET(kRRectOffsetScaleDataOffset)); + glEnableVertexAttribArray(offset_scale_handle_); + + // Set up corner position attribute. + glVertexAttribPointer(corner_position_handle_, kRRectCornerPositionDataSize, + GL_FLOAT, false, kRRectDataStride, + VOID_OFFSET(kRRectCornerPositionDataOffset)); + glEnableVertexAttribArray(corner_position_handle_); // Link texture data with texture unit. glActiveTexture(GL_TEXTURE0); @@ -407,16 +586,19 @@ glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glUniform1i(tex_uniform_handle_, 0); - glUniform4fv(copy_rect_uniform_handle_, 1, - reinterpret_cast<const float*>(©_rect)); + // Set up uniforms. + glUniform1i(texture_handle_, 0); glUniform1f(opacity_handle_, opacity); + glUniform1f(corner_scale_handle_, 1.0f / physical_width); + glUniform2f(corner_offset_handle_, corner_radius / element_size.width(), + corner_radius / element_size.height()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer_); - glDrawElements(GL_TRIANGLES, arraysize(kTexturedQuadIndices), - GL_UNSIGNED_SHORT, 0); + glDrawElements(GL_TRIANGLES, arraysize(kRRectIndices), GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(position_handle_); + glDisableVertexAttribArray(offset_scale_handle_); + glDisableVertexAttribArray(corner_position_handle_); } ExternalTexturedQuadRenderer::~ExternalTexturedQuadRenderer() = default; @@ -810,6 +992,7 @@ gradient_quad_renderer_(base::MakeUnique<GradientQuadRenderer>()), gradient_grid_renderer_(base::MakeUnique<GradientGridRenderer>()) { BaseQuadRenderer::SetVertexBuffer(); + ExternalTexturedQuadRenderer::SetVertexBuffer(); } VrShellRenderer::~VrShellRenderer() = default;
diff --git a/chrome/browser/android/vr_shell/vr_shell_renderer.h b/chrome/browser/android/vr_shell/vr_shell_renderer.h index 9ac13c14..305a6590 100644 --- a/chrome/browser/android/vr_shell/vr_shell_renderer.h +++ b/chrome/browser/android/vr_shell/vr_shell_renderer.h
@@ -12,6 +12,8 @@ #include "base/macros.h" #include "chrome/browser/android/vr_shell/ui_element_renderer.h" #include "chrome/browser/android/vr_shell/vr_controller_model.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/geometry/size_f.h" #include "ui/gfx/transform.h" #include "ui/gl/gl_bindings.h" @@ -95,7 +97,7 @@ DISALLOW_COPY_AND_ASSIGN(BaseQuadRenderer); }; -class ExternalTexturedQuadRenderer : public BaseQuadRenderer { +class ExternalTexturedQuadRenderer : public BaseRenderer { public: ExternalTexturedQuadRenderer(); ~ExternalTexturedQuadRenderer() override; @@ -103,14 +105,27 @@ // Draw the content rect in the texture quad. void Draw(int texture_data_handle, const gfx::Transform& view_proj_matrix, - const gfx::RectF& copy_rect, - float opacity); + const gfx::Size& surface_size, + const gfx::SizeF& element_size, + float opacity, + float corner_radius); + + static void SetVertexBuffer(); private: + static GLuint vertex_buffer_; + static GLuint index_buffer_; + + // Uniforms GLuint model_view_proj_matrix_handle_; - GLuint copy_rect_uniform_handle_; - GLuint tex_uniform_handle_; + GLuint corner_offset_handle_; + GLuint corner_scale_handle_; GLuint opacity_handle_; + GLuint texture_handle_; + + // Attributes + GLuint corner_position_handle_; + GLuint offset_scale_handle_; DISALLOW_COPY_AND_ASSIGN(ExternalTexturedQuadRenderer); };
diff --git a/chrome/browser/android/web_contents_factory.cc b/chrome/browser/android/web_contents_factory.cc index 37a0799..63fe8fa 100644 --- a/chrome/browser/android/web_contents_factory.cc +++ b/chrome/browser/android/web_contents_factory.cc
@@ -8,7 +8,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents.h" #include "jni/WebContentsFactory_jni.h"
diff --git a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.cc b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.cc index 2729854..626e3f3b 100644 --- a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.cc +++ b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.cc
@@ -10,6 +10,7 @@ #include "base/location.h" #include "base/metrics/user_metrics.h" #include "base/task_scheduler/post_task.h" +#include "chrome/browser/android/shortcut_helper.h" #include "chrome/browser/android/webapk/webapk_web_manifest_checker.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/installable/installable_manager.h" @@ -64,6 +65,39 @@ return params; } +// Creates a launcher icon from |icon|. |start_url| is used to generate the icon +// if |icon| is empty or is not large enough. Returns a std::pair with: +// - the generated icon +// - whether |icon| was used in generating the launcher icon +std::pair<SkBitmap, bool> CreateLauncherIconInBackground(const GURL& start_url, + const SkBitmap& icon) { + base::ThreadRestrictions::AssertIOAllowed(); + + bool is_generated = false; + SkBitmap primary_icon = ShortcutHelper::FinalizeLauncherIconInBackground( + icon, start_url, &is_generated); + return std::make_pair(primary_icon, is_generated); +} + +// Creates a launcher icon from |bitmap_result|. |start_url| is used to +// generate the icon if there is no bitmap in |bitmap_result| or the bitmap is +// not large enough. Returns a std::pair with: +// - the generated icon +// - whether the bitmap in |bitmap_result| was used in generating the launcher +// icon +std::pair<SkBitmap, bool> CreateLauncherIconFromFaviconInBackground( + const GURL& start_url, + const favicon_base::FaviconRawBitmapResult& bitmap_result) { + base::ThreadRestrictions::AssertIOAllowed(); + + SkBitmap decoded; + if (bitmap_result.is_valid()) { + gfx::PNGCodec::Decode(bitmap_result.bitmap_data->front(), + bitmap_result.bitmap_data->size(), &decoded); + } + return CreateLauncherIconInBackground(start_url, decoded); +} + } // namespace AddToHomescreenDataFetcher::AddToHomescreenDataFetcher( @@ -78,7 +112,7 @@ Observer* observer) : content::WebContentsObserver(web_contents), installable_manager_(InstallableManager::FromWebContents(web_contents)), - weak_observer_(observer), + observer_(observer), shortcut_info_(GetShortcutUrl(web_contents->GetBrowserContext(), web_contents->GetLastCommittedURL())), ideal_icon_size_in_px_(ideal_icon_size_in_px), @@ -89,7 +123,7 @@ data_timeout_ms_(data_timeout_ms), check_webapk_compatibility_(check_webapk_compatibility), is_waiting_for_web_application_info_(true), - is_installable_check_complete_(false) { + weak_ptr_factory_(this) { DCHECK(minimum_icon_size_in_px <= ideal_icon_size_in_px); DCHECK(minimum_splash_image_size_in_px <= ideal_splash_image_size_in_px); @@ -99,10 +133,12 @@ new ChromeFrameMsg_GetWebApplicationInfo(main_frame->GetRoutingID())); } +AddToHomescreenDataFetcher::~AddToHomescreenDataFetcher() {} + void AddToHomescreenDataFetcher::OnDidGetWebApplicationInfo( const WebApplicationInfo& received_web_app_info) { is_waiting_for_web_application_info_ = false; - if (!web_contents() || !weak_observer_) + if (!web_contents()) return; // Sanitize received_web_app_info. @@ -144,17 +180,15 @@ // timeout, fall back to using a dynamically-generated launcher icon. data_timeout_timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(data_timeout_ms_), - base::Bind(&AddToHomescreenDataFetcher::OnDataTimedout, this)); + base::Bind(&AddToHomescreenDataFetcher::OnDataTimedout, + weak_ptr_factory_.GetWeakPtr())); installable_manager_->GetData( ParamsToPerformManifestAndIconFetch( ideal_icon_size_in_px_, minimum_icon_size_in_px_, badge_size_in_px_, check_webapk_compatibility_), - base::Bind(&AddToHomescreenDataFetcher::OnDidGetManifestAndIcons, this)); -} - -AddToHomescreenDataFetcher::~AddToHomescreenDataFetcher() { - DCHECK(!weak_observer_); + base::Bind(&AddToHomescreenDataFetcher::OnDidGetManifestAndIcons, + weak_ptr_factory_.GetWeakPtr())); } bool AddToHomescreenDataFetcher::OnMessageReceived( @@ -175,22 +209,21 @@ } void AddToHomescreenDataFetcher::OnDataTimedout() { - if (!web_contents() || !weak_observer_) + weak_ptr_factory_.InvalidateWeakPtrs(); + + if (!web_contents()) return; - if (!is_installable_check_complete_) { - is_installable_check_complete_ = true; - if (check_webapk_compatibility_) - weak_observer_->OnDidDetermineWebApkCompatibility(false); - weak_observer_->OnUserTitleAvailable(shortcut_info_.user_title); - } + if (check_webapk_compatibility_) + observer_->OnDidDetermineWebApkCompatibility(false); + observer_->OnUserTitleAvailable(shortcut_info_.user_title); CreateLauncherIcon(raw_primary_icon_); } void AddToHomescreenDataFetcher::OnDidGetManifestAndIcons( const InstallableData& data) { - if (!web_contents() || !weak_observer_ || is_installable_check_complete_) + if (!web_contents()) return; if (!data.manifest.IsEmpty()) { @@ -203,8 +236,8 @@ // a manifest with name and standalone specified, but no icons. if (data.manifest.IsEmpty() || !data.primary_icon) { if (check_webapk_compatibility_) - weak_observer_->OnDidDetermineWebApkCompatibility(false); - weak_observer_->OnUserTitleAvailable(shortcut_info_.user_title); + observer_->OnDidDetermineWebApkCompatibility(false); + observer_->OnUserTitleAvailable(shortcut_info_.user_title); data_timeout_timer_.Stop(); FetchFavicon(); return; @@ -230,37 +263,35 @@ installable_manager_->GetData( ParamsToPerformInstallableCheck(check_webapk_compatibility_), base::Bind(&AddToHomescreenDataFetcher::OnDidPerformInstallableCheck, - this)); + weak_ptr_factory_.GetWeakPtr())); } void AddToHomescreenDataFetcher::OnDidPerformInstallableCheck( const InstallableData& data) { data_timeout_timer_.Stop(); - if (!web_contents() || !weak_observer_ || is_installable_check_complete_) + if (!web_contents()) return; - is_installable_check_complete_ = true; - bool webapk_compatible = false; if (check_webapk_compatibility_) { webapk_compatible = (data.error_code == NO_ERROR_DETECTED && data.is_installable && AreWebManifestUrlsWebApkCompatible(data.manifest)); - weak_observer_->OnDidDetermineWebApkCompatibility(webapk_compatible); + observer_->OnDidDetermineWebApkCompatibility(webapk_compatible); } - weak_observer_->OnUserTitleAvailable(shortcut_info_.user_title); + observer_->OnUserTitleAvailable(shortcut_info_.user_title); if (webapk_compatible) { shortcut_info_.UpdateSource(ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_PWA); - NotifyObserver(raw_primary_icon_); + NotifyObserver(std::make_pair(raw_primary_icon_, false /* is_generated */)); } else { CreateLauncherIcon(raw_primary_icon_); } } void AddToHomescreenDataFetcher::FetchFavicon() { - if (!web_contents() || !weak_observer_) + if (!web_contents()) return; // Grab the best, largest icon we can find to represent this bookmark. @@ -280,7 +311,8 @@ int threshold_to_get_any_largest_icon = ideal_icon_size_in_px_ - 1; favicon_service->GetLargestRawFaviconForPageURL( shortcut_info_.url, icon_types, threshold_to_get_any_largest_icon, - base::Bind(&AddToHomescreenDataFetcher::OnFaviconFetched, this), + base::Bind(&AddToHomescreenDataFetcher::OnFaviconFetched, + weak_ptr_factory_.GetWeakPtr()), &favicon_task_tracker_); } @@ -288,9 +320,11 @@ const favicon_base::FaviconRawBitmapResult& bitmap_result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!web_contents() || !weak_observer_) + if (!web_contents()) return; + shortcut_info_.best_primary_icon_url = bitmap_result.icon_url; + // The user is waiting for the icon to be processed before they can proceed // with add to homescreen. But if we shut down, there's no point starting the // image processing. Use USER_VISIBLE with MayBlock and SKIP_ON_SHUTDOWN. @@ -298,25 +332,10 @@ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce(&AddToHomescreenDataFetcher:: - CreateLauncherIconFromFaviconInBackground, - base::Unretained(this), bitmap_result), + base::BindOnce(&CreateLauncherIconFromFaviconInBackground, + shortcut_info_.url, bitmap_result), base::BindOnce(&AddToHomescreenDataFetcher::NotifyObserver, - base::RetainedRef(this))); -} - -SkBitmap AddToHomescreenDataFetcher::CreateLauncherIconFromFaviconInBackground( - const favicon_base::FaviconRawBitmapResult& bitmap_result) { - base::ThreadRestrictions::AssertIOAllowed(); - - if (bitmap_result.is_valid()) { - gfx::PNGCodec::Decode(bitmap_result.bitmap_data->front(), - bitmap_result.bitmap_data->size(), - &raw_primary_icon_); - } - - shortcut_info_.best_primary_icon_url = bitmap_result.icon_url; - return CreateLauncherIconInBackground(raw_primary_icon_); + weak_ptr_factory_.GetWeakPtr())); } void AddToHomescreenDataFetcher::CreateLauncherIcon(const SkBitmap& icon) { @@ -329,35 +348,19 @@ FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, - base::BindOnce( - &AddToHomescreenDataFetcher::CreateLauncherIconInBackground, - base::Unretained(this), icon), + base::BindOnce(&CreateLauncherIconInBackground, shortcut_info_.url, icon), base::BindOnce(&AddToHomescreenDataFetcher::NotifyObserver, - base::RetainedRef(this))); + weak_ptr_factory_.GetWeakPtr())); } -SkBitmap AddToHomescreenDataFetcher::CreateLauncherIconInBackground( - const SkBitmap& icon) { - base::ThreadRestrictions::AssertIOAllowed(); - - SkBitmap primary_icon; - bool is_generated = false; - if (weak_observer_) { - primary_icon = weak_observer_->FinalizeLauncherIconInBackground( - icon, shortcut_info_.url, &is_generated); - } - - if (is_generated) - shortcut_info_.best_primary_icon_url = GURL(); - - return primary_icon; -} - -void AddToHomescreenDataFetcher::NotifyObserver(const SkBitmap& primary_icon) { +void AddToHomescreenDataFetcher::NotifyObserver( + const std::pair<SkBitmap, bool /*is_generated*/>& primary_icon) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!web_contents() || !weak_observer_) + if (!web_contents()) return; - primary_icon_ = primary_icon; - weak_observer_->OnDataAvailable(shortcut_info_, primary_icon_, badge_icon_); + primary_icon_ = primary_icon.first; + if (primary_icon.second) + shortcut_info_.best_primary_icon_url = GURL(); + observer_->OnDataAvailable(shortcut_info_, primary_icon_, badge_icon_); }
diff --git a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.h b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.h index 6212b1692..f2750666 100644 --- a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.h +++ b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher.h
@@ -5,8 +5,10 @@ #ifndef CHROME_BROWSER_ANDROID_WEBAPPS_ADD_TO_HOMESCREEN_DATA_FETCHER_H_ #define CHROME_BROWSER_ANDROID_WEBAPPS_ADD_TO_HOMESCREEN_DATA_FETCHER_H_ +#include <utility> + #include "base/macros.h" -#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "base/task/cancelable_task_tracker.h" #include "base/timer/timer.h" @@ -18,20 +20,13 @@ struct FaviconRawBitmapResult; } -class GURL; class InstallableManager; struct InstallableData; struct WebApplicationInfo; // Aysnchronously fetches and processes data needed to create a shortcut for an // Android Home screen launcher. -// -// Because of the various asynchronous calls made by this class, it is -// refcounted to prevent the class from being prematurely deleted. If the -// |weak_observer_| pointer becomes invalid, the pipeline should kill itself. -class AddToHomescreenDataFetcher - : public base::RefCounted<AddToHomescreenDataFetcher>, - public content::WebContentsObserver { +class AddToHomescreenDataFetcher : public content::WebContentsObserver { public: class Observer { public: @@ -43,13 +38,6 @@ // OnDidDetermineWebApkCompatibility. virtual void OnUserTitleAvailable(const base::string16& title) = 0; - // Converts the icon into one that can be used on the Android Home screen. - // |is_generated| is an out-param that indicates whether the icon was - // generated by Chrome. - virtual SkBitmap FinalizeLauncherIconInBackground(const SkBitmap& icon, - const GURL& url, - bool* is_generated) = 0; - // Called when all the data needed to create a shortcut is available. virtual void OnDataAvailable(const ShortcutInfo& info, const SkBitmap& primary_icon, @@ -62,6 +50,7 @@ // Initialize the fetcher by requesting the information about the page from // the renderer process. The initialization is asynchronous and // OnDidGetWebApplicationInfo is expected to be called when finished. + // |observer| must outlive AddToHomescreenDataFetcher. AddToHomescreenDataFetcher(content::WebContents* web_contents, int ideal_icon_size_in_px, int minimum_icon_size_in_px, @@ -72,20 +61,17 @@ bool check_webapk_compatible, Observer* observer); + ~AddToHomescreenDataFetcher() override; + // IPC message received when the initialization is finished. void OnDidGetWebApplicationInfo(const WebApplicationInfo& web_app_info); // Accessors, etc. - void set_weak_observer(Observer* observer) { weak_observer_ = observer; } const SkBitmap& badge_icon() const { return badge_icon_; } const SkBitmap& primary_icon() const { return primary_icon_; } ShortcutInfo& shortcut_info() { return shortcut_info_; } private: - friend class base::RefCounted<AddToHomescreenDataFetcher>; - - ~AddToHomescreenDataFetcher() override; - // WebContentsObserver: bool OnMessageReceived(const IPC::Message& message, content::RenderFrameHost* sender) override; @@ -104,21 +90,14 @@ void OnFaviconFetched( const favicon_base::FaviconRawBitmapResult& bitmap_result); - // Creates the launcher icon from the given bitmap. shortcut_info_.url is - // used to generate an icon if there is no bitmap in |bitmap_result| or the - // bitmap is not large enough. - SkBitmap CreateLauncherIconFromFaviconInBackground( - const favicon_base::FaviconRawBitmapResult& bitmap_result); - // Creates the primary launcher icon from the given |icon|. void CreateLauncherIcon(const SkBitmap& icon); - SkBitmap CreateLauncherIconInBackground(const SkBitmap& icon); // Notifies the observer that the shortcut data is all available. - void NotifyObserver(const SkBitmap& icon); + void NotifyObserver(const std::pair<SkBitmap, bool /*is_generated*/>& icon); InstallableManager* installable_manager_; - Observer* weak_observer_; + Observer* observer_; // The icons must only be set on the UI thread for thread safety. SkBitmap raw_primary_icon_; @@ -139,7 +118,8 @@ // Indicates whether to check WebAPK compatibility. bool check_webapk_compatibility_; bool is_waiting_for_web_application_info_; - bool is_installable_check_complete_; + + base::WeakPtrFactory<AddToHomescreenDataFetcher> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(AddToHomescreenDataFetcher); };
diff --git a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher_unittest.cc b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher_unittest.cc index ebe6b85..bb5c761 100644 --- a/chrome/browser/android/webapps/add_to_homescreen_data_fetcher_unittest.cc +++ b/chrome/browser/android/webapps/add_to_homescreen_data_fetcher_unittest.cc
@@ -10,6 +10,7 @@ #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -136,13 +137,6 @@ title_ = title; } - SkBitmap FinalizeLauncherIconInBackground(const SkBitmap& icon, - const GURL& url, - bool* is_generated) override { - *is_generated = false; - return icon; - } - void OnDataAvailable(const ShortcutInfo& info, const SkBitmap& primary_icon, const SkBitmap& badge_icon) override { @@ -231,11 +225,11 @@ ChromeRenderViewHostTestHarness::TearDown(); } - scoped_refptr<AddToHomescreenDataFetcher> BuildFetcher( + std::unique_ptr<AddToHomescreenDataFetcher> BuildFetcher( bool check_webapk_compatible, AddToHomescreenDataFetcher::Observer* observer) { - return new AddToHomescreenDataFetcher(web_contents(), 1, 1, 1, 1, 1, 500, - check_webapk_compatible, observer); + return base::MakeUnique<AddToHomescreenDataFetcher>( + web_contents(), 1, 1, 1, 1, 1, 500, check_webapk_compatible, observer); } // Set the manifest to be returned as a result of WebContents::GetManifest(). @@ -295,7 +289,7 @@ AddToHomescreenDataFetcherTestCommon() {} ~AddToHomescreenDataFetcherTestCommon() override {} - scoped_refptr<AddToHomescreenDataFetcher> BuildFetcher( + std::unique_ptr<AddToHomescreenDataFetcher> BuildFetcher( AddToHomescreenDataFetcher::Observer* observer) { return AddToHomescreenDataFetcherTest::BuildFetcher( check_webapk_compatibility(), observer); @@ -319,7 +313,7 @@ SetManifest(GURL(kDefaultManifestUrl), BuildEmptyManifest()); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); @@ -328,8 +322,6 @@ EXPECT_FALSE(waiter.is_webapk_compatible()); EXPECT_TRUE(waiter.title_available()); EXPECT_TRUE(base::EqualsASCII(waiter.title(), kWebApplicationInfoTitle)); - - fetcher->set_weak_observer(nullptr); } // Test that when the manifest provides Manifest::short_name but not @@ -347,15 +339,13 @@ SetManifest(GURL(kDefaultManifestUrl), manifest); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); EXPECT_TRUE(base::EqualsASCII(waiter.title(), kDefaultManifestShortName)); EXPECT_TRUE(base::EqualsASCII(fetcher->shortcut_info().name, kDefaultManifestShortName)); - - fetcher->set_weak_observer(nullptr); } // Test that when the manifest does not provide either Manifest::short_name nor @@ -374,7 +364,7 @@ SetManifest(GURL(kDefaultManifestUrl), manifest); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); @@ -384,8 +374,6 @@ EXPECT_TRUE(base::EqualsASCII(waiter.title(), kWebApplicationInfoTitle)); EXPECT_TRUE(base::EqualsASCII(fetcher->shortcut_info().name, kWebApplicationInfoTitle)); - - fetcher->set_weak_observer(nullptr); } // Checks that the AddToHomescreenDataFetcher::Observer callbacks are called @@ -400,7 +388,7 @@ SetShouldImageTimeOut(false); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); @@ -409,8 +397,6 @@ EXPECT_FALSE(waiter.is_webapk_compatible()); EXPECT_TRUE(base::EqualsASCII(waiter.title(), kWebApplicationInfoTitle)); EXPECT_TRUE(waiter.title_available()); - - fetcher->set_weak_observer(nullptr); } // Checks that the AddToHomescreenDataFetcher::Observer callbacks are called @@ -425,7 +411,7 @@ SetShouldImageTimeOut(true); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); @@ -434,8 +420,6 @@ EXPECT_FALSE(waiter.is_webapk_compatible()); EXPECT_TRUE(waiter.title_available()); EXPECT_TRUE(base::EqualsASCII(waiter.title(), kWebApplicationInfoTitle)); - - fetcher->set_weak_observer(nullptr); } // Checks that the AddToHomescreenDataFetcher::Observer callbacks are called @@ -451,7 +435,7 @@ SetShouldImageTimeOut(false); ObserverWaiter waiter; - scoped_refptr<AddToHomescreenDataFetcher> fetcher(BuildFetcher(&waiter)); + std::unique_ptr<AddToHomescreenDataFetcher> fetcher = BuildFetcher(&waiter); fetcher->OnDidGetWebApplicationInfo(web_application_info); waiter.WaitForDataAvailable(); @@ -462,8 +446,6 @@ EXPECT_TRUE(base::EqualsASCII(waiter.title(), kDefaultManifestShortName)); EXPECT_TRUE(base::EqualsASCII(fetcher->shortcut_info().user_title, kDefaultManifestShortName)); - - fetcher->set_weak_observer(nullptr); } INSTANTIATE_TEST_CASE_P(CheckWebApkCompatibility,
diff --git a/chrome/browser/android/webapps/add_to_homescreen_manager.cc b/chrome/browser/android/webapps/add_to_homescreen_manager.cc index 03503e7..5a80899 100644 --- a/chrome/browser/android/webapps/add_to_homescreen_manager.cc +++ b/chrome/browser/android/webapps/add_to_homescreen_manager.cc
@@ -96,7 +96,7 @@ ShowDialog(); } - data_fetcher_ = new AddToHomescreenDataFetcher( + data_fetcher_ = base::MakeUnique<AddToHomescreenDataFetcher>( web_contents, ShortcutHelper::GetIdealHomescreenIconSizeInPx(), ShortcutHelper::GetMinimumHomescreenIconSizeInPx(), ShortcutHelper::GetIdealSplashImageSizeInPx(), @@ -105,12 +105,7 @@ check_webapk_compatible, this); } -AddToHomescreenManager::~AddToHomescreenManager() { - if (data_fetcher_) { - data_fetcher_->set_weak_observer(nullptr); - data_fetcher_ = nullptr; - } -} +AddToHomescreenManager::~AddToHomescreenManager() {} void AddToHomescreenManager::ShowDialog() { JNIEnv* env = base::android::AttachCurrentThread(); @@ -188,13 +183,3 @@ -1 /* event_request_id */, true /* is_webapk */, webapk::INSTALL_SOURCE_MENU); } - -SkBitmap AddToHomescreenManager::FinalizeLauncherIconInBackground( - const SkBitmap& bitmap, - const GURL& url, - bool* is_generated) { - base::ThreadRestrictions::AssertIOAllowed(); - - return ShortcutHelper::FinalizeLauncherIconInBackground(bitmap, url, - is_generated); -}
diff --git a/chrome/browser/android/webapps/add_to_homescreen_manager.h b/chrome/browser/android/webapps/add_to_homescreen_manager.h index 3d7af4d..7cdefa41 100644 --- a/chrome/browser/android/webapps/add_to_homescreen_manager.h +++ b/chrome/browser/android/webapps/add_to_homescreen_manager.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_ANDROID_WEBAPPS_ADD_TO_HOMESCREEN_MANAGER_H_ #define CHROME_BROWSER_ANDROID_WEBAPPS_ADD_TO_HOMESCREEN_MANAGER_H_ +#include <memory> + #include "base/android/jni_android.h" #include "base/android/scoped_java_ref.h" #include "base/macros.h" @@ -14,7 +16,6 @@ class WebContents; } -class GURL; class SkBitmap; struct ShortcutInfo; @@ -60,9 +61,6 @@ void OnDataAvailable(const ShortcutInfo& info, const SkBitmap& primary_icon, const SkBitmap& badge_icon) override; - SkBitmap FinalizeLauncherIconInBackground(const SkBitmap& icon, - const GURL& url, - bool* is_generated) override; // Points to the Java object. base::android::ScopedJavaGlobalRef<jobject> java_ref_; @@ -71,7 +69,7 @@ bool is_webapk_compatible_; // Fetches data required to add a shortcut. - scoped_refptr<AddToHomescreenDataFetcher> data_fetcher_; + std::unique_ptr<AddToHomescreenDataFetcher> data_fetcher_; DISALLOW_COPY_AND_ASSIGN(AddToHomescreenManager); };
diff --git a/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm b/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm index 238e0e1..17403691 100644 --- a/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm +++ b/chrome/browser/apps/app_shim/app_shim_interactive_uitest_mac.mm
@@ -53,8 +53,8 @@ // testing::Test: void SetUp() override { - PlatformAppBrowserTest::SetUp(); scoped_feature_list_.InitAndEnableFeature(features::kBookmarkApps); + PlatformAppBrowserTest::SetUp(); } // Install a test app of |type| and reliably wait for its app shim to be
diff --git a/chrome/browser/apps/shortcut_manager.cc b/chrome/browser/apps/shortcut_manager.cc index 761714da..6ca05e8 100644 --- a/chrome/browser/apps/shortcut_manager.cc +++ b/chrome/browser/apps/shortcut_manager.cc
@@ -136,8 +136,9 @@ const base::FilePath& profile_path) { if (profile_path != profile_->GetPath()) return; - content::BrowserThread::PostTask( - content::BrowserThread::FILE, FROM_HERE, + + web_app::ShortcutInfo::GetTaskRunner()->PostTask( + FROM_HERE, base::BindOnce(&web_app::internals::DeleteAllShortcutsForProfile, profile_path)); }
diff --git a/chrome/browser/browser_process_impl.cc b/chrome/browser/browser_process_impl.cc index 5f9cd96..818d057 100644 --- a/chrome/browser/browser_process_impl.cc +++ b/chrome/browser/browser_process_impl.cc
@@ -236,12 +236,14 @@ print_job_manager_.reset(new printing::PrintJobManager); #endif - base::FilePath net_log_path; - if (command_line.HasSwitch(switches::kLogNetLog)) - net_log_path = command_line.GetSwitchValuePath(switches::kLogNetLog); - net_log_.reset(new net_log::ChromeNetLog( - net_log_path, GetNetCaptureModeFromCommandLine(command_line), - command_line.GetCommandLineString(), chrome::GetChannelString())); + net_log_ = base::MakeUnique<net_log::ChromeNetLog>(); + + if (command_line.HasSwitch(switches::kLogNetLog)) { + net_log_->StartWritingToFile( + command_line.GetSwitchValuePath(switches::kLogNetLog), + GetNetCaptureModeFromCommandLine(command_line), + command_line.GetCommandLineString(), chrome::GetChannelString()); + } ChildProcessSecurityPolicy::GetInstance()->RegisterWebSafeScheme( chrome::kChromeSearchScheme); @@ -1300,11 +1302,11 @@ void BrowserProcessImpl::ApplyMetricsReportingPolicy() { #if !defined(OS_ANDROID) - CHECK(BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, + GoogleUpdateSettings::CollectStatsConsentTaskRunner()->PostTask( + FROM_HERE, base::BindOnce( base::IgnoreResult(&GoogleUpdateSettings::SetCollectStatsConsent), - ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled()))); + ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled())); #endif }
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 44fee5aa1..6dc8dde 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -23,6 +23,7 @@ #include "chrome/browser/history/web_history_service_factory.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/media/media_device_id_salt.h" +#include "chrome/browser/media/media_engagement_service.h" #include "chrome/browser/net/nqe/ui_network_quality_estimator_service.h" #include "chrome/browser/net/nqe/ui_network_quality_estimator_service_factory.h" #include "chrome/browser/net/predictor.h" @@ -749,6 +750,14 @@ } ////////////////////////////////////////////////////////////////////////////// + // Media Engagement + if (remove_mask & DATA_TYPE_SITE_USAGE_DATA && + MediaEngagementService::IsEnabled()) { + MediaEngagementService::Get(profile_)->ClearDataBetweenTime(delete_begin_, + delete_end_); + } + + ////////////////////////////////////////////////////////////////////////////// // DATA_TYPE_SITE_USAGE_DATA if (remove_mask & DATA_TYPE_SITE_USAGE_DATA) { HostContentSettingsMapFactory::GetForProfile(profile_)
diff --git a/chrome/browser/chrome_browser_main_linux.cc b/chrome/browser/chrome_browser_main_linux.cc index 1fc00fa..52e0aad 100644 --- a/chrome/browser/chrome_browser_main_linux.cc +++ b/chrome/browser/chrome_browser_main_linux.cc
@@ -8,6 +8,7 @@ #include <string> +#include "base/files/file_path.h" #include "base/single_thread_task_runner.h" #include "base/task_scheduler/post_task.h" #include "build/build_config.h" @@ -23,6 +24,7 @@ #if !defined(OS_CHROMEOS) #include "base/command_line.h" #include "base/linux_util.h" +#include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/os_crypt.h" #include "content/public/browser/browser_thread.h" @@ -69,6 +71,12 @@ content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::UI)); OSCrypt::SetMainThreadRunner(main_thread_runner); + // OSCrypt can be disabled in a special settings file. + OSCrypt::ShouldUsePreference( + parsed_command_line().HasSwitch(switches::kEnableEncryptionSelection)); + base::FilePath user_data_dir; + chrome::GetDefaultUserDataDirectory(&user_data_dir); + OSCrypt::SetUserDataPath(user_data_dir); #endif ChromeBrowserMainPartsPosix::PreProfileInit();
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 9d061cb..1466eac 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -200,6 +200,7 @@ #include "media/audio/audio_manager.h" #include "media/media_features.h" #include "media/mojo/features.h" +#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h" #include "net/base/mime_util.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h" @@ -402,6 +403,7 @@ #endif #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) +#include "media/mojo/interfaces/constants.mojom.h" // nogncheck #include "media/mojo/services/media_service_factory.h" // nogncheck #endif @@ -2991,6 +2993,22 @@ } } +bool ChromeContentBrowserClient::BindAssociatedInterfaceRequestFromFrame( + content::RenderFrameHost* render_frame_host, + const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle* handle) { + // TODO(https://crbug.com/736357): Factor AssociatedInterfaceRegistryImpl out + // into content/public/ so it can be used here instead of this abomination. + if (interface_name == password_manager::mojom::CredentialManager::Name_) { + ChromePasswordManagerClient::BindCredentialManager( + password_manager::mojom::CredentialManagerAssociatedRequest( + std::move(*handle)), + render_frame_host); + return true; + } + return false; +} + void ChromeContentBrowserClient::BindInterfaceRequest( const service_manager::BindSourceInfo& source_info, const std::string& interface_name, @@ -3007,7 +3025,7 @@ #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(&media::CreateMediaService); - services->insert(std::make_pair("media", info)); + services->insert(std::make_pair(media::mojom::kMediaServiceName, info)); #endif #if defined(OS_CHROMEOS) { @@ -3323,8 +3341,6 @@ base::Bind(&bluetooth::AdapterFactory::Create)); frame_interfaces_parameterized_->AddInterface( - base::Bind(&ChromePasswordManagerClient::BindCredentialManager)); - frame_interfaces_parameterized_->AddInterface( base::Bind(&ChromeTranslateClient::BindContentTranslateDriver)); frame_interfaces_parameterized_->AddInterface(
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index a91a3b0a..93e6591 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -285,6 +285,10 @@ const service_manager::BindSourceInfo& source_info, const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) override; + bool BindAssociatedInterfaceRequestFromFrame( + content::RenderFrameHost* render_frame_host, + const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle* handle) override; void BindInterfaceRequest( const service_manager::BindSourceInfo& source_info, const std::string& interface_name,
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.cc b/chrome/browser/chromeos/arc/arc_service_launcher.cc index ad980b70..eea3de5a 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/arc_service_launcher.cc
@@ -80,7 +80,6 @@ // static ArcServiceLauncher* ArcServiceLauncher::Get() { - DCHECK(g_arc_service_launcher); return g_arc_service_launcher; } @@ -165,16 +164,9 @@ base::MakeUnique<GpuArcVideoServiceHost>(arc_bridge_service)); } -void ArcServiceLauncher::OnPrimaryUserProfilePrepared(Profile* profile) { +void ArcServiceLauncher::MaybeSetProfile(Profile* profile) { DCHECK(arc_service_manager_); DCHECK(arc_session_manager_); - // TODO(hidehiko): DCHECK(!arc_session_manager_->IsAllowed()) here. - // Do not expect it in real use case, but it is used for testing. - // Because the ArcService instances tied to the old profile is kept, - // and ones tied to the new profile are added, which is unexpected situation. - // For compatibility, call Shutdown() here in case |profile| is not - // allowed for ARC. - arc_session_manager_->Shutdown(); if (!IsArcAllowedForProfile(profile)) return; @@ -186,6 +178,29 @@ return; } + // Do not expect it in real use case, but it is used for testing. + // Because the ArcService instances tied to the old profile is kept, + // and ones tied to the new profile are added, which is unexpected situation. + // For compatibility, call Shutdown() here in case |profile| is not + // allowed for ARC. + // TODO(hidehiko): DCHECK(!arc_session_manager_->IsAllowed()) here, and + // get rid of Shutdown(). + if (arc_session_manager_->profile()) + arc_session_manager_->Shutdown(); + + arc_session_manager_->SetProfile(profile); +} + +void ArcServiceLauncher::OnPrimaryUserProfilePrepared(Profile* profile) { + DCHECK(arc_service_manager_); + DCHECK(arc_session_manager_); + + if (arc_session_manager_->profile() != profile) { + // Profile is not matched, so the given |profile| is not allowed to use + // ARC. + return; + } + // List in lexicographical order arc_service_manager_->AddService(base::MakeUnique<ArcBootPhaseMonitorBridge>( arc_service_manager_->arc_bridge_service(), @@ -206,7 +221,6 @@ chromeos::ArcKioskAppService::Get(profile))); } - arc_session_manager_->SetProfile(profile); arc_session_manager_->Initialize(); arc_play_store_enabled_preference_handler_ = base::MakeUnique<ArcPlayStoreEnabledPreferenceHandler>(
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.h b/chrome/browser/chromeos/arc/arc_service_launcher.h index 2c8132e..e6997fc 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.h +++ b/chrome/browser/chromeos/arc/arc_service_launcher.h
@@ -23,7 +23,7 @@ ArcServiceLauncher(); ~ArcServiceLauncher(); - // This is to access OnPrimaryUserProfilePrepared() only. + // Returns a global instance. static ArcServiceLauncher* Get(); // Called before the main MessageLooop starts. @@ -33,6 +33,11 @@ // destroyed. void Shutdown(); + // Called just before most of BrowserContextKeyedService instance creation. + // Set the given |profile| to ArcSessionManager, if the profile is allowed + // to use ARC. + void MaybeSetProfile(Profile* profile); + // Called when the main profile is initialized after user logs in. void OnPrimaryUserProfilePrepared(Profile* profile);
diff --git a/chrome/browser/chromeos/arc/arc_session_manager.cc b/chrome/browser/chromeos/arc/arc_session_manager.cc index 3226fc6..1bed59e 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager.cc +++ b/chrome/browser/chromeos/arc/arc_session_manager.cc
@@ -490,10 +490,8 @@ break; case State::ACTIVE: // Request to stop the ARC. |state_| will be set to STOPPED eventually. - // TODO(yusukes): Once Shutdown() in - // ArcServiceLauncher::OnPrimaryUserProfilePrepared() is removed, always - // call RequestStop() with |true|. We can actually remove the boolean - // parameter then. + // TODO(yusukes): Always call RequestStop() with |true|. + // We can actually remove the boolean parameter then. arc_session_runner_->RequestStop(false); state_ = State::STOPPING; break;
diff --git a/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc b/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc index 4e089808..393ec700 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc +++ b/chrome/browser/chromeos/arc/arc_session_manager_browsertest.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/cloud/test_request_interceptor.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" @@ -124,13 +125,22 @@ user_manager_enabler_.reset(new chromeos::ScopedUserManagerEnabler( new chromeos::FakeChromeUserManager)); // Init ArcSessionManager for testing. + ArcServiceLauncher::Get()->Shutdown(); + ArcServiceLauncher::Get()->Initialize(); ArcSessionManager::DisableUIForTesting(); ArcAuthNotification::DisableForTesting(); ArcSessionManager::EnableCheckAndroidManagementForTesting(); ArcSessionManager::Get()->SetArcSessionRunnerForTesting( base::MakeUnique<ArcSessionRunner>(base::Bind(FakeArcSession::Create))); - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + + chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(true); + + const AccountId account_id( + AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId)); + GetFakeUserManager()->AddUser(account_id); + GetFakeUserManager()->LoginUser(account_id); // Create test profile. TestingProfile::Builder profile_builder; @@ -147,11 +157,6 @@ profile()->GetPrefs()->SetBoolean(prefs::kArcSignedIn, true); profile()->GetPrefs()->SetBoolean(prefs::kArcTermsAccepted, true); - const AccountId account_id( - AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId)); - GetFakeUserManager()->AddUser(account_id); - GetFakeUserManager()->LoginUser(account_id); - // Set up ARC for test profile. // Currently, ArcSessionManager is singleton and set up with the original // Profile instance. This re-initializes the ArcServiceLauncher by @@ -180,6 +185,7 @@ profile_.reset(); user_manager_enabler_.reset(); test_server_.reset(); + chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(false); } chromeos::FakeChromeUserManager* GetFakeUserManager() const {
diff --git a/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc b/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc index e2ae7fe..46193ef 100644 --- a/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc +++ b/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc
@@ -11,15 +11,11 @@ #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher.h" #include "chrome/browser/chromeos/arc/auth/arc_auth_code_fetcher.h" #include "chrome/browser/chromeos/arc/auth/arc_auth_service.h" -#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" -#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/dm_token_storage.h" -#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/policy/cloud/test_request_interceptor.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" @@ -50,7 +46,6 @@ constexpr char kFakeUserId[] = "fake-user-id"; constexpr char kFakeAuthSessionId[] = "fake-auth-session-id"; constexpr char kFakeAdfsServerUrl[] = "http://example.com/adfs/ls/awesome.aspx"; -constexpr char kFakeGuid[] = "f04557de-5da2-40ce-ae9d-b8874d8da96e"; constexpr char kNotYetFetched[] = "NOT-YET-FETCHED"; constexpr char kRedirectHeaderFormat[] = "HTTP/1.1 302 MOVED\n" @@ -264,19 +259,6 @@ token_fetcher_ = base::MakeUnique<ArcActiveDirectoryEnrollmentTokenFetcher>(); - - user_manager_enabler_ = - base::MakeUnique<chromeos::ScopedUserManagerEnabler>( - new chromeos::FakeChromeUserManager()); - - const AccountId account_id(AccountId::AdFromObjGuid(kFakeGuid)); - GetFakeUserManager()->AddUser(account_id); - GetFakeUserManager()->LoginUser(account_id); - chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(true); - - testing_profile_ = base::MakeUnique<TestingProfile>(); - chromeos::ProfileHelper::Get()->SetUserToProfileMappingForTesting( - GetFakeUserManager()->GetPrimaryUser(), testing_profile_.get()); } // Stores a correct (fake) DM token. ArcActiveDirectoryEnrollmentTokenFetcher @@ -310,16 +292,9 @@ } void TearDownOnMainThread() override { - user_manager_enabler_.reset(); - dm_interceptor_.reset(); + token_fetcher_.reset(); adfs_interceptor_.reset(); - testing_profile_.reset(); - chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(false); - } - - chromeos::FakeChromeUserManager* GetFakeUserManager() const { - return static_cast<chromeos::FakeChromeUserManager*>( - user_manager::UserManager::Get()); + dm_interceptor_.reset(); } void FetchEnrollmentToken( @@ -386,10 +361,8 @@ private: std::unique_ptr<ArcActiveDirectoryEnrollmentTokenFetcher> token_fetcher_; - std::unique_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_; // DBusThreadManager owns this. chromeos::FakeCryptohomeClient* fake_cryptohome_client_; - std::unique_ptr<TestingProfile> testing_profile_; DISALLOW_COPY_AND_ASSIGN(ArcActiveDirectoryEnrollmentTokenFetcherBrowserTest); };
diff --git a/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc b/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc index 5fa98957..cd420e6 100644 --- a/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc +++ b/chrome/browser/chromeos/arc/auth/arc_auth_service_browsertest.cc
@@ -19,6 +19,7 @@ #include "chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h" #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h" #include "chrome/browser/signin/fake_signin_manager_builder.h" @@ -37,7 +38,6 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "net/url_request/test_url_fetcher_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -93,14 +93,24 @@ base::MakeUnique<chromeos::ScopedUserManagerEnabler>( new chromeos::FakeChromeUserManager()); // Init ArcSessionManager for testing. + ArcServiceLauncher::Get()->Shutdown(); + ArcServiceLauncher::Get()->Initialize(); ArcSessionManager::DisableUIForTesting(); ArcAuthNotification::DisableForTesting(); ArcSessionManager::EnableCheckAndroidManagementForTesting(); ArcSessionManager::Get()->SetArcSessionRunnerForTesting( base::MakeUnique<ArcSessionRunner>(base::Bind(FakeArcSession::Create))); + chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(true); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + const AccountId account_id( + AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId)); + GetFakeUserManager()->AddUser(account_id); + GetFakeUserManager()->LoginUser(account_id); + GetFakeUserManager()->CreateLocalState(); + // Create test profile. TestingProfile::Builder profile_builder; profile_builder.SetPath(temp_dir_.GetPath().AppendASCII("TestArcProfile")); @@ -127,28 +137,12 @@ profile()->GetPrefs()->SetBoolean(prefs::kArcSignedIn, true); profile()->GetPrefs()->SetBoolean(prefs::kArcTermsAccepted, true); - const AccountId account_id( - AccountId::FromUserEmailGaiaId(kFakeUserName, kFakeGaiaId)); - GetFakeUserManager()->AddUser(account_id); - GetFakeUserManager()->LoginUser(account_id); - GetFakeUserManager()->CreateLocalState(); - - // Set up ARC for test profile. - // Currently, ArcSessionManager is singleton and set up with the original - // Profile instance. This re-initializes the ArcServiceLauncher by - // overwriting Profile with profile(). - // TODO(hidehiko): This way several ArcService instances created with - // the original Profile instance on Browser creatuion are kept in the - // ArcServiceManager. For proper overwriting, those should be removed. ArcServiceLauncher::Get()->OnPrimaryUserProfilePrepared(profile()); // It is non-trivial to navigate through the merge session in a testing // context; currently we just skip it. // TODO(blundell): Figure out how to enable this flow. ArcSessionManager::Get()->auth_context()->SkipMergeSessionForTesting(); - - user_manager::known_user::SetDeviceId( - multi_user_util::GetAccountIdFromProfile(profile()), "dummy"); } void TearDownOnMainThread() override { @@ -168,6 +162,7 @@ ArcServiceLauncher::Get()->Shutdown(); profile_.reset(); user_manager_enabler_.reset(); + chromeos::ProfileHelper::SetAlwaysReturnPrimaryUserForTesting(false); } chromeos::FakeChromeUserManager* GetFakeUserManager() const {
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc index b82f94d..a69e3f2 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc
@@ -311,14 +311,14 @@ // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed. LOG(WARNING) << "Show device attribute prompt screen"; StartupUtils::MarkDeviceRegistered( - base::Bind(&EnrollmentScreen::ShowAttributePromptScreen, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&EnrollmentScreen::ShowAttributePromptScreen, + weak_ptr_factory_.GetWeakPtr())); } else { // TODO(pbond): remove this LOG once http://crbug.com/586961 is fixed. LOG(WARNING) << "The device attribute update is not permitted"; StartupUtils::MarkDeviceRegistered( - base::Bind(&EnrollmentScreen::ShowEnrollmentStatusOnSuccess, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&EnrollmentScreen::ShowEnrollmentStatusOnSuccess, + weak_ptr_factory_.GetWeakPtr())); } }
diff --git a/chrome/browser/chromeos/login/profile_auth_data.cc b/chrome/browser/chromeos/login/profile_auth_data.cc index 9fef4cb3..62b6df0 100644 --- a/chrome/browser/chromeos/login/profile_auth_data.cc +++ b/chrome/browser/chromeos/login/profile_auth_data.cc
@@ -191,7 +191,7 @@ // Retrieve the contents of |to_context_|'s cookie jar. net::CookieStore* to_store = to_context_->GetURLRequestContext()->cookie_store(); - to_store->GetAllCookiesAsync(base::Bind( + to_store->GetAllCookiesAsync(base::BindOnce( &ProfileAuthDataTransferer::OnTargetCookieJarContentsRetrieved, base::Unretained(this))); } else { @@ -240,8 +240,8 @@ net::CookieStore* from_store = from_context_->GetURLRequestContext()->cookie_store(); from_store->GetAllCookiesAsync( - base::Bind(&ProfileAuthDataTransferer::OnCookiesToTransferRetrieved, - base::Unretained(this))); + base::BindOnce(&ProfileAuthDataTransferer::OnCookiesToTransferRetrieved, + base::Unretained(this))); } void ProfileAuthDataTransferer::OnCookiesToTransferRetrieved(
diff --git a/chrome/browser/chromeos/login/profile_auth_data_unittest.cc b/chrome/browser/chromeos/login/profile_auth_data_unittest.cc index d2a1470..fda00ba7 100644 --- a/chrome/browser/chromeos/login/profile_auth_data_unittest.cc +++ b/chrome/browser/chromeos/login/profile_auth_data_unittest.cc
@@ -144,9 +144,10 @@ net::CookieList ProfileAuthDataTest::GetUserCookies() { run_loop_.reset(new base::RunLoop); - GetCookies(&user_browser_context_)->GetAllCookiesAsync(base::Bind( - &ProfileAuthDataTest::StoreCookieListAndQuitLoop, - base::Unretained(this))); + GetCookies(&user_browser_context_) + ->GetAllCookiesAsync( + base::BindOnce(&ProfileAuthDataTest::StoreCookieListAndQuitLoop, + base::Unretained(this))); run_loop_->Run(); return user_cookie_list_; } @@ -220,8 +221,8 @@ net::CookieStore* cookies = GetCookies(browser_context); // Ensure |cookies| is fully initialized. run_loop_.reset(new base::RunLoop); - cookies->GetAllCookiesAsync(base::Bind(&ProfileAuthDataTest::QuitLoop, - base::Unretained(this))); + cookies->GetAllCookiesAsync( + base::BindOnce(&ProfileAuthDataTest::QuitLoop, base::Unretained(this))); run_loop_->Run(); cookies->SetCookieWithDetailsAsync(
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index 428d8599..c05eba90 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -1230,8 +1230,8 @@ const scoped_refptr<net::URLRequestContextGetter>& request_context, const base::Closure& callback) { request_context->GetURLRequestContext()->cookie_store()->GetAllCookiesAsync( - base::Bind(&SAMLPolicyTest::StoreCookieList, base::Unretained(this), - callback)); + base::BindOnce(&SAMLPolicyTest::StoreCookieList, base::Unretained(this), + callback)); } void SAMLPolicyTest::StoreCookieList(
diff --git a/chrome/browser/chromeos/login/screens/host_pairing_screen.cc b/chrome/browser/chromeos/login/screens/host_pairing_screen.cc index 9b8e3a7..8252404 100644 --- a/chrome/browser/chromeos/login/screens/host_pairing_screen.cc +++ b/chrome/browser/chromeos/login/screens/host_pairing_screen.cc
@@ -204,7 +204,7 @@ } void HostPairingScreen::OnDeviceEnrolled(const std::string& additional_token) { - StartupUtils::MarkDeviceRegistered(base::Bind(&base::DoNothing)); + StartupUtils::MarkDeviceRegistered(base::BindOnce(&base::DoNothing)); enrollment_helper_->ClearAuth(base::Bind(&HostPairingScreen::OnAuthCleared, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc index eb54b5a..e95cb8c 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc
@@ -433,7 +433,7 @@ void ReadCookiesOnIOThread() { context_->GetURLRequestContext()->cookie_store()->GetAllCookiesAsync( - base::Bind(&CookieReader::OnGetAllCookiesOnUIThread, this)); + base::BindOnce(&CookieReader::OnGetAllCookiesOnUIThread, this)); } void OnGetAllCookiesOnUIThread(const net::CookieList& cookies) {
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_browsertest.cc b/chrome/browser/chromeos/login/supervised/supervised_user_creation_browsertest.cc index a30fba0..4c5a1bb 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_browsertest.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_browsertest.cc
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/login_manager_test.h" @@ -26,6 +27,7 @@ #include "chrome/browser/supervised_user/legacy/supervised_user_registration_utility.h" #include "chrome/browser/supervised_user/legacy/supervised_user_registration_utility_stub.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" +#include "chrome/common/chrome_features.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/cryptohome/mock_homedir_methods.h" #include "components/sync/model/attachments/attachment_service_proxy_for_test.h" @@ -58,7 +60,15 @@ public: SupervisedUserCreationTest() : SupervisedUserTestBase() {} + void SetUpInProcessBrowserTestFixture() override { + SupervisedUserTestBase::SetUpInProcessBrowserTestFixture(); + scoped_feature_list_.InitAndEnableFeature( + features::kSupervisedUserCreation); + } + private: + base::test::ScopedFeatureList scoped_feature_list_; + DISALLOW_COPY_AND_ASSIGN(SupervisedUserCreationTest); }; @@ -66,7 +76,15 @@ public: SupervisedUserTransactionCleanupTest() : SupervisedUserTestBase() {} + void SetUpInProcessBrowserTestFixture() override { + SupervisedUserTestBase::SetUpInProcessBrowserTestFixture(); + scoped_feature_list_.InitAndEnableFeature( + features::kSupervisedUserCreation); + } + private: + base::test::ScopedFeatureList scoped_feature_list_; + DISALLOW_COPY_AND_ASSIGN(SupervisedUserTransactionCleanupTest); }; @@ -76,12 +94,16 @@ void SetUpInProcessBrowserTestFixture() override { SupervisedUserTestBase::SetUpInProcessBrowserTestFixture(); + scoped_feature_list_.InitAndEnableFeature( + features::kSupervisedUserCreation); cros_settings_provider_.reset(new StubCrosSettingsProvider()); cros_settings_provider_->Set(kDeviceOwner, base::Value(kTestManager)); } private: std::unique_ptr<StubCrosSettingsProvider> cros_settings_provider_; + base::test::ScopedFeatureList scoped_feature_list_; + DISALLOW_COPY_AND_ASSIGN(SupervisedUserOwnerCreationTest); };
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_password_browsertest.cc b/chrome/browser/chromeos/login/supervised/supervised_user_password_browsertest.cc index 308cde3..6fd8745 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_password_browsertest.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_password_browsertest.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/login_manager_test.h" @@ -21,6 +22,7 @@ #include "chrome/browser/chromeos/net/network_portal_detector_test_impl.h" #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" +#include "chrome/common/chrome_features.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/cryptohome/mock_homedir_methods.h" #include "components/sync/model/attachments/attachment_service_proxy_for_test.h" @@ -43,7 +45,15 @@ public: SupervisedUserPasswordTest() : SupervisedUserTestBase() {} + void SetUpInProcessBrowserTestFixture() override { + SupervisedUserTestBase::SetUpInProcessBrowserTestFixture(); + scoped_feature_list_.InitAndEnableFeature( + features::kSupervisedUserCreation); + } + private: + base::test::ScopedFeatureList scoped_feature_list_; + DISALLOW_COPY_AND_ASSIGN(SupervisedUserPasswordTest); };
diff --git a/chrome/browser/chromeos/login/wizard_controller.cc b/chrome/browser/chromeos/login/wizard_controller.cc index f826f99d..ce2aca3 100644 --- a/chrome/browser/chromeos/login/wizard_controller.cc +++ b/chrome/browser/chromeos/login/wizard_controller.cc
@@ -907,9 +907,9 @@ // Launch browser and delete login host controller. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, - base::Bind(&UserSessionManager::DoBrowserLaunch, - base::Unretained(UserSessionManager::GetInstance()), - ProfileManager::GetActiveUserProfile(), host_)); + base::BindOnce(&UserSessionManager::DoBrowserLaunch, + base::Unretained(UserSessionManager::GetInstance()), + ProfileManager::GetActiveUserProfile(), host_)); host_ = nullptr; }
diff --git a/chrome/browser/chromeos/night_light/OWNERS b/chrome/browser/chromeos/night_light/OWNERS new file mode 100644 index 0000000..1bfdf742 --- /dev/null +++ b/chrome/browser/chromeos/night_light/OWNERS
@@ -0,0 +1,2 @@ +afakhry@chromium.org +jamescook@chromium.org \ No newline at end of file
diff --git a/chrome/browser/chromeos/night_light/night_light_client.cc b/chrome/browser/chromeos/night_light/night_light_client.cc index 0b8941b..0ba2982 100644 --- a/chrome/browser/chromeos/night_light/night_light_client.cc +++ b/chrome/browser/chromeos/night_light/night_light_client.cc
@@ -4,7 +4,10 @@ #include "chrome/browser/chromeos/night_light/night_light_client.h" +#include <algorithm> + #include "ash/public/interfaces/constants.mojom.h" +#include "base/time/clock.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" @@ -31,7 +34,8 @@ url_context_getter, chromeos::SimpleGeolocationProvider::DefaultGeolocationProviderURL()), binding_(this), - backoff_delay_(kMinimumDelayAfterFailure) {} + backoff_delay_(kMinimumDelayAfterFailure), + timer_(base::MakeUnique<base::OneShotTimer>()) {} NightLightClient::~NightLightClient() {} @@ -49,15 +53,33 @@ void NightLightClient::OnScheduleTypeChanged( ash::mojom::NightLightController::ScheduleType new_type) { - if (new_type == + if (new_type != ash::mojom::NightLightController::ScheduleType::kSunsetToSunrise) { - // Schedule an immediate request. - using_geoposition_ = true; - ScheduleNextRequest(base::TimeDelta::FromSeconds(0)); - } else { using_geoposition_ = false; - timer_.Stop(); + timer_->Stop(); + return; } + + using_geoposition_ = true; + // No need to request a new position if we already have a valid one from a + // request less than kNextRequestDelayAfterSuccess ago. + base::Time now = GetNow(); + if ((now - last_successful_geo_request_time_) < + kNextRequestDelayAfterSuccess) { + // Use the current valid position to update NightLightController. + SendCurrentGeoposition(); + } + + // Next request is either immediate or kNextRequestDelayAfterSuccess later + // than the last success time, whichever is greater. + ScheduleNextRequest(std::max( + base::TimeDelta::FromSeconds(0), + last_successful_geo_request_time_ + kNextRequestDelayAfterSuccess - now)); +} + +// static +base::TimeDelta NightLightClient::GetNextRequestDelayAfterSuccessForTesting() { + return kNextRequestDelayAfterSuccess; } void NightLightClient::SetNightLightControllerPtrForTesting( @@ -69,6 +91,15 @@ night_light_controller_.FlushForTesting(); } +void NightLightClient::SetTimerForTesting( + std::unique_ptr<base::OneShotTimer> timer) { + timer_ = std::move(timer); +} + +void NightLightClient::SetClockForTesting(base::Clock* clock) { + clock_ = clock; +} + void NightLightClient::OnGeoposition(const chromeos::Geoposition& position, bool server_error, const base::TimeDelta elapsed) { @@ -90,9 +121,11 @@ return; } - night_light_controller_->SetCurrentGeoposition( - ash::mojom::SimpleGeoposition::New(position.latitude, - position.longitude)); + last_successful_geo_request_time_ = GetNow(); + + latitude_ = position.latitude; + longitude_ = position.longitude; + SendCurrentGeoposition(); // On success, reset the backoff delay to its minimum value, and schedule // another request. @@ -100,8 +133,17 @@ ScheduleNextRequest(kNextRequestDelayAfterSuccess); } +base::Time NightLightClient::GetNow() const { + return clock_ ? clock_->Now() : base::Time::Now(); +} + +void NightLightClient::SendCurrentGeoposition() { + night_light_controller_->SetCurrentGeoposition( + ash::mojom::SimpleGeoposition::New(latitude_, longitude_)); +} + void NightLightClient::ScheduleNextRequest(base::TimeDelta delay) { - timer_.Start(FROM_HERE, delay, this, &NightLightClient::RequestGeoposition); + timer_->Start(FROM_HERE, delay, this, &NightLightClient::RequestGeoposition); } void NightLightClient::RequestGeoposition() {
diff --git a/chrome/browser/chromeos/night_light/night_light_client.h b/chrome/browser/chromeos/night_light/night_light_client.h index 0f8580d..0594840 100644 --- a/chrome/browser/chromeos/night_light/night_light_client.h +++ b/chrome/browser/chromeos/night_light/night_light_client.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_CHROMEOS_NIGHT_LIGHT_NIGHT_LIGHT_CLIENT_H_ #define CHROME_BROWSER_CHROMEOS_NIGHT_LIGHT_NIGHT_LIGHT_CLIENT_H_ +#include <memory> + #include "ash/public/interfaces/night_light_controller.mojom.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -12,6 +14,10 @@ #include "chromeos/geolocation/simple_geolocation_provider.h" #include "mojo/public/cpp/bindings/binding.h" +namespace base { +class Clock; +} // namespace base + namespace net { class URLRequestContextGetter; } @@ -21,7 +27,7 @@ class NightLightClient : public NON_EXPORTED_BASE(ash::mojom::NightLightClient) { public: - explicit NightLightClient(net::URLRequestContextGetter* url_context_getter); + NightLightClient(net::URLRequestContextGetter* url_context_getter); ~NightLightClient() override; // Starts watching changes in the Night Light schedule type in order to begin @@ -33,19 +39,36 @@ void OnScheduleTypeChanged( ash::mojom::NightLightController::ScheduleType new_type) override; + const base::OneShotTimer& timer() const { return *timer_; } + + base::Time last_successful_geo_request_time() const { + return last_successful_geo_request_time_; + } + bool using_geoposition() const { return using_geoposition_; } + static base::TimeDelta GetNextRequestDelayAfterSuccessForTesting(); + void SetNightLightControllerPtrForTesting( ash::mojom::NightLightControllerPtr controller); void FlushNightLightControllerForTesting(); + void SetTimerForTesting(std::unique_ptr<base::OneShotTimer> timer); + + void SetClockForTesting(base::Clock* clock); + protected: void OnGeoposition(const chromeos::Geoposition& position, bool server_error, const base::TimeDelta elapsed); private: + base::Time GetNow() const; + + // Sends the most recent valid geoposition to NightLightController in ash. + void SendCurrentGeoposition(); + void ScheduleNextRequest(base::TimeDelta delay); // Virtual so that it can be overriden by a fake implementation in unit tests @@ -61,7 +84,15 @@ // Delay after which a new request is retried after a failed one. base::TimeDelta backoff_delay_; - base::OneShotTimer timer_; + std::unique_ptr<base::OneShotTimer> timer_; + + // Optional Used in tests to override the time of "Now". + base::Clock* clock_ = nullptr; // Not owned. + + // Last successful geoposition coordinates and its timestamp. + base::Time last_successful_geo_request_time_; + double latitude_ = 0.0; + double longitude_ = 0.0; // True as long as the schedule type is set to "sunset to sunrise", which // means this client will be retrieving the IP-based geoposition once per day.
diff --git a/chrome/browser/chromeos/night_light/night_light_client_unittest.cc b/chrome/browser/chromeos/night_light/night_light_client_unittest.cc index bfe124b..de6f88f 100644 --- a/chrome/browser/chromeos/night_light/night_light_client_unittest.cc +++ b/chrome/browser/chromeos/night_light/night_light_client_unittest.cc
@@ -6,6 +6,8 @@ #include "ash/public/interfaces/night_light_controller.mojom.h" #include "base/test/scoped_task_environment.h" +#include "base/time/clock.h" +#include "base/time/tick_clock.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,6 +21,8 @@ FakeNightLightController() : binding_(this) {} ~FakeNightLightController() override = default; + const ash::mojom::SimpleGeopositionPtr& position() const { return position_; } + int position_pushes_num() const { return position_pushes_num_; } ash::mojom::NightLightControllerPtr CreateInterfacePtrAndBind() { @@ -56,25 +60,51 @@ // A fake implementation of NightLightClient that doesn't perform any actual // geoposition requests. -class FakeNightLightClient : public NightLightClient { +class FakeNightLightClient : public NightLightClient, + public base::Clock, + public base::TickClock { public: - FakeNightLightClient() : NightLightClient(nullptr /* url_context_getter */) {} + FakeNightLightClient() : NightLightClient(nullptr /* url_context_getter */) { + SetTimerForTesting( + base::MakeUnique<base::OneShotTimer>(this /* tick_clock */)); + SetClockForTesting(this); + } ~FakeNightLightClient() override = default; + // base::Clock: + base::Time Now() override { return fake_now_; } + + // base::TickClock: + base::TimeTicks NowTicks() override { return fake_now_ticks_; } + + void set_fake_now(base::Time now) { fake_now_ = now; } + void set_fake_now_ticks(base::TimeTicks now_ticks) { + fake_now_ticks_ = now_ticks; + } + void set_position_to_send(const chromeos::Geoposition& position) { position_to_send_ = position; } + int geoposition_requests_num() const { return geoposition_requests_num_; } + private: // night_light::NightLightClient: void RequestGeoposition() override { OnGeoposition(position_to_send_, false, base::TimeDelta()); + ++geoposition_requests_num_; } + base::Time fake_now_; + base::TimeTicks fake_now_ticks_; + // The position to send to the controller the next time OnGeoposition is // invoked. chromeos::Geoposition position_to_send_; + // The number of new geoposition requests that have been triggered. + int geoposition_requests_num_ = 0; + DISALLOW_COPY_AND_ASSIGN(FakeNightLightClient); }; @@ -85,6 +115,10 @@ ~NightLightClientTest() override = default; void SetUp() override { + // Deterministic fake time that doesn't change for the sake of testing. + client_.set_fake_now(base::Time::Now()); + client_.set_fake_now_ticks(base::TimeTicks::Now()); + client_.SetNightLightControllerPtrForTesting( controller_.CreateInterfacePtrAndBind()); client_.Start(); @@ -119,29 +153,71 @@ } // Test that client only pushes valid positions. -TEST_F(NightLightClientTest, TestPositionPushes) { - // Start with a valid position, and expect it to be delivered to the - // controller. +TEST_F(NightLightClientTest, TestInvalidPositions) { EXPECT_EQ(0, controller_.position_pushes_num()); chromeos::Geoposition position; position.latitude = 32.0; position.longitude = 31.0; - position.status = chromeos::Geoposition::STATUS_OK; + position.status = chromeos::Geoposition::STATUS_TIMEOUT; position.accuracy = 10; position.timestamp = base::Time::Now(); client_.set_position_to_send(position); controller_.NotifyScheduleTypeChanged(ScheduleType::kSunsetToSunrise); scoped_task_environment_.RunUntilIdle(); client_.FlushNightLightControllerForTesting(); - EXPECT_EQ(1, controller_.position_pushes_num()); + EXPECT_EQ(1, client_.geoposition_requests_num()); + EXPECT_EQ(0, controller_.position_pushes_num()); +} - // Invalid positions should not be sent. - position.status = chromeos::Geoposition::STATUS_TIMEOUT; - client_.set_position_to_send(position); +// Test that successive changes of the schedule type to sunset to sunrise do not +// trigger repeated geoposition requests. +TEST_F(NightLightClientTest, TestRepeatedScheduleTypeChanges) { + // Start with a valid position, and expect it to be delivered to the + // controller. + EXPECT_EQ(0, controller_.position_pushes_num()); + chromeos::Geoposition position1; + position1.latitude = 32.0; + position1.longitude = 31.0; + position1.status = chromeos::Geoposition::STATUS_OK; + position1.accuracy = 10; + position1.timestamp = base::Time::Now(); + client_.set_position_to_send(position1); controller_.NotifyScheduleTypeChanged(ScheduleType::kSunsetToSunrise); scoped_task_environment_.RunUntilIdle(); client_.FlushNightLightControllerForTesting(); + EXPECT_EQ(1, client_.geoposition_requests_num()); EXPECT_EQ(1, controller_.position_pushes_num()); + EXPECT_EQ(client_.Now(), client_.last_successful_geo_request_time()); + + // A new different position just for the sake of comparison with position1 to + // make sure that no new requests are triggered and the same old position will + // be resent to the controller. + chromeos::Geoposition position2; + position2.latitude = 100.0; + position2.longitude = 200.0; + position2.status = chromeos::Geoposition::STATUS_OK; + position2.accuracy = 10; + position2.timestamp = base::Time::Now(); + client_.set_position_to_send(position2); + controller_.NotifyScheduleTypeChanged(ScheduleType::kSunsetToSunrise); + scoped_task_environment_.RunUntilIdle(); + client_.FlushNightLightControllerForTesting(); + // No new request has been triggered, however the same old valid position was + // pushed to the controller. + EXPECT_EQ(1, client_.geoposition_requests_num()); + EXPECT_EQ(2, controller_.position_pushes_num()); + EXPECT_TRUE(ash::mojom::SimpleGeoposition::New(position1.latitude, + position1.longitude) + .Equals(controller_.position())); + + // The timer should be running scheduling a next request that is a + // kNextRequestDelayAfterSuccess from the last successful request time. + EXPECT_TRUE(client_.timer().IsRunning()); + base::TimeDelta expected_delay = + client_.last_successful_geo_request_time() + + NightLightClient::GetNextRequestDelayAfterSuccessForTesting() - + client_.Now(); + EXPECT_EQ(expected_delay, client_.timer().GetCurrentDelay()); } } // namespace
diff --git a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc index 51ceec0..40d6659 100644 --- a/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc +++ b/chrome/browser/chromeos/ownership/owner_settings_service_chromeos.cc
@@ -712,8 +712,10 @@ &settings); has_pending_fixups_ = false; + scoped_refptr<base::TaskRunner> task_runner = + base::CreateTaskRunnerWithTraits({base::MayBlock()}); bool rv = AssembleAndSignPolicyAsync( - content::BrowserThread::GetBlockingPool(), std::move(policy), + task_runner.get(), std::move(policy), base::Bind(&OwnerSettingsServiceChromeOS::OnPolicyAssembledAndSigned, store_settings_factory_.GetWeakPtr())); if (!rv)
diff --git a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc index 78375691..15df190 100644 --- a/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc +++ b/chrome/browser/chromeos/printing/cups_print_job_manager_impl.cc
@@ -356,11 +356,11 @@ if (!in_query_) { in_query_ = true; - content::BrowserThread::GetTaskRunnerForThread(content::BrowserThread::UI) - ->PostDelayedTask(FROM_HERE, - base::Bind(&CupsPrintJobManagerImpl::PostQuery, - weak_ptr_factory_.GetWeakPtr()), - delay); + content::BrowserThread::PostDelayedTask( + content::BrowserThread::UI, FROM_HERE, + base::Bind(&CupsPrintJobManagerImpl::PostQuery, + weak_ptr_factory_.GetWeakPtr()), + delay); } } @@ -376,7 +376,7 @@ auto result = base::MakeUnique<QueryResult>(); QueryResult* result_ptr = result.get(); - // Runs a query on query_runner_ which will rejoin this sequnece on + // Runs a query on |query_runner_| which will rejoin this sequnece on // completion. query_runner_->PostTaskAndReply( FROM_HERE,
diff --git a/chrome/browser/chromeos/profiles/profile_helper.h b/chrome/browser/chromeos/profiles/profile_helper.h index 2c302ba0..bb0eb05 100644 --- a/chrome/browser/chromeos/profiles/profile_helper.h +++ b/chrome/browser/chromeos/profiles/profile_helper.h
@@ -31,7 +31,8 @@ } namespace arc { -class ArcActiveDirectoryEnrollmentTokenFetcherBrowserTest; +class ArcAuthServiceTest; +class ArcSessionManagerTest; } namespace ash { @@ -190,7 +191,8 @@ friend class ProfileListChromeOSTest; friend class SystemTrayDelegateChromeOSTest; friend class ash::test::MultiUserWindowManagerChromeOSTest; - friend class arc::ArcActiveDirectoryEnrollmentTokenFetcherBrowserTest; + friend class arc::ArcSessionManagerTest; + friend class arc::ArcAuthServiceTest; friend class ::ArcAppTest; friend class ::SessionControllerClientTest; friend class ::test::BrowserFinderChromeOSTest;
diff --git a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc index 27c015d3..50632934 100644 --- a/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc +++ b/chrome/browser/content_settings/content_settings_pref_provider_unittest.cc
@@ -181,69 +181,6 @@ std::string(), false)); } -// Tests that last usage content settings are cleared. -TEST_F(PrefProviderTest, DiscardObsoleteLastUsagePreferences) { - std::string kGeolocationPrefPath = - ContentSettingsRegistry::GetInstance() - ->Get(CONTENT_SETTINGS_TYPE_GEOLOCATION) - ->website_settings_info() - ->pref_name(); - std::string kMicPrefPath = ContentSettingsRegistry::GetInstance() - ->Get(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) - ->website_settings_info() - ->pref_name(); - const char kObsoleteLastUsed[] = "last_used"; - - TestingProfile profile; - PrefService* prefs = profile.GetPrefs(); - - // Content settings prefs are structured as follows: - // "media_stream_mic": { - // "https://example.com:443,*": { - // "last_used": 1486968992.758971, - // "setting": 1 - // } - // } - const char kPattern[] = "https://example.com:443,*"; - GURL host("https://example.com/"); - - auto geolocation_pattern_data = base::MakeUnique<base::DictionaryValue>(); - geolocation_pattern_data->SetDouble(kObsoleteLastUsed, 1485000000.0); - base::DictionaryValue geolocation_pref_data; - geolocation_pref_data.SetWithoutPathExpansion( - kPattern, std::move(geolocation_pattern_data)); - prefs->Set(kGeolocationPrefPath, geolocation_pref_data); - - auto mic_pattern_data = base::MakeUnique<base::DictionaryValue>(); - mic_pattern_data->SetInteger("setting", CONTENT_SETTING_ALLOW); - mic_pattern_data->SetDouble(kObsoleteLastUsed, 1480000000.0); - base::DictionaryValue mic_pref_data; - mic_pref_data.SetWithoutPathExpansion(kPattern, std::move(mic_pattern_data)); - prefs->Set(kMicPrefPath, mic_pref_data); - - // Instantiate a new PrefProvider here, because we want to test the - // constructor's behavior after setting the above. - PrefProvider provider(prefs, false /* incognito */, - true /* store_last_modified */); - - // Check that last_used data has been deleted. - EXPECT_TRUE(prefs->GetDictionary(kGeolocationPrefPath)->empty()); - auto* mic_prefs = prefs->GetDictionary(kMicPrefPath); - const base::DictionaryValue* mic_result_pattern_data; - ASSERT_TRUE(mic_prefs->GetDictionaryWithoutPathExpansion( - kPattern, &mic_result_pattern_data)); - EXPECT_EQ(static_cast<size_t>(1), mic_result_pattern_data->size()); - int mic_result_setting; - EXPECT_TRUE( - mic_result_pattern_data->GetInteger("setting", &mic_result_setting)); - EXPECT_EQ(CONTENT_SETTING_ALLOW, mic_result_setting); - EXPECT_EQ(CONTENT_SETTING_ALLOW, - TestUtils::GetContentSetting(&provider, host, host, - CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC, - std::string(), false)); - provider.ShutdownOnUIThread(); -} - // Test for regression in which the PrefProvider modified the user pref store // of the OTR unintentionally: http://crbug.com/74466. TEST_F(PrefProviderTest, Incognito) {
diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 478d000..b9a33b03 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn
@@ -224,8 +224,6 @@ "api/identity/identity_mint_queue.h", "api/identity/identity_remove_cached_auth_token_function.cc", "api/identity/identity_remove_cached_auth_token_function.h", - "api/identity/identity_signin_flow.cc", - "api/identity/identity_signin_flow.h", "api/identity/web_auth_flow.cc", "api/identity/web_auth_flow.h", "api/idltest/idltest_api.cc",
diff --git a/chrome/browser/extensions/api/identity/identity_api.h b/chrome/browser/extensions/api/identity/identity_api.h index 83a293e..0d25874 100644 --- a/chrome/browser/extensions/api/identity/identity_api.h +++ b/chrome/browser/extensions/api/identity/identity_api.h
@@ -24,7 +24,6 @@ #include "chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.h" #include "chrome/browser/extensions/api/identity/identity_mint_queue.h" #include "chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h" -#include "chrome/browser/extensions/api/identity/identity_signin_flow.h" #include "chrome/browser/extensions/api/identity/web_auth_flow.h" #include "chrome/browser/extensions/chrome_extension_function.h" #include "components/signin/core/browser/profile_identity_provider.h"
diff --git a/chrome/browser/extensions/api/identity/identity_apitest.cc b/chrome/browser/extensions/api/identity/identity_apitest.cc index 8e5f4d5..80be4cc4 100644 --- a/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chrome/browser/extensions/api/identity/identity_apitest.cc
@@ -323,10 +323,17 @@ void ShowLoginPopup() override { EXPECT_FALSE(login_ui_shown_); login_ui_shown_ = true; - if (login_ui_result_) - SigninSuccess(); - else + if (login_ui_result_) { + ::identity::AccountState account_state; + account_state.has_refresh_token = true; + account_state.is_primary_account = true; + OnPrimaryAccountAvailable( + SigninManagerFactory::GetForProfile(GetProfile()) + ->GetAuthenticatedAccountInfo(), + account_state); + } else { SigninFailed(); + } } void ShowOAuthApprovalDialog(const IssueAdviceInfo& issue_advice) override { @@ -924,7 +931,11 @@ std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); +// ChromeOS does not support the interactive login flow, so the login UI will +// never be shown on that platform. +#if !defined(OS_CHROMEOS) EXPECT_TRUE(func->login_ui_shown()); +#endif EXPECT_FALSE(func->scope_ui_shown()); } @@ -939,22 +950,18 @@ std::string error = utils::RunFunctionAndReturnError( func.get(), "[{\"interactive\": true}]", browser()); EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); +// ChromeOS does not support the interactive login flow, so the login UI will +// never be shown on that platform. +#if !defined(OS_CHROMEOS) EXPECT_TRUE(func->login_ui_shown()); +#endif EXPECT_FALSE(func->scope_ui_shown()); } -IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, - InteractiveLoginSuccessNoToken) { - scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction()); - func->set_extension(CreateExtension(CLIENT_ID | SCOPES)); - func->set_login_ui_result(false); - std::string error = utils::RunFunctionAndReturnError( - func.get(), "[{\"interactive\": true}]", browser()); - EXPECT_EQ(std::string(errors::kUserNotSignedIn), error); - EXPECT_TRUE(func->login_ui_shown()); - EXPECT_FALSE(func->scope_ui_shown()); -} - +// The interactive login flow is always short-circuited out with failure on +// ChromeOS, so the tests of the interactive login flow being successful are not +// relevant on that platform. +#if !defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveLoginSuccessMintFailure) { scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction()); @@ -1030,6 +1037,7 @@ EXPECT_TRUE(func->login_ui_shown()); EXPECT_TRUE(func->scope_ui_shown()); } +#endif IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveApprovalAborted) { @@ -1357,6 +1365,9 @@ EXPECT_FALSE(func->scope_ui_shown()); } +// The interactive login UI is never shown on ChromeOS, so tests of the +// interactive login flow being successful are not relevant on that platform. +#if !defined(OS_CHROMEOS) IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, LoginInvalidatesTokenCache) { scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction()); @@ -1383,6 +1394,7 @@ EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken(std::string()).status()); } +#endif IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, ComponentWithChromeClientId) { scoped_refptr<FakeGetAuthTokenFunction> func(new FakeGetAuthTokenFunction());
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc index 1b3c20a..b304dbc 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc
@@ -5,17 +5,18 @@ #include "chrome/browser/extensions/api/identity/identity_get_auth_token_function.h" #include "base/strings/string_number_conversions.h" +#include "build/build_config.h" #include "chrome/browser/extensions/api/identity/identity_api.h" #include "chrome/browser/extensions/api/identity/identity_constants.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/ui/webui/signin/login_ui_service.h" +#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/common/extensions/api/identity.h" #include "components/signin/core/browser/account_tracker_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/common/profile_management_switches.h" #include "content/public/common/service_manager_connection.h" #include "extensions/common/extension_l10n_util.h" @@ -49,12 +50,6 @@ "chrome-extension://gbchcmhmhahfdphkhkmpfmihenigjmpp/"}; #endif -std::string GetPrimaryAccountId(content::BrowserContext* context) { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(Profile::FromBrowserContext(context)); - return signin_manager->GetAuthenticatedAccountId(); -} - } // namespace namespace identity = api::identity; @@ -254,9 +249,24 @@ IdentityAPI* id_api = extensions::IdentityAPI::GetFactoryInstance()->Get(GetProfile()); id_api->EraseAllCachedTokens(); - // Display a login prompt. If the subsequent mint fails, don't display the - // login prompt again. + + // If the signin flow fails, don't display the login prompt again. should_prompt_for_signin_ = false; + +#if defined(OS_CHROMEOS) + // In normal mode (i.e. non-kiosk mode), the user has to log out to + // re-establish credentials. Let the global error popup handle everything. + // In kiosk mode, interactive sign-in is not supported. + SigninFailed(); + return; +#endif + + // Start listening for the primary account being available and display a + // login prompt. + GetIdentityManager()->GetPrimaryAccountWhenAvailable( + base::Bind(&IdentityGetAuthTokenFunction::OnPrimaryAccountAvailable, + base::Unretained(this))); + ShowLoginPopup(); } @@ -440,16 +450,16 @@ StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_INTERACTIVE); } -void IdentityGetAuthTokenFunction::SigninSuccess() { - TRACE_EVENT_ASYNC_STEP_PAST0("identity", - "IdentityGetAuthTokenFunction", - this, - "SigninSuccess"); +void IdentityGetAuthTokenFunction::OnPrimaryAccountAvailable( + const AccountInfo& account_info, + const ::identity::AccountState& account_state) { + TRACE_EVENT_ASYNC_STEP_PAST0("identity", "IdentityGetAuthTokenFunction", this, + "OnPrimaryAccountAvailable"); // If there was no account associated this profile before the // sign-in, we may not have an account_id in the token_key yet. if (token_key_->account_id.empty()) { - token_key_->account_id = GetPrimaryAccountId(GetProfile()); + token_key_->account_id = account_info.account_id; } StartMintTokenFlow(IdentityMintRequestQueue::MINT_TYPE_NONINTERACTIVE); @@ -574,7 +584,6 @@ void IdentityGetAuthTokenFunction::Shutdown() { gaia_web_auth_flow_.reset(); - signin_flow_.reset(); login_token_request_.reset(); identity_manager_.reset(); @@ -654,8 +663,9 @@ } void IdentityGetAuthTokenFunction::ShowLoginPopup() { - signin_flow_.reset(new IdentitySigninFlow(this, GetProfile())); - signin_flow_->Start(); + LoginUIService* login_ui_service = + LoginUIServiceFactory::GetForProfile(GetProfile()); + login_ui_service->ShowLoginPopup(); } void IdentityGetAuthTokenFunction::ShowOAuthApprovalDialog(
diff --git a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h index ee23b26..6acf9660 100644 --- a/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h +++ b/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h
@@ -7,7 +7,6 @@ #include "chrome/browser/extensions/api/identity/gaia_web_auth_flow.h" #include "chrome/browser/extensions/api/identity/identity_mint_queue.h" -#include "chrome/browser/extensions/api/identity/identity_signin_flow.h" #include "chrome/browser/extensions/chrome_extension_function.h" #include "extensions/browser/extension_function_histogram_value.h" #include "google_apis/gaia/oauth2_mint_token_flow.h" @@ -37,11 +36,10 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction, public GaiaWebAuthFlow::Delegate, public IdentityMintRequestQueue::Request, - public OAuth2MintTokenFlow::Delegate, #if defined(OS_CHROMEOS) public OAuth2TokenService::Consumer, #endif - public IdentitySigninFlow::Delegate { + public OAuth2MintTokenFlow::Delegate { public: DECLARE_EXTENSION_FUNCTION("identity.getAuthToken", EXPERIMENTAL_IDENTITY_GETAUTHTOKEN); @@ -57,9 +55,7 @@ protected: ~IdentityGetAuthTokenFunction() override; - // IdentitySigninFlow::Delegate implementation: - void SigninSuccess() override; - void SigninFailed() override; + void SigninFailed(); // GaiaWebAuthFlow::Delegate implementation: void OnGaiaFlowFailure(GaiaWebAuthFlow::Failure failure, @@ -89,6 +85,10 @@ base::Time expiration_time, const GoogleServiceAuthError& error); + // Invoked by the IdentityManager when the primary account is available. + void OnPrimaryAccountAvailable(const AccountInfo& account_info, + const identity::AccountState& account_state); + // Starts a mint token request to GAIA. // Exposed for testing. virtual void StartGaiaRequest(const std::string& login_access_token); @@ -192,7 +192,6 @@ // a permissions prompt will be popped up to the user. IssueAdviceInfo issue_advice_; std::unique_ptr<GaiaWebAuthFlow> gaia_web_auth_flow_; - std::unique_ptr<IdentitySigninFlow> signin_flow_; identity::mojom::IdentityManagerPtr identity_manager_; };
diff --git a/chrome/browser/extensions/api/identity/identity_signin_flow.cc b/chrome/browser/extensions/api/identity/identity_signin_flow.cc deleted file mode 100644 index 1a0ed0e3..0000000 --- a/chrome/browser/extensions/api/identity/identity_signin_flow.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/identity/identity_signin_flow.h" - -#include "build/build_config.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" -#include "chrome/browser/ui/webui/signin/login_ui_service.h" -#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" - -namespace extensions { - -IdentitySigninFlow::IdentitySigninFlow(Delegate* delegate, Profile* profile) - : delegate_(delegate), - profile_(profile) { -} - -IdentitySigninFlow::~IdentitySigninFlow() { - ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)-> - RemoveObserver(this); -} - -void IdentitySigninFlow::Start() { - DCHECK(delegate_); - -#if defined(OS_CHROMEOS) - // In normal mode (i.e. non-kiosk mode), the user has to log out to - // re-establish credentials. Let the global error popup handle everything. - // In kiosk mode, interactive sign-in is not supported. - delegate_->SigninFailed(); - return; -#endif - - ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->AddObserver(this); - - LoginUIService* login_ui_service = - LoginUIServiceFactory::GetForProfile(profile_); - login_ui_service->ShowLoginPopup(); -} - -void IdentitySigninFlow::OnRefreshTokenAvailable( - const std::string& account_id) { - if (SigninManagerFactory::GetForProfile(profile_)-> - GetAuthenticatedAccountId() == account_id) { - delegate_->SigninSuccess(); - } -} - -} // namespace extensions
diff --git a/chrome/browser/extensions/api/identity/identity_signin_flow.h b/chrome/browser/extensions/api/identity/identity_signin_flow.h deleted file mode 100644 index 43a8393..0000000 --- a/chrome/browser/extensions/api/identity/identity_signin_flow.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_IDENTITY_IDENTITY_SIGNIN_FLOW_H_ -#define CHROME_BROWSER_EXTENSIONS_API_IDENTITY_IDENTITY_SIGNIN_FLOW_H_ - -#include <memory> -#include <string> - -#include "base/macros.h" -#include "google_apis/gaia/oauth2_token_service.h" - -class Profile; - -namespace extensions { - -// IdentitySigninFlow is a controller class to do a sign-in flow for an -// interactive Identity API call. The UI is launched through the LoginUIService. -// When the flow completes, the delegate is notified, and on success will -// be given an OAuth2 login refresh token. -class IdentitySigninFlow : public OAuth2TokenService::Observer { - public: - class Delegate { - public: - Delegate() {} - virtual ~Delegate() {} - // Called when the flow has completed successfully. - virtual void SigninSuccess() = 0; - // Called when the flow has failed. - virtual void SigninFailed() = 0; - - DISALLOW_COPY_AND_ASSIGN(Delegate); - }; - - IdentitySigninFlow(Delegate* delegate, - Profile* profile); - ~IdentitySigninFlow() override; - - // Starts the flow. Should only be called once. - void Start(); - - // OAuth2TokenService::Observer implementation: - void OnRefreshTokenAvailable(const std::string& account_id) override; - - private: - Delegate* delegate_; - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(IdentitySigninFlow); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_IDENTITY_IDENTITY_SIGNIN_FLOW_H_
diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc index 826edf29..65dac00 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
@@ -752,15 +752,14 @@ blob_uuids->push_back(current_blob->GetUUID()); - content::RenderProcessHost* render_process_host = - render_frame_host()->GetProcess(); - if (!render_process_host) { + if (!render_frame_host() || !render_frame_host()->GetProcess()) { SendResponse(false); return; } extensions::BlobHolder* holder = - extensions::BlobHolder::FromRenderProcessHost(render_process_host); + extensions::BlobHolder::FromRenderProcessHost( + render_frame_host()->GetProcess()); holder->HoldBlobReference(std::move(current_blob)); // Construct the next Blob if necessary.
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 98b61d2..221a679 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2504,6 +2504,12 @@ const char kOfflinePagesCtDescription[] = "Enable Offline Pages CT features."; +const char kOfflinePagesCtV2Name[] = "Enable Offline Pages CT V2 features."; + +const char kOfflinePagesCtV2Description[] = + "V2 features include attributing pages to the app that initiated the " + "custom tabs, and being able to query for pages by page attribution."; + #endif // defined(OS_ANDROID) #if defined(OS_ANDROID) @@ -3183,10 +3189,11 @@ "the current page is provided as the first suggestion without a title. " "Enabling this flag causes the title to be displayed."; -const char kOmniboxUIHideSuggestionUrlPathName[] = - "Omnibox UI Hide Suggestion URL Path"; -const char kOmniboxUIHideSuggestionUrlPathDescription[] = - "Elides the paths of suggested URLs in the Omnibox dropdown."; +const char kOmniboxUIElideSuggestionUrlAfterHostName[] = + "Omnibox UI Elide Suggestion URL After Host"; +const char kOmniboxUIElideSuggestionUrlAfterHostDescription[] = + "Elides the path, query, and ref of suggested URLs in the Omnibox " + "dropdown."; const char kOmniboxUIHideSuggestionUrlSchemeName[] = "Omnibox UI Hide Suggestion URL Scheme";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 930247a..afbb68a 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -513,8 +513,8 @@ extern const char kOmniboxDisplayTitleForCurrentUrlName[]; extern const char kOmniboxDisplayTitleForCurrentUrlDescription[]; -extern const char kOmniboxUIHideSuggestionUrlPathName[]; -extern const char kOmniboxUIHideSuggestionUrlPathDescription[]; +extern const char kOmniboxUIElideSuggestionUrlAfterHostName[]; +extern const char kOmniboxUIElideSuggestionUrlAfterHostDescription[]; extern const char kOmniboxUIHideSuggestionUrlSchemeName[]; extern const char kOmniboxUIHideSuggestionUrlSchemeDescription[]; @@ -1067,6 +1067,9 @@ extern const char kOfflinePagesCtName[]; extern const char kOfflinePagesCtDescription[]; +extern const char kOfflinePagesCtV2Name[]; +extern const char kOfflinePagesCtV2Description[]; + extern const char kOfflinePagesLoadSignalCollectingName[]; extern const char kOfflinePagesLoadSignalCollectingDescription[];
diff --git a/chrome/browser/google/google_update_settings_posix.cc b/chrome/browser/google/google_update_settings_posix.cc index d053b1e..d6de41e 100644 --- a/chrome/browser/google/google_update_settings_posix.cc +++ b/chrome/browser/google/google_update_settings_posix.cc
@@ -10,6 +10,7 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" +#include "base/task_scheduler/lazy_task_runner.h" #include "build/build_config.h" #include "chrome/common/chrome_paths.h" @@ -19,6 +20,12 @@ namespace { +base::LazySequencedTaskRunner g_collect_stats_consent_task_runner = + LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER( + base::TaskTraits(base::MayBlock(), + base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN)); + base::LazyInstance<std::string>::Leaky g_posix_client_id = LAZY_INSTANCE_INITIALIZER; base::LazyInstance<base::Lock>::Leaky g_posix_client_id_lock = @@ -42,6 +49,14 @@ } // namespace // static +base::SequencedTaskRunner* +GoogleUpdateSettings::CollectStatsConsentTaskRunner() { + // TODO(fdoray): Use LazySequencedTaskRunner::GetRaw() here instead of + // .Get().get() when it's added to the API, http://crbug.com/730170. + return g_collect_stats_consent_task_runner.Get().get(); +} + +// static bool GoogleUpdateSettings::GetCollectStatsConsent() { base::FilePath consent_file; PathService::Get(chrome::DIR_USER_DATA, &consent_file);
diff --git a/chrome/browser/media/media_engagement_contents_observer.cc b/chrome/browser/media/media_engagement_contents_observer.cc index aae3c6d..8e90abe 100644 --- a/chrome/browser/media/media_engagement_contents_observer.cc +++ b/chrome/browser/media/media_engagement_contents_observer.cc
@@ -59,8 +59,7 @@ if (committed_origin_.unique()) return; - - // TODO(mlamouri): record the visit into content settings. + service_->RecordVisit(committed_origin_.GetURL()); } void MediaEngagementContentsObserver::WasShown() { @@ -149,7 +148,7 @@ if (committed_origin_.unique()) return; - // TODO(mlamouri): record the playback into content settings. + service_->RecordPlayback(committed_origin_.GetURL()); } void MediaEngagementContentsObserver::MaybeInsertSignificantPlayer(
diff --git a/chrome/browser/media/media_engagement_contents_observer_unittest.cc b/chrome/browser/media/media_engagement_contents_observer_unittest.cc index 5c0cbad..7cc4d225 100644 --- a/chrome/browser/media/media_engagement_contents_observer_unittest.cc +++ b/chrome/browser/media/media_engagement_contents_observer_unittest.cc
@@ -6,6 +6,7 @@ #include "base/test/scoped_feature_list.h" #include "base/timer/mock_timer.h" +#include "chrome/browser/media/media_engagement_score.h" #include "chrome/browser/media/media_engagement_service.h" #include "chrome/browser/media/media_engagement_service_factory.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" @@ -47,13 +48,6 @@ return contents_observer_->player_states_.size(); } - void Navigate(GURL url) { - std::unique_ptr<content::NavigationHandle> test_handle = - content::NavigationHandle::CreateNavigationHandleForTesting( - url, main_rfh(), true /** committed */); - contents_observer_->DidFinishNavigation(test_handle.get()); - } - void SimulatePlaybackStarted(int id) { content::WebContentsObserver::MediaPlayerInfo player_info(true, true); SimulatePlaybackStarted(player_info, id); @@ -99,8 +93,36 @@ contents_observer_->significant_playback_recorded_ = true; } + void SimulateSignificantPlaybackTime() { + contents_observer_->OnSignificantMediaPlaybackTime(); + } + void SimulatePlaybackTimerFired() { playback_timer_->Fire(); } + void ExpectScores(GURL url, + double expected_score, + int expected_visits, + int expected_media_playbacks) { + EXPECT_EQ(contents_observer_->service_->GetEngagementScore(url), + expected_score); + EXPECT_EQ(contents_observer_->service_->GetScoreMapForTesting()[url], + expected_score); + + MediaEngagementScore* score = + contents_observer_->service_->CreateEngagementScore(url); + EXPECT_EQ(score->visits(), expected_visits); + EXPECT_EQ(score->media_playbacks(), expected_media_playbacks); + delete score; + } + + void Navigate(GURL url) { + std::unique_ptr<content::NavigationHandle> test_handle = + content::NavigationHandle::CreateNavigationHandleForTesting( + GURL(url), main_rfh(), true /** committed */); + contents_observer_->DidFinishNavigation(test_handle.get()); + contents_observer_->committed_origin_ = url::Origin(url); + } + private: // contents_observer_ auto-destroys when WebContents is destroyed. MediaEngagementContentsObserver* contents_observer_; @@ -242,6 +264,17 @@ EXPECT_TRUE(WasSignificantPlaybackRecorded()); } +TEST_F(MediaEngagementContentsObserverTest, InteractionsRecorded) { + GURL url("https://www.example.com"); + ExpectScores(url, 0.0, 0, 0); + + Navigate(url); + ExpectScores(url, 0.0, 1, 0); + + SimulateSignificantPlaybackTime(); + ExpectScores(url, 0.0, 1, 1); +} + TEST_F(MediaEngagementContentsObserverTest, DoNotRecordAudiolessTrack) { EXPECT_EQ(0u, GetSignificantActivePlayersCount());
diff --git a/chrome/browser/media/media_engagement_score.cc b/chrome/browser/media/media_engagement_score.cc index 318a1e6..e26bbade 100644 --- a/chrome/browser/media/media_engagement_score.cc +++ b/chrome/browser/media/media_engagement_score.cc
@@ -64,7 +64,7 @@ MediaEngagementScore::~MediaEngagementScore() = default; double MediaEngagementScore::GetTotalScore() const { - if (visits_ < kScoreMinVisits) + if (visits() < kScoreMinVisits) return 0; return static_cast<double>(media_playbacks_) / static_cast<double>(visits_); }
diff --git a/chrome/browser/media/media_engagement_score.h b/chrome/browser/media/media_engagement_score.h index 5190559..a45c2cbf 100644 --- a/chrome/browser/media/media_engagement_score.h +++ b/chrome/browser/media/media_engagement_score.h
@@ -55,7 +55,13 @@ return last_media_playback_time_; } + void SetVisits(int visits) { visits_ = visits; } + void SetMediaPlaybacks(int media_playbacks) { + media_playbacks_ = media_playbacks; + } + private: + friend class MediaEngagementServiceTest; friend class MediaEngagementScoreTest; // Used for tests.
diff --git a/chrome/browser/media/media_engagement_service.cc b/chrome/browser/media/media_engagement_service.cc index 1c4de26e..0990493d 100644 --- a/chrome/browser/media/media_engagement_service.cc +++ b/chrome/browser/media/media_engagement_service.cc
@@ -4,12 +4,63 @@ #include "chrome/browser/media/media_engagement_service.h" +#include "base/time/clock.h" +#include "base/time/default_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/media/media_engagement_contents_observer.h" +#include "chrome/browser/media/media_engagement_score.h" #include "chrome/browser/media/media_engagement_service_factory.h" #include "chrome/browser/profiles/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 "content/public/browser/web_contents.h" #include "media/base/media_switches.h" +namespace { + +// Returns the combined list of origins which have media engagement data. +std::set<GURL> GetEngagementOriginsFromContentSettings(Profile* profile) { + ContentSettingsForOneType content_settings; + std::set<GURL> urls; + + HostContentSettingsMapFactory::GetForProfile(profile)->GetSettingsForOneType( + CONTENT_SETTINGS_TYPE_MEDIA_ENGAGEMENT, + content_settings::ResourceIdentifier(), &content_settings); + + for (const auto& site : content_settings) + urls.insert(GURL(site.primary_pattern.ToString())); + + return urls; +} + +bool MediaEngagementFilterAdapter( + const GURL& predicate, + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern) { + GURL url(primary_pattern.ToString()); + DCHECK(url.is_valid()); + return predicate == url; +} + +bool MediaEngagementTimeFilterAdapter( + MediaEngagementService* service, + base::Time delete_begin, + base::Time delete_end, + const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern) { + GURL url(primary_pattern.ToString()); + DCHECK(url.is_valid()); + MediaEngagementScore* score = service->CreateEngagementScore(url); + base::Time playback_time = score->last_media_playback_time(); + delete score; + return playback_time >= delete_begin && playback_time <= delete_end; +} + +} // namespace + // static bool MediaEngagementService::IsEnabled() { return base::FeatureList::IsEnabled(media::kMediaEngagement); @@ -33,8 +84,132 @@ new MediaEngagementContentsObserver(web_contents, service)); } -MediaEngagementService::MediaEngagementService(Profile* profile) { +MediaEngagementService::MediaEngagementService(Profile* profile) + : MediaEngagementService(profile, base::MakeUnique<base::DefaultClock>()) {} + +MediaEngagementService::MediaEngagementService( + Profile* profile, + std::unique_ptr<base::Clock> clock) + : profile_(profile), clock_(std::move(clock)) { DCHECK(IsEnabled()); + + // May be null in tests. + history::HistoryService* history = HistoryServiceFactory::GetForProfile( + profile, ServiceAccessType::IMPLICIT_ACCESS); + if (history) + history->AddObserver(this); } MediaEngagementService::~MediaEngagementService() = default; + +void MediaEngagementService::ClearDataBetweenTime( + const base::Time& delete_begin, + const base::Time& delete_end) { + HostContentSettingsMapFactory::GetForProfile(profile_) + ->ClearSettingsForOneTypeWithPredicate( + CONTENT_SETTINGS_TYPE_MEDIA_ENGAGEMENT, base::Time(), + base::Bind(&MediaEngagementTimeFilterAdapter, this, delete_begin, + delete_end)); +} + +void MediaEngagementService::Shutdown() { + history::HistoryService* history = HistoryServiceFactory::GetForProfile( + profile_, ServiceAccessType::IMPLICIT_ACCESS); + if (history) + history->RemoveObserver(this); +} + +void MediaEngagementService::OnURLsDeleted( + history::HistoryService* history_service, + bool all_history, + bool expired, + const history::URLRows& deleted_rows, + const std::set<GURL>& favicon_urls) { + std::map<GURL, int> origins; + for (const history::URLRow& row : deleted_rows) { + GURL origin = row.url().GetOrigin(); + if (origins.find(origin) == origins.end()) { + origins[origin] = 0; + } + origins[origin]++; + } + + for (auto const& kv : origins) { + // Remove the number of visits consistent with the number + // of URLs from the same origin we are removing. + MediaEngagementScore* score = CreateEngagementScore(kv.first); + double original_score = score->GetTotalScore(); + score->SetVisits(score->visits() - kv.second); + + // If this results in zero visits then clear the score. + if (score->visits() <= 0) { + Clear(kv.first); + delete score; + continue; + } + + // Otherwise, recalculate the playbacks to keep the + // MEI score consistent. + score->SetMediaPlaybacks(original_score * score->visits()); + score->Commit(); + delete score; + } +} + +void MediaEngagementService::Clear(const GURL& url) { + HostContentSettingsMapFactory::GetForProfile(profile_) + ->ClearSettingsForOneTypeWithPredicate( + CONTENT_SETTINGS_TYPE_MEDIA_ENGAGEMENT, base::Time(), + base::Bind(&MediaEngagementFilterAdapter, base::ConstRef(url))); +} + +double MediaEngagementService::GetEngagementScore(const GURL& url) const { + MediaEngagementScore* score = CreateEngagementScore(url); + double total_score = score->GetTotalScore(); + delete score; + return total_score; +} + +std::map<GURL, double> MediaEngagementService::GetScoreMapForTesting() const { + std::map<GURL, double> score_map; + for (const GURL& url : GetEngagementOriginsFromContentSettings(profile_)) { + if (!url.is_valid()) + continue; + score_map[url] = GetEngagementScore(url); + } + return score_map; +} + +void MediaEngagementService::RecordVisit(const GURL& url) { + if (!ShouldRecordEngagement(url)) + return; + + MediaEngagementScore* score = CreateEngagementScore(url); + score->IncrementVisits(); + score->Commit(); + delete score; +} + +void MediaEngagementService::RecordPlayback(const GURL& url) { + if (!ShouldRecordEngagement(url)) + return; + + MediaEngagementScore* score = CreateEngagementScore(url); + score->IncrementMediaPlaybacks(); + score->Commit(); + delete score; +} + +MediaEngagementScore* MediaEngagementService::CreateEngagementScore( + const GURL& url) const { + // If we are in incognito, |settings| will automatically have the data from + // the original profile migrated in, so all engagement scores in incognito + // will be initialised to the values from the original profile. + return new MediaEngagementScore( + clock_.get(), url, + HostContentSettingsMapFactory::GetForProfile(profile_)); +} + +bool MediaEngagementService::ShouldRecordEngagement(const GURL& url) const { + return url.SchemeIsHTTPOrHTTPS(); +}
diff --git a/chrome/browser/media/media_engagement_service.h b/chrome/browser/media/media_engagement_service.h index 7f4d228a..0f1ebd59 100644 --- a/chrome/browser/media/media_engagement_service.h +++ b/chrome/browser/media/media_engagement_service.h
@@ -5,19 +5,34 @@ #ifndef CHROME_BROWSER_MEDIA_MEDIA_ENGAGEMENT_SERVICE_H_ #define CHROME_BROWSER_MEDIA_MEDIA_ENGAGEMENT_SERVICE_H_ +#include <map> #include <set> #include "base/macros.h" +#include "base/values.h" +#include "chrome/browser/media/media_engagement_score.h" +#include "components/history/core/browser/history_service_observer.h" #include "components/keyed_service/core/keyed_service.h" +class GURL; class MediaEngagementContentsObserver; +class MediaEngagementScore; class Profile; +namespace base { +class Clock; +} + namespace content { class WebContents; } // namespace content -class MediaEngagementService : public KeyedService { +namespace history { +class HistoryService; +} + +class MediaEngagementService : public KeyedService, + public history::HistoryServiceObserver { public: // Returns the instance attached to the given |profile|. static MediaEngagementService* Get(Profile* profile); @@ -32,11 +47,56 @@ explicit MediaEngagementService(Profile* profile); ~MediaEngagementService() override; + // Returns the engagement score of |url|. + double GetEngagementScore(const GURL& url) const; + + // Returns a map of all stored origins and their engagement levels. + std::map<GURL, double> GetScoreMapForTesting() const; + + // Record a visit of a |url|. + void RecordVisit(const GURL& url); + + // Record a media playback on a |url|. + void RecordPlayback(const GURL& url); + + // Overridden from 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; + + // KeyedService support: + void Shutdown() override; + + // Clear data if the last playback time is between these two time points. + void ClearDataBetweenTime(const base::Time& delete_begin, + const base::Time& delete_end); + + // Retrieves the MediaEngagementScore for |url|. + MediaEngagementScore* CreateEngagementScore(const GURL& url) const; + private: + friend class MediaEngagementServiceTest; + friend class MediaEngagementContentsObserverTest; friend MediaEngagementContentsObserver; + MediaEngagementService(Profile* profile, std::unique_ptr<base::Clock> clock); + + // Returns true if we should record engagement for this url. Currently, + // engagement is only earned for HTTP and HTTPS. + bool ShouldRecordEngagement(const GURL& url) const; + std::set<MediaEngagementContentsObserver*> contents_observers_; + Profile* profile_; + + // Clear any data for a specific origin. + void Clear(const GURL& url); + + // An internal clock for testing. + std::unique_ptr<base::Clock> clock_; + DISALLOW_COPY_AND_ASSIGN(MediaEngagementService); };
diff --git a/chrome/browser/media/media_engagement_service_factory.cc b/chrome/browser/media/media_engagement_service_factory.cc index 8bab790..adb07e47 100644 --- a/chrome/browser/media/media_engagement_service_factory.cc +++ b/chrome/browser/media/media_engagement_service_factory.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/media/media_engagement_service_factory.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/media/media_engagement_service.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" @@ -24,7 +26,10 @@ MediaEngagementServiceFactory::MediaEngagementServiceFactory() : BrowserContextKeyedServiceFactory( "MediaEngagementServiceFactory", - BrowserContextDependencyManager::GetInstance()) {} + BrowserContextDependencyManager::GetInstance()) { + DependsOn(HistoryServiceFactory::GetInstance()); + DependsOn(HostContentSettingsMapFactory::GetInstance()); +} MediaEngagementServiceFactory::~MediaEngagementServiceFactory() {}
diff --git a/chrome/browser/media/media_engagement_service_unittest.cc b/chrome/browser/media/media_engagement_service_unittest.cc new file mode 100644 index 0000000..4dbe9f53 --- /dev/null +++ b/chrome/browser/media/media_engagement_service_unittest.cc
@@ -0,0 +1,452 @@ +// 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/media/media_engagement_service.h" + +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/run_loop.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/simple_test_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/media/media_engagement_score.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/content_settings_observer.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_types.h" +#include "components/history/core/browser/history_database_params.h" +#include "components/history/core/browser/history_service.h" +#include "components/history/core/test/test_history_database.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/page_navigator.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/web_contents_tester.h" +#include "media/base/media_switches.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +base::FilePath g_temp_history_dir; + +// Waits until a change is observed in media engagement content settings. +class MediaEngagementChangeWaiter : public content_settings::Observer { + public: + explicit MediaEngagementChangeWaiter(Profile* profile) : profile_(profile) { + HostContentSettingsMapFactory::GetForProfile(profile)->AddObserver(this); + } + + ~MediaEngagementChangeWaiter() override { + HostContentSettingsMapFactory::GetForProfile(profile_)->RemoveObserver( + this); + } + + // Overridden from content_settings::Observer: + void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, + const ContentSettingsPattern& secondary_pattern, + ContentSettingsType content_type, + std::string resource_identifier) override { + if (content_type == CONTENT_SETTINGS_TYPE_MEDIA_ENGAGEMENT) + Proceed(); + } + + void Wait() { run_loop_.Run(); } + + private: + void Proceed() { run_loop_.Quit(); } + + Profile* profile_; + base::RunLoop run_loop_; + + DISALLOW_COPY_AND_ASSIGN(MediaEngagementChangeWaiter); +}; + +base::Time GetReferenceTime() { + base::Time::Exploded exploded_reference_time; + exploded_reference_time.year = 2015; + exploded_reference_time.month = 1; + exploded_reference_time.day_of_month = 30; + exploded_reference_time.day_of_week = 5; + exploded_reference_time.hour = 11; + exploded_reference_time.minute = 0; + exploded_reference_time.second = 0; + exploded_reference_time.millisecond = 0; + + base::Time out_time; + EXPECT_TRUE( + base::Time::FromLocalExploded(exploded_reference_time, &out_time)); + return out_time; +} + +std::unique_ptr<KeyedService> BuildTestHistoryService( + content::BrowserContext* context) { + std::unique_ptr<history::HistoryService> service( + new history::HistoryService()); + service->Init(history::TestHistoryDatabaseParamsForPath(g_temp_history_dir)); + return std::move(service); +} + +} // namespace + +class MediaEngagementServiceTest : public ChromeRenderViewHostTestHarness { + public: + void SetUp() override { + scoped_feature_list_.InitAndEnableFeature(media::kMediaEngagement); + ChromeRenderViewHostTestHarness::SetUp(); + + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + g_temp_history_dir = temp_dir_.GetPath(); + HistoryServiceFactory::GetInstance()->SetTestingFactory( + profile(), &BuildTestHistoryService); + + test_clock_ = new base::SimpleTestClock(); + test_clock_->SetNow(GetReferenceTime()); + service_ = base::WrapUnique( + new MediaEngagementService(profile(), base::WrapUnique(test_clock_))); + } + + void RecordVisitAndPlaybackAndAdvanceClock(GURL url) { + RecordVisit(url); + AdvanceClock(); + RecordPlayback(url); + } + + void TearDown() override { + service_->Shutdown(); + service_.reset(); + ChromeRenderViewHostTestHarness::TearDown(); + } + + void AdvanceClock() { + test_clock_->SetNow(Now() + base::TimeDelta::FromHours(1)); + } + + void RecordVisit(GURL url) { service_->RecordVisit(url); } + + void RecordPlayback(GURL url) { service_->RecordPlayback(url); } + + void ExpectScores(MediaEngagementService* service, + GURL url, + double expected_score, + int expected_visits, + int expected_media_playbacks, + base::Time expected_last_media_playback_time) { + EXPECT_EQ(service->GetEngagementScore(url), expected_score); + EXPECT_EQ(service->GetScoreMapForTesting()[url], expected_score); + + MediaEngagementScore* score = service->CreateEngagementScore(url); + EXPECT_EQ(score->visits(), expected_visits); + EXPECT_EQ(score->media_playbacks(), expected_media_playbacks); + EXPECT_EQ(score->last_media_playback_time(), + expected_last_media_playback_time); + delete score; + } + + void ExpectScores(GURL url, + double expected_score, + int expected_visits, + int expected_media_playbacks, + base::Time expected_last_media_playback_time) { + ExpectScores(service_.get(), url, expected_score, expected_visits, + expected_media_playbacks, expected_last_media_playback_time); + } + + void SetScores(GURL url, int visits, int media_playbacks) { + MediaEngagementScore* score = service_->CreateEngagementScore(url); + score->SetVisits(visits); + score->SetMediaPlaybacks(media_playbacks); + score->Commit(); + delete score; + } + + void SetLastMediaPlaybackTime(const GURL& url, + base::Time last_media_playback_time) { + MediaEngagementScore* score = service_->CreateEngagementScore(url); + score->last_media_playback_time_ = last_media_playback_time; + score->Commit(); + delete score; + } + + double GetTotalScore(GURL url) { + MediaEngagementScore* score = service_->CreateEngagementScore(url); + double total_score = score->GetTotalScore(); + delete score; + return total_score; + } + + std::map<GURL, double> GetScoreMapForTesting() const { + return service_->GetScoreMapForTesting(); + } + + void ClearDataBetweenTime(base::Time begin, base::Time end) { + service_->ClearDataBetweenTime(begin, end); + } + + base::Time Now() const { return test_clock_->Now(); } + + base::Time TimeNotSet() const { return base::Time(); } + + void SetNow(base::Time now) { test_clock_->SetNow(now); } + + private: + base::SimpleTestClock* test_clock_ = nullptr; + + std::unique_ptr<MediaEngagementService> service_; + + base::ScopedTempDir temp_dir_; + + base::test::ScopedFeatureList scoped_feature_list_; +}; + +TEST_F(MediaEngagementServiceTest, RestrictedToHTTPAndHTTPS) { + GURL url1("ftp://www.google.com/"); + GURL url2("file://blah"); + GURL url3("chrome://"); + GURL url4("about://config"); + + RecordVisitAndPlaybackAndAdvanceClock(url1); + ExpectScores(url1, 0.0, 0, 0, TimeNotSet()); + + RecordVisitAndPlaybackAndAdvanceClock(url2); + ExpectScores(url2, 0.0, 0, 0, TimeNotSet()); + + RecordVisitAndPlaybackAndAdvanceClock(url3); + ExpectScores(url3, 0.0, 0, 0, TimeNotSet()); + + RecordVisitAndPlaybackAndAdvanceClock(url4); + ExpectScores(url4, 0.0, 0, 0, TimeNotSet()); +} + +TEST_F(MediaEngagementServiceTest, + HandleRecordVisitAndPlaybackAndAdvanceClockion) { + GURL url1("https://www.google.com"); + ExpectScores(url1, 0.0, 0, 0, TimeNotSet()); + RecordVisitAndPlaybackAndAdvanceClock(url1); + ExpectScores(url1, 0.0, 1, 1, Now()); + + RecordVisit(url1); + ExpectScores(url1, 0.0, 2, 1, Now()); + + RecordPlayback(url1); + ExpectScores(url1, 0.0, 2, 2, Now()); + base::Time url1_time = Now(); + + GURL url2("https://www.google.co.uk"); + RecordVisitAndPlaybackAndAdvanceClock(url2); + ExpectScores(url2, 0.0, 1, 1, Now()); + ExpectScores(url1, 0.0, 2, 2, url1_time); +} + +TEST_F(MediaEngagementServiceTest, IncognitoEngagementService) { + GURL url1("http://www.google.com/"); + GURL url2("https://www.google.com/"); + GURL url3("https://drive.google.com/"); + GURL url4("https://maps.google.com/"); + + RecordVisitAndPlaybackAndAdvanceClock(url1); + base::Time url1_time = Now(); + RecordVisitAndPlaybackAndAdvanceClock(url2); + + MediaEngagementService* incognito_service = + MediaEngagementService::Get(profile()->GetOffTheRecordProfile()); + ExpectScores(incognito_service, url1, 0.0, 1, 1, url1_time); + ExpectScores(incognito_service, url2, 0.0, 1, 1, Now()); + ExpectScores(incognito_service, url3, 0.0, 0, 0, TimeNotSet()); + + incognito_service->RecordVisit(url3); + ExpectScores(incognito_service, url3, 0.0, 1, 0, TimeNotSet()); + ExpectScores(url3, 0.0, 0, 0, TimeNotSet()); + + incognito_service->RecordVisit(url2); + ExpectScores(incognito_service, url2, 0.0, 2, 1, Now()); + ExpectScores(url2, 0.0, 1, 1, Now()); + + RecordVisitAndPlaybackAndAdvanceClock(url3); + ExpectScores(incognito_service, url3, 0.0, 1, 0, TimeNotSet()); + ExpectScores(url3, 0.0, 1, 1, Now()); + + ExpectScores(incognito_service, url4, 0.0, 0, 0, TimeNotSet()); + RecordVisitAndPlaybackAndAdvanceClock(url4); + ExpectScores(incognito_service, url4, 0.0, 1, 1, Now()); + ExpectScores(url4, 0.0, 1, 1, Now()); +} + +TEST_F(MediaEngagementServiceTest, CleanupOriginsOnHistoryDeletion) { + GURL origin1("http://www.google.com/"); + GURL origin1a("http://www.google.com/search?q=asdf"); + GURL origin1b("http://www.google.com/maps/search?q=asdf"); + GURL origin2("https://drive.google.com/"); + GURL origin3("http://deleted.com/"); + GURL origin3a("http://deleted.com/test"); + GURL origin4("http://notdeleted.com"); + + // origin1 will have a score that is high enough to not return zero + // and we will ensure it has the same score. origin2 will have a score + // that is zero and will remain zero. origin3 will have a score + // and will be cleared. origin4 will have a normal score. + SetScores(origin1, MediaEngagementScore::kScoreMinVisits + 3, 2); + SetScores(origin2, 2, 1); + SetScores(origin3, 2, 1); + SetScores(origin4, MediaEngagementScore::kScoreMinVisits, 2); + + base::Time today = GetReferenceTime(); + base::Time yesterday = GetReferenceTime() - base::TimeDelta::FromDays(1); + base::Time yesterday_afternoon = GetReferenceTime() - + base::TimeDelta::FromDays(1) + + base::TimeDelta::FromHours(4); + base::Time yesterday_week = GetReferenceTime() - base::TimeDelta::FromDays(8); + SetNow(today); + + history::HistoryService* history = HistoryServiceFactory::GetForProfile( + profile(), ServiceAccessType::IMPLICIT_ACCESS); + + history->AddPage(origin1, yesterday_afternoon, history::SOURCE_BROWSED); + history->AddPage(origin1a, yesterday_afternoon, history::SOURCE_BROWSED); + history->AddPage(origin1b, yesterday_week, history::SOURCE_BROWSED); + history->AddPage(origin2, yesterday_afternoon, history::SOURCE_BROWSED); + history->AddPage(origin3, yesterday_week, history::SOURCE_BROWSED); + history->AddPage(origin3a, yesterday_afternoon, history::SOURCE_BROWSED); + + // Check that the scores are valid at the beginning. + ExpectScores(origin1, 0.25, MediaEngagementScore::kScoreMinVisits + 3, 2, + TimeNotSet()); + EXPECT_TRUE(GetTotalScore(origin1)); + ExpectScores(origin2, 0.0, 2, 1, TimeNotSet()); + EXPECT_FALSE(GetTotalScore(origin2)); + ExpectScores(origin3, 0.0, 2, 1, TimeNotSet()); + EXPECT_FALSE(GetTotalScore(origin3)); + ExpectScores(origin4, 0.4, MediaEngagementScore::kScoreMinVisits, 2, + TimeNotSet()); + EXPECT_TRUE(GetTotalScore(origin4)); + + { + MediaEngagementChangeWaiter waiter(profile()); + + base::CancelableTaskTracker task_tracker; + // Expire origin1, origin1a, origin2, and origin3a's most recent visit. + history->ExpireHistoryBetween(std::set<GURL>(), yesterday, today, + base::Bind(&base::DoNothing), &task_tracker); + waiter.Wait(); + + // origin1 should have a score that is not zero and is the same as the old + // score (sometimes it may not match exactly due to rounding). origin2 + // should have a score that is zero but it's visits and playbacks should + // have decreased. origin3 should have had a decrease in the number of + // visits. origin4 should have the old score. + ExpectScores(origin1, 1.0 / 6.0, MediaEngagementScore::kScoreMinVisits + 1, + 1, TimeNotSet()); + EXPECT_TRUE(GetTotalScore(origin1)); + ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); + EXPECT_FALSE(GetTotalScore(origin2)); + ExpectScores(origin3, 0.0, 1, 0, TimeNotSet()); + ExpectScores(origin4, 0.4, MediaEngagementScore::kScoreMinVisits, 2, + TimeNotSet()); + } + + { + MediaEngagementChangeWaiter waiter(profile()); + + // Expire origin1b. + std::vector<history::ExpireHistoryArgs> expire_list; + history::ExpireHistoryArgs args; + args.urls.insert(origin1b); + args.SetTimeRangeForOneDay(yesterday_week); + expire_list.push_back(args); + + base::CancelableTaskTracker task_tracker; + history->ExpireHistory(expire_list, base::Bind(&base::DoNothing), + &task_tracker); + waiter.Wait(); + + // origin1's score should have changed but the rest should remain the same. + ExpectScores(origin1, 0.0, MediaEngagementScore::kScoreMinVisits, 0, + TimeNotSet()); + ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); + ExpectScores(origin3, 0.0, 1, 0, TimeNotSet()); + ExpectScores(origin4, 0.4, MediaEngagementScore::kScoreMinVisits, 2, + TimeNotSet()); + } + + { + MediaEngagementChangeWaiter waiter(profile()); + + // Expire origin3. + std::vector<history::ExpireHistoryArgs> expire_list; + history::ExpireHistoryArgs args; + args.urls.insert(origin3); + args.SetTimeRangeForOneDay(yesterday_week); + expire_list.push_back(args); + + base::CancelableTaskTracker task_tracker; + history->ExpireHistory(expire_list, base::Bind(&base::DoNothing), + &task_tracker); + waiter.Wait(); + + // origin3's score should be removed but the rest should remain the same. + std::map<GURL, double> scores = GetScoreMapForTesting(); + EXPECT_TRUE(scores.find(origin3) == scores.end()); + ExpectScores(origin1, 0.0, MediaEngagementScore::kScoreMinVisits, 0, + TimeNotSet()); + ExpectScores(origin2, 0.0, 1, 0, TimeNotSet()); + ExpectScores(origin3, 0.0, 0, 0, TimeNotSet()); + ExpectScores(origin4, 0.4, MediaEngagementScore::kScoreMinVisits, 2, + TimeNotSet()); + } +} + +TEST_F(MediaEngagementServiceTest, + CleanupDataOnSiteDataCleanup_OutsideBoundary) { + GURL origin("https://www.google.com"); + + base::Time today = GetReferenceTime(); + SetNow(today); + + SetScores(origin, 1, 1); + SetLastMediaPlaybackTime(origin, today); + + ClearDataBetweenTime(today - base::TimeDelta::FromDays(2), + today - base::TimeDelta::FromDays(1)); + ExpectScores(origin, 0.0, 1, 1, today); +} + +TEST_F(MediaEngagementServiceTest, + CleanupDataOnSiteDataCleanup_WithinBoundary) { + GURL origin1("https://www.google.com"); + GURL origin2("https://www.google.co.uk"); + + base::Time today = GetReferenceTime(); + base::Time yesterday = today - base::TimeDelta::FromDays(1); + base::Time two_days_ago = today - base::TimeDelta::FromDays(2); + SetNow(today); + + SetScores(origin1, 1, 1); + SetScores(origin2, 1, 1); + SetLastMediaPlaybackTime(origin1, yesterday); + SetLastMediaPlaybackTime(origin2, two_days_ago); + + ClearDataBetweenTime(two_days_ago, yesterday); + ExpectScores(origin1, 0.0, 0, 0, TimeNotSet()); + ExpectScores(origin2, 0.0, 0, 0, TimeNotSet()); +} + +TEST_F(MediaEngagementServiceTest, CleanupDataOnSiteDataCleanup_NoTimeSet) { + GURL origin("https://www.google.com"); + + base::Time today = GetReferenceTime(); + + SetNow(GetReferenceTime()); + SetScores(origin, 1, 0); + + ClearDataBetweenTime(today - base::TimeDelta::FromDays(2), + today - base::TimeDelta::FromDays(1)); + ExpectScores(origin, 0.0, 1, 0, TimeNotSet()); +}
diff --git a/chrome/browser/media/webrtc/media_stream_device_permission_context.cc b/chrome/browser/media/webrtc/media_stream_device_permission_context.cc index 7a8813f03..0450d8b 100644 --- a/chrome/browser/media/webrtc/media_stream_device_permission_context.cc +++ b/chrome/browser/media/webrtc/media_stream_device_permission_context.cc
@@ -100,12 +100,6 @@ NOTREACHED() << "ResetPermission is not implemented"; } -void MediaStreamDevicePermissionContext::CancelPermissionRequest( - content::WebContents* web_contents, - const PermissionRequestID& id) { - NOTREACHED() << "CancelPermissionRequest is not implemented"; -} - bool MediaStreamDevicePermissionContext::IsRestrictedToSecureOrigins() const { return base::FeatureList::IsEnabled( features::kRequireSecureOriginsForPepperMediaRequests);
diff --git a/chrome/browser/media/webrtc/media_stream_device_permission_context.h b/chrome/browser/media/webrtc/media_stream_device_permission_context.h index a3bf754..8c607f1 100644 --- a/chrome/browser/media/webrtc/media_stream_device_permission_context.h +++ b/chrome/browser/media/webrtc/media_stream_device_permission_context.h
@@ -34,9 +34,6 @@ void ResetPermission(const GURL& requesting_origin, const GURL& embedding_origin) override; - void CancelPermissionRequest(content::WebContents* web_contents, - const PermissionRequestID& id) override; - private: // PermissionContextBase: bool IsRestrictedToSecureOrigins() const override;
diff --git a/chrome/browser/metrics/metrics_reporting_state.cc b/chrome/browser/metrics/metrics_reporting_state.cc index 25dbee4..183a1e7 100644 --- a/chrome/browser/metrics/metrics_reporting_state.cc +++ b/chrome/browser/metrics/metrics_reporting_state.cc
@@ -6,6 +6,7 @@ #include "base/callback.h" #include "base/metrics/histogram_macros.h" +#include "base/task_runner_util.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" @@ -95,10 +96,8 @@ return; } #endif - // Posts to FILE thread as SetGoogleUpdateSettings does IO operations. - content::BrowserThread::PostTaskAndReplyWithResult( - content::BrowserThread::FILE, - FROM_HERE, + base::PostTaskAndReplyWithResult( + GoogleUpdateSettings::CollectStatsConsentTaskRunner(), FROM_HERE, base::Bind(&SetGoogleUpdateSettings, enabled), base::Bind(&SetMetricsReporting, enabled, callback_fn)); }
diff --git a/chrome/browser/metrics/ukm_browsertest.cc b/chrome/browser/metrics/ukm_browsertest.cc index fcb79221..ad13861 100644 --- a/chrome/browser/metrics/ukm_browsertest.cc +++ b/chrome/browser/metrics/ukm_browsertest.cc
@@ -12,9 +12,9 @@ #include "components/browser_sync/profile_sync_service.h" #include "components/metrics_services_manager/metrics_services_manager.h" #include "components/sync/test/fake_server/fake_server_network_resources.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/ukm/ukm_service.h" #include "content/public/common/content_switches.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace metrics {
diff --git a/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc b/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc index e16338c..76c3cf59 100644 --- a/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc +++ b/chrome/browser/offline_pages/prefetch/prefetch_service_factory.cc
@@ -7,13 +7,17 @@ #include <memory> #include <utility> +#include "base/files/file_path.h" #include "base/memory/ptr_util.h" #include "base/memory/singleton.h" +#include "base/sequenced_task_runner.h" +#include "base/task_scheduler/post_task.h" #include "chrome/browser/download/download_service_factory.h" #include "chrome/browser/offline_pages/prefetch/offline_metrics_collector_impl.h" #include "chrome/browser/offline_pages/prefetch/prefetch_instance_id_proxy.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/channel_info.h" +#include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_content_client.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/offline_pages/core/prefetch/prefetch_dispatcher_impl.h" @@ -21,6 +25,7 @@ #include "components/offline_pages/core/prefetch/prefetch_gcm_app_handler.h" #include "components/offline_pages/core/prefetch/prefetch_network_request_factory_impl.h" #include "components/offline_pages/core/prefetch/prefetch_service_impl.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" #include "components/offline_pages/core/prefetch/suggested_articles_observer.h" #include "content/public/browser/browser_context.h" @@ -49,15 +54,27 @@ content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); DCHECK(profile); + + auto offline_metrics_collector = + base::MakeUnique<OfflineMetricsCollectorImpl>(profile->GetPrefs()); + auto prefetch_dispatcher = base::MakeUnique<PrefetchDispatcherImpl>(); + auto prefetch_gcm_app_handler = base::MakeUnique<PrefetchGCMAppHandler>( base::MakeUnique<PrefetchInstanceIDProxy>(kPrefetchingOfflinePagesAppId, context)); + auto prefetch_network_request_factory = base::MakeUnique<PrefetchNetworkRequestFactoryImpl>( profile->GetRequestContext(), chrome::GetChannel(), GetUserAgent()); - auto offline_metrics_collector = - base::MakeUnique<OfflineMetricsCollectorImpl>(profile->GetPrefs()); + + scoped_refptr<base::SequencedTaskRunner> background_task_runner = + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::FilePath store_path = + profile->GetPath().Append(chrome::kOfflinePagePrefetchStoreDirname); + auto prefetch_store = + base::MakeUnique<PrefetchStore>(background_task_runner, store_path); + auto suggested_articles_observer = base::MakeUnique<SuggestedArticlesObserver>(); @@ -68,7 +85,7 @@ return new PrefetchServiceImpl( std::move(offline_metrics_collector), std::move(prefetch_dispatcher), std::move(prefetch_gcm_app_handler), - std::move(prefetch_network_request_factory), + std::move(prefetch_network_request_factory), std::move(prefetch_store), std::move(suggested_articles_observer), std::move(prefetch_downloader)); }
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc index 1497e9d1..346d383 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc
@@ -8,9 +8,9 @@ #include "chrome/browser/net/nqe/ui_network_quality_estimator_service_factory.h" #include "chrome/browser/page_load_metrics/page_load_metrics_util.h" #include "chrome/browser/profiles/profile.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/public/browser/web_contents.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace internal {
diff --git a/chrome/browser/page_load_metrics/page_load_tracker.cc b/chrome/browser/page_load_metrics/page_load_tracker.cc index 6847eeb..da13644 100644 --- a/chrome/browser/page_load_metrics/page_load_tracker.cc +++ b/chrome/browser/page_load_metrics/page_load_tracker.cc
@@ -17,12 +17,12 @@ #include "chrome/browser/page_load_metrics/page_load_metrics_util.h" #include "chrome/browser/prerender/prerender_contents.h" #include "chrome/common/page_load_metrics/page_load_timing.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "ui/base/page_transition_types.h" // This macro invokes the specified method on each observer, passing the
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.cc b/chrome/browser/password_manager/chrome_password_manager_client.cc index 8723dfc..c3446297 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client.cc
@@ -52,7 +52,6 @@ #include "components/prefs/pref_service.h" #include "components/sessions/content/content_record_password_state.h" #include "components/signin/core/browser/signin_manager.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" @@ -66,6 +65,7 @@ #include "extensions/features/features.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/url_util.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/re2/src/re2/re2.h" #if defined(SAFE_BROWSING_DB_LOCAL) @@ -387,6 +387,7 @@ // If a site stores a credential the autofill password manager shouldn't kick // in. password_manager_.DropFormManagers(); + was_store_ever_called_ = true; } void ChromePasswordManagerClient::AutomaticPasswordSave( @@ -478,8 +479,6 @@ return metrics_recorder_.value(); } -// TODO(crbug.com/706392): Fix password reuse detection for Android. -#if !defined(OS_ANDROID) void ChromePasswordManagerClient::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame() || !navigation_handle->HasCommitted()) @@ -491,6 +490,14 @@ metrics_recorder_.reset(); } + // From this point on, the CredentialManagerImpl will service API calls in the + // context of the new WebContents::GetLastCommittedURL, which may very well be + // cross-origin. Disconnect existing client, and drop pending requests. + if (!navigation_handle->IsSameDocument()) + credential_manager_impl_.DisconnectBinding(); + +// TODO(crbug.com/706392): Fix password reuse detection for Android. +#if !defined(OS_ANDROID) password_reuse_detection_manager_.DidNavigateMainFrame(GetMainFrameURL()); // After some navigations RenderViewHost persists and just adding the observer // will cause multiple call of OnInputEvent. Since Widget API doesn't allow to @@ -499,8 +506,10 @@ web_contents()->GetRenderViewHost()->GetWidget()->RemoveInputEventObserver( this); web_contents()->GetRenderViewHost()->GetWidget()->AddInputEventObserver(this); +#endif } +#if !defined(OS_ANDROID) void ChromePasswordManagerClient::OnInputEvent( const blink::WebInputEvent& event) { if (event.GetType() != blink::WebInputEvent::kChar) @@ -741,8 +750,7 @@ // static void ChromePasswordManagerClient::BindCredentialManager( - const service_manager::BindSourceInfo& source_info, - password_manager::mojom::CredentialManagerRequest request, + password_manager::mojom::CredentialManagerAssociatedRequest request, content::RenderFrameHost* render_frame_host) { // Only valid for the main frame. if (render_frame_host->GetParent()) @@ -752,6 +760,11 @@ content::WebContents::FromRenderFrameHost(render_frame_host); DCHECK(web_contents); + // Only valid for the currently committed RenderFrameHost, and not, e.g. old + // zombie RFH's being swapped out following cross-origin navigations. + if (web_contents->GetMainFrame() != render_frame_host) + return; + ChromePasswordManagerClient* instance = ChromePasswordManagerClient::FromWebContents(web_contents);
diff --git a/chrome/browser/password_manager/chrome_password_manager_client.h b/chrome/browser/password_manager/chrome_password_manager_client.h index 2af35807..a589af69 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client.h +++ b/chrome/browser/password_manager/chrome_password_manager_client.h
@@ -11,6 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/optional.h" +#include "build/build_config.h" #include "components/autofill/content/common/autofill_driver.mojom.h" #include "components/password_manager/content/browser/content_password_manager_driver_factory.h" #include "components/password_manager/content/browser/credential_manager_impl.h" @@ -130,14 +131,20 @@ void SetTestObserver(autofill::PasswordGenerationPopupObserver* observer); static void BindCredentialManager( - const service_manager::BindSourceInfo& source_info, - password_manager::mojom::CredentialManagerRequest request, + password_manager::mojom::CredentialManagerAssociatedRequest request, content::RenderFrameHost* render_frame_host); // A helper method to determine whether a save/update bubble can be shown // on this |url|. static bool CanShowBubbleOnURL(const GURL& url); +#if defined(UNIT_TEST) + bool was_store_ever_called() const { return was_store_ever_called_; } + bool has_binding_for_credential_manager() const { + return credential_manager_impl_.HasBinding(); + } +#endif + protected: // Callable for tests. ChromePasswordManagerClient(content::WebContents* web_contents, @@ -149,11 +156,11 @@ // content::WebContentsObserver overrides. void DidStartNavigation( content::NavigationHandle* navigation_handle) override; -// TODO(crbug.com/706392): Fix password reuse detection for Android. -#if !defined(OS_ANDROID) void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; +// TODO(crbug.com/706392): Fix password reuse detection for Android. +#if !defined(OS_ANDROID) // content::RenderWidgetHost::InputEventObserver overrides. void OnInputEvent(const blink::WebInputEvent&) override; #endif @@ -232,6 +239,10 @@ base::Optional<password_manager::PasswordManagerMetricsRecorder> metrics_recorder_; + // Whether navigator.credentials.store() was ever called from this + // WebContents. Used for testing. + bool was_store_ever_called_ = false; + DISALLOW_COPY_AND_ASSIGN(ChromePasswordManagerClient); };
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 0c5d528..334ed68 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -576,8 +576,7 @@ // This call should not crash. ChromePasswordManagerClient::BindCredentialManager( - service_manager::BindSourceInfo(), - password_manager::mojom::CredentialManagerRequest(), + password_manager::mojom::CredentialManagerAssociatedRequest(), web_contents->GetMainFrame()); }
diff --git a/chrome/browser/password_manager/credential_manager_browsertest.cc b/chrome/browser/password_manager/credential_manager_browsertest.cc index f33470e..3d736459 100644 --- a/chrome/browser/password_manager/credential_manager_browsertest.cc +++ b/chrome/browser/password_manager/credential_manager_browsertest.cc
@@ -4,16 +4,21 @@ #include "base/macros.h" #include "base/stl_util.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/password_manager/password_manager_test_base.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "components/password_manager/core/browser/password_bubble_experiment.h" #include "components/password_manager/core/browser/test_password_store.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" @@ -31,8 +36,8 @@ } bool IsShowingAccountChooser() { - return PasswordsModelDelegateFromWebContents(WebContents())-> - GetState() == password_manager::ui::CREDENTIAL_REQUEST_STATE; + return PasswordsModelDelegateFromWebContents(WebContents())->GetState() == + password_manager::ui::CREDENTIAL_REQUEST_STATE; } // Similarly to PasswordManagerBrowserTestBase::NavigateToFile this is a @@ -48,6 +53,178 @@ observer.Wait(); } + // Triggers a call to `navigator.credentials.get` to retrieve passwords, waits + // for success, and ASSERTs that |expect_has_results| is satisfied. + void TriggerNavigatorGetPasswordCredentialsAndExpectHasResult( + content::WebContents* web_contents, + bool expect_has_results) { + bool result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + web_contents, + "navigator.credentials.get({password: true}).then(c => {" + " window.domAutomationController.send(!!c);" + "});", + &result)); + ASSERT_EQ(expect_has_results, result); + } + + // Schedules a call to be made to navigator.credentials.store() in the + // `unload` handler to save a credential with |username| and |password|. + void ScheduleNavigatorStoreCredentialAtUnload( + content::WebContents* web_contents, + const char* username, + const char* password) { + ASSERT_TRUE(content::ExecuteScript( + web_contents, + base::StringPrintf( + "window.addEventListener(\"unload\", () => {" + " var c = new PasswordCredential({ id: '%s', password: '%s' });" + " navigator.credentials.store(c);" + "});", + username, password))); + } + + // Tests that when navigator.credentials.store() is called in an `unload` + // handler before a same-RenderFrame navigation, the request is guaranteed to + // be serviced in the context of the initial document. + // + // If |preestablish_mojo_pipe| is set, then the CredentialManagerClient will + // establish the Mojo connection to the CredentialManagerImpl ahead of time, + // instead of letting the Mojo connection be established on-demand when the + // call to store() triggered from the unload handler. + void TestStoreInUnloadHandlerForSameSiteNavigation( + bool preestablish_mojo_pipe) { + // Use URLs that differ on subdomains so we can tell which one was used for + // saving, but they still belong to the same SiteInstance, so they will be + // renderered in the same RenderFrame (in the same process). + const GURL a_url1 = https_test_server().GetURL("foo.a.com", "/title1.html"); + const GURL a_url2 = https_test_server().GetURL("bar.a.com", "/title2.html"); + + // Navigate to a mostly empty page. + ui_test_utils::NavigateToURL(browser(), a_url1); + + ChromePasswordManagerClient* client = + ChromePasswordManagerClient::FromWebContents(WebContents()); + + if (preestablish_mojo_pipe) { + EXPECT_FALSE(client->has_binding_for_credential_manager()); + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult( + WebContents(), false)); + EXPECT_TRUE(client->has_binding_for_credential_manager()); + } + + // Schedule storing a credential on the `unload` event. + ASSERT_NO_FATAL_FAILURE(ScheduleNavigatorStoreCredentialAtUnload( + WebContents(), "user", "hunter2")); + + // Trigger a same-site navigation carried out in the same RenderFrame. + content::RenderFrameHost* old_rfh = WebContents()->GetMainFrame(); + ui_test_utils::NavigateToURL(browser(), a_url2); + ASSERT_EQ(old_rfh, WebContents()->GetMainFrame()); + + // Ensure that the old document no longer has a Mojo connection to the + // CredentialManagerImpl, nor can it get one later. + // + // The sequence of events for same-RFH navigations is as follows: + // 1.) FrameHostMsg_DidStartProvisionalLoad + // 2.) FrameLoader::PrepareForCommit + // 2.1) Document::Shutdown (old Document) + // 3.) FrameHostMsg_DidCommitProvisionalLoad (new load) + // ... loading ... + // 4.) FrameHostMsg_DidStopLoading + // 5.) content::WaitForLoadStop inside NavigateToURL returns + // 6.) NavigateToURL returns + // + // After Step 2.1, the old Document cannot issue a new Mojo InterfaceRequest + // anymore. Plus, because the AssociatedInterfaceRegistry, through which the + // associated interface to the CredentialManagerImpl is retrieved, is itself + // Channel-associated, any InterfaceRequest messages that may have been + // issued before or during Step 2.1, will be guaranteed to arrive to the + // browser side before FrameHostMsg_DidCommitProvisionalLoad in Step 3. + // + // Hence it is sufficient to check that the Mojo connection is closed now. + EXPECT_FALSE(client->has_binding_for_credential_manager()); + + // Ensure that the navigator.credentials.store() call was serviced in the + // context of the old URL, |a_url|. + // + // The CredentialManager Mojo interface is Channel-associated, so message + // ordering with legacy IPC messages is preserved. Therefore, servicing the + // store() called from the `unload` handler, triggered from + // FrameLoader::PrepareForCommit, will be serviced before + // FrameHostMsg_DidCommitProvisionalLoad, thus before DidFinishNavigation, + ASSERT_TRUE(client->was_store_ever_called()); + + BubbleObserver prompt_observer(WebContents()); + prompt_observer.WaitForSavePrompt(); + ASSERT_TRUE(prompt_observer.IsShowingSavePrompt()); + prompt_observer.AcceptSavePrompt(); + + WaitForPasswordStore(); + + password_manager::TestPasswordStore* test_password_store = + static_cast<password_manager::TestPasswordStore*>( + PasswordStoreFactory::GetForProfile( + browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) + .get()); + + ASSERT_EQ(1u, test_password_store->stored_passwords().size()); + autofill::PasswordForm signin_form = + test_password_store->stored_passwords().begin()->second[0]; + EXPECT_EQ(base::ASCIIToUTF16("user"), signin_form.username_value); + EXPECT_EQ(base::ASCIIToUTF16("hunter2"), signin_form.password_value); + EXPECT_EQ(a_url1.GetOrigin(), signin_form.origin); + } + + // Tests the when navigator.credentials.store() is called in an `unload` + // handler before a cross-site transfer navigation, the request is ignored. + // + // If |preestablish_mojo_pipe| is set, then the CredentialManagerClient will + // establish the Mojo connection to the CredentialManagerImpl ahead of time, + // instead of letting the Mojo connection be established on-demand when the + // call to store() triggered from the unload handler. + void TestStoreInUnloadHandlerForCrossSiteNavigation( + bool preestablish_mojo_pipe) { + const GURL a_url = https_test_server().GetURL("a.com", "/title1.html"); + const GURL b_url = https_test_server().GetURL("b.com", "/title2.html"); + + // Navigate to a mostly empty page. + ui_test_utils::NavigateToURL(browser(), a_url); + + ChromePasswordManagerClient* client = + ChromePasswordManagerClient::FromWebContents(WebContents()); + + if (preestablish_mojo_pipe) { + EXPECT_FALSE(client->has_binding_for_credential_manager()); + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult( + WebContents(), false)); + EXPECT_TRUE(client->has_binding_for_credential_manager()); + } + + // Schedule storing a credential on the `unload` event. + ASSERT_NO_FATAL_FAILURE(ScheduleNavigatorStoreCredentialAtUnload( + WebContents(), "user", "hunter2")); + + // Trigger a cross-site navigation that is carried out in a new renderer, + // and which will swap out the old RenderFrameHost. + content::RenderFrameDeletedObserver rfh_destruction_observer( + WebContents()->GetMainFrame()); + ui_test_utils::NavigateToURL(browser(), b_url); + + // Ensure that the navigator.credentials.store() call is never serviced. + // The sufficient conditions for this are: + // -- The swapped out RFH is destroyed, so the RenderFrame cannot + // establish a new Mojo connection to CredentialManagerImpl anymore. + // -- There is no already existing Mojo connection to CredentialManagerImpl + // either, which could be used to call store() in the future. + // -- There have not been any calls to store() in the past. + rfh_destruction_observer.WaitUntilDeleted(); + EXPECT_FALSE(client->has_binding_for_credential_manager()); + EXPECT_FALSE(client->was_store_ever_called()); + } + private: DISALLOW_COPY_AND_ASSIGN(CredentialManagerBrowserTest); }; @@ -60,7 +237,8 @@ scoped_refptr<password_manager::TestPasswordStore> password_store = static_cast<password_manager::TestPasswordStore*>( PasswordStoreFactory::GetForProfile( - browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS).get()); + browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS) + .get()); autofill::PasswordForm signin_form; signin_form.signon_realm = embedded_test_server()->base_url().spec(); signin_form.password_value = base::ASCIIToUTF16("password"); @@ -71,8 +249,8 @@ NavigateToFile("/password/password_form.html"); std::string fill_password = - "document.getElementById('username_field').value = 'user';" - "document.getElementById('password_field').value = 'password';"; + "document.getElementById('username_field').value = 'user';" + "document.getElementById('password_field').value = 'password';"; ASSERT_TRUE(content::ExecuteScript(RenderViewHost(), fill_password)); // Call the API to trigger the notification to the client. @@ -82,9 +260,10 @@ ".then(cred => window.location = '/password/done.html')")); // Mojo calls from the renderer are asynchronous. BubbleObserver(WebContents()).WaitForAccountChooser(); - PasswordsModelDelegateFromWebContents(WebContents())->ChooseCredential( - signin_form, - password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD); + PasswordsModelDelegateFromWebContents(WebContents()) + ->ChooseCredential( + signin_form, + password_manager::CredentialType::CREDENTIAL_TYPE_PASSWORD); NavigationObserver observer(WebContents()); observer.SetPathToWaitFor("/password/done.html"); @@ -245,6 +424,106 @@ EXPECT_FALSE(prompt_observer.IsShowingSavePrompt()); } +// Regression test for https://crbug.com/736357. +IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, + StoreInUnloadHandler_SameSite_OnDemandMojoPipe) { + TestStoreInUnloadHandlerForSameSiteNavigation( + false /* preestablish_mojo_pipe */); +} + +// Regression test for https://crbug.com/736357. +IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, + StoreInUnloadHandler_SameSite_PreestablishedPipe) { + TestStoreInUnloadHandlerForSameSiteNavigation( + true /* preestablish_mojo_pipe */); +} +// Regression test for https://crbug.com/736357. +IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, + StoreInUnloadHandler_CrossSite_OnDemandMojoPipe) { + TestStoreInUnloadHandlerForCrossSiteNavigation( + false /* preestablish_mojo_pipe */); +} + +// Regression test for https://crbug.com/736357. +IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, + StoreInUnloadHandler_CrossSite_PreestablishedPipe) { + TestStoreInUnloadHandlerForCrossSiteNavigation( + true /* preestablish_mojo_pipe */); +} + +// Regression test for https://crbug.com/736357. +IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, + MojoConnectionRecreatedAfterNavigation) { + const GURL a_url1 = https_test_server().GetURL("a.com", "/title1.html"); + const GURL a_url2 = https_test_server().GetURL("a.com", "/title2.html"); + const GURL a_url2_ref = https_test_server().GetURL("a.com", "/title2.html#r"); + const GURL b_url = https_test_server().GetURL("b.com", "/title2.html#ref"); + + // Enable 'auto signin' for the profile. + password_bubble_experiment::RecordAutoSignInPromptFirstRunExperienceWasShown( + browser()->profile()->GetPrefs()); + + // Navigate to a mostly empty page. + ui_test_utils::NavigateToURL(browser(), a_url1); + + ChromePasswordManagerClient* client = + ChromePasswordManagerClient::FromWebContents(WebContents()); + + // Store a credential, and expect it to establish the Mojo connection. + EXPECT_FALSE(client->has_binding_for_credential_manager()); + EXPECT_FALSE(client->was_store_ever_called()); + + ASSERT_TRUE(content::ExecuteScript( + WebContents(), + "var c = new PasswordCredential({ id: 'user', password: 'hunter2' });" + "navigator.credentials.store(c);")); + + BubbleObserver prompt_observer(WebContents()); + prompt_observer.WaitForSavePrompt(); + ASSERT_TRUE(prompt_observer.IsShowingSavePrompt()); + prompt_observer.AcceptSavePrompt(); + WaitForPasswordStore(); + + EXPECT_TRUE(client->has_binding_for_credential_manager()); + EXPECT_TRUE(client->was_store_ever_called()); + + // Trigger a same-site navigation. + content::RenderFrameHost* old_rfh = WebContents()->GetMainFrame(); + ui_test_utils::NavigateToURL(browser(), a_url2); + ASSERT_EQ(old_rfh, WebContents()->GetMainFrame()); + + // Expect the Mojo connection closed. + EXPECT_FALSE(client->has_binding_for_credential_manager()); + + // Calling navigator.credentials.get() again should re-establish the Mojo + // connection and succeed. + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult(WebContents(), + true)); + EXPECT_TRUE(client->has_binding_for_credential_manager()); + + // Same-document navigation. Call to get() succeeds. + ui_test_utils::NavigateToURL(browser(), a_url2_ref); + ASSERT_EQ(old_rfh, WebContents()->GetMainFrame()); + EXPECT_TRUE(client->has_binding_for_credential_manager()); + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult(WebContents(), + true)); + + // Cross-site navigation. Call to get() succeeds without results. + ui_test_utils::NavigateToURL(browser(), b_url); + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult(WebContents(), + false)); + + // Trigger a cross-site navigation back. Call to get() should still succeed, + // and once again with results. + ui_test_utils::NavigateToURL(browser(), a_url1); + ASSERT_NO_FATAL_FAILURE( + TriggerNavigatorGetPasswordCredentialsAndExpectHasResult(WebContents(), + true)); +} + IN_PROC_BROWSER_TEST_F(CredentialManagerBrowserTest, SaveViaAPIAndAutofill) { NavigateToFile("/password/password_form.html");
diff --git a/chrome/browser/password_manager/password_store_factory.cc b/chrome/browser/password_manager/password_store_factory.cc index 399a3b2..28e50f8 100644 --- a/chrome/browser/password_manager/password_store_factory.cc +++ b/chrome/browser/password_manager/password_store_factory.cc
@@ -21,6 +21,7 @@ #include "chrome/browser/sync/glue/sync_start_util.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/web_data_service_factory.h" +#include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #include "components/browser_sync/profile_sync_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" @@ -195,8 +196,17 @@ PrefService* prefs = profile->GetPrefs(); LocalProfileId id = GetLocalProfileId(prefs); + bool use_preference = base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableEncryptionSelection); + bool use_backend = true; + if (use_preference) { + base::FilePath user_data_dir; + chrome::GetDefaultUserDataDirectory(&user_data_dir); + use_backend = os_crypt::GetBackendUse(user_data_dir); + } + os_crypt::SelectedLinuxBackend selected_backend = - os_crypt::SelectBackend(store_type, desktop_env); + os_crypt::SelectBackend(store_type, use_backend, desktop_env); std::unique_ptr<PasswordStoreX::NativeBackend> backend; if (selected_backend == os_crypt::SelectedLinuxBackend::KWALLET ||
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 2a3cda54b..7b796c30 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -776,168 +776,6 @@ } #endif -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, LinkCtrlLeftClick) { - GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); - WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); - ASSERT_TRUE(guest_contents); - - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); - - WebContents* web_contents = GetActiveWebContents(); - - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - content::SimulateMouseClickAt(web_contents, kDefaultKeyModifier, - blink::WebMouseEvent::Button::kLeft, - link_position); - observer.Wait(); - - int tab_count = browser()->tab_strip_model()->count(); - ASSERT_EQ(2, tab_count); - - WebContents* active_web_contents = GetActiveWebContents(); - ASSERT_EQ(web_contents, active_web_contents); - - WebContents* new_web_contents = - browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(new_web_contents); - ASSERT_NE(web_contents, new_web_contents); - - const GURL& url = new_web_contents->GetURL(); - ASSERT_EQ(std::string("http://www.example.com/"), url.spec()); -} - -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, LinkMiddleClick) { - GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); - WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); - ASSERT_TRUE(guest_contents); - - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); - - WebContents* web_contents = GetActiveWebContents(); - - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - content::SimulateMouseClickAt( - web_contents, 0, blink::WebMouseEvent::Button::kMiddle, link_position); - observer.Wait(); - - int tab_count = browser()->tab_strip_model()->count(); - ASSERT_EQ(2, tab_count); - - WebContents* active_web_contents = GetActiveWebContents(); - ASSERT_EQ(web_contents, active_web_contents); - - WebContents* new_web_contents = - browser()->tab_strip_model()->GetWebContentsAt(1); - ASSERT_TRUE(new_web_contents); - ASSERT_NE(web_contents, new_web_contents); - - const GURL& url = new_web_contents->GetURL(); - ASSERT_EQ(std::string("http://www.example.com/"), url.spec()); -} - -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, LinkCtrlShiftLeftClick) { - GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); - WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); - ASSERT_TRUE(guest_contents); - - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); - - WebContents* web_contents = GetActiveWebContents(); - - int modifiers = blink::WebInputEvent::kShiftKey | kDefaultKeyModifier; - - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - content::SimulateMouseClickAt(web_contents, modifiers, - blink::WebMouseEvent::Button::kLeft, - link_position); - observer.Wait(); - - int tab_count = browser()->tab_strip_model()->count(); - ASSERT_EQ(2, tab_count); - - WebContents* active_web_contents = GetActiveWebContents(); - ASSERT_NE(web_contents, active_web_contents); - - const GURL& url = active_web_contents->GetURL(); - ASSERT_EQ(std::string("http://www.example.com/"), url.spec()); -} - -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, LinkShiftMiddleClick) { - GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); - WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); - ASSERT_TRUE(guest_contents); - - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); - - WebContents* web_contents = GetActiveWebContents(); - - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - content::SimulateMouseClickAt(web_contents, blink::WebInputEvent::kShiftKey, - blink::WebMouseEvent::Button::kMiddle, - link_position); - observer.Wait(); - - int tab_count = browser()->tab_strip_model()->count(); - ASSERT_EQ(2, tab_count); - - WebContents* active_web_contents = GetActiveWebContents(); - ASSERT_NE(web_contents, active_web_contents); - - const GURL& url = active_web_contents->GetURL(); - ASSERT_EQ(std::string("http://www.example.com/"), url.spec()); -} - -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, LinkShiftLeftClick) { - GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); - WebContents* guest_contents = LoadPdfGetGuestContents(test_pdf_url); - ASSERT_TRUE(guest_contents); - ASSERT_EQ(1U, chrome::GetTotalBrowserCount()); - - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); - - WebContents* web_contents = GetActiveWebContents(); - - content::WindowedNotificationObserver observer( - chrome::NOTIFICATION_BROWSER_WINDOW_READY, - content::NotificationService::AllSources()); - content::SimulateMouseClickAt(web_contents, blink::WebInputEvent::kShiftKey, - blink::WebMouseEvent::Button::kLeft, - link_position); - observer.Wait(); - - ASSERT_EQ(2U, chrome::GetTotalBrowserCount()); - - WebContents* active_web_contents = - chrome::FindLastActive()->tab_strip_model()->GetActiveWebContents(); - ASSERT_NE(web_contents, active_web_contents); - - const GURL& url = active_web_contents->GetURL(); - ASSERT_EQ(std::string("http://www.example.com/"), url.spec()); -} - // Test that if the plugin tries to load a URL that redirects then it will fail // to load. This is to avoid the source origin of the document changing during // the redirect, which can have security implications. https://crbug.com/653749. @@ -954,8 +792,7 @@ WebContents* web_contents = GetActiveWebContents(); ui_test_utils::NavigateToURLWithDisposition( - browser(), GURL("about:blank"), - WindowOpenDisposition::NEW_FOREGROUND_TAB, + browser(), GURL("about:blank"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB | ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); WebContents* active_web_contents = GetActiveWebContents(); @@ -970,11 +807,187 @@ EXPECT_FALSE(active_web_contents->GetController().GetPendingEntry()); } +IN_PROC_BROWSER_TEST_F(PDFExtensionTest, OpenFromFTP) { + net::SpawnedTestServer ftp_server( + net::SpawnedTestServer::TYPE_FTP, net::SpawnedTestServer::kLocalhost, + base::FilePath(FILE_PATH_LITERAL("chrome/test/data/pdf"))); + ASSERT_TRUE(ftp_server.Start()); + + GURL url(ftp_server.GetURL("/test.pdf")); + ASSERT_TRUE(LoadPdf(url)); + EXPECT_EQ(base::ASCIIToUTF16("test.pdf"), GetActiveWebContents()->GetTitle()); +} + +class PDFExtensionLinkClickTest : public PDFExtensionTest { + public: + PDFExtensionLinkClickTest() : guest_contents_(nullptr) {} + ~PDFExtensionLinkClickTest() override {} + + protected: + void LoadTestLinkPdfGetGuestContents() { + GURL test_pdf_url(embedded_test_server()->GetURL("/pdf/test-link.pdf")); + guest_contents_ = LoadPdfGetGuestContents(test_pdf_url); + ASSERT_TRUE(guest_contents_); + } + + // The rectangle of the link in test-link.pdf is [72 706 164 719] in PDF user + // space. To calculate a position inside this rectangle, several + // transformations have to be applied: + // [a] (110, 110) in Blink page coordinates -> + // [b] (219, 169) in Blink screen coordinates -> + // [c] (115, 169) in PDF Device space coordinates -> + // [d] (82.5, 709.5) in PDF user space coordinates. + // This performs the [a] to [b] transformation, since that is the coordinate + // space content::SimulateMouseClickAt() needs. + gfx::Point GetLinkPosition() { + gfx::Point link_position(110, 110); + ConvertPageCoordToScreenCoord(guest_contents_, &link_position); + return link_position; + } + + void SetGuestContents(WebContents* guest_contents) { + ASSERT_TRUE(guest_contents); + guest_contents_ = guest_contents; + } + + private: + WebContents* guest_contents_; +}; + +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, CtrlLeft) { + LoadTestLinkPdfGetGuestContents(); + + WebContents* web_contents = GetActiveWebContents(); + + content::WindowedNotificationObserver observer( + chrome::NOTIFICATION_TAB_ADDED, + content::NotificationService::AllSources()); + content::SimulateMouseClickAt(web_contents, kDefaultKeyModifier, + blink::WebMouseEvent::Button::kLeft, + GetLinkPosition()); + observer.Wait(); + + int tab_count = browser()->tab_strip_model()->count(); + ASSERT_EQ(2, tab_count); + + WebContents* active_web_contents = GetActiveWebContents(); + ASSERT_EQ(web_contents, active_web_contents); + + WebContents* new_web_contents = + browser()->tab_strip_model()->GetWebContentsAt(1); + ASSERT_TRUE(new_web_contents); + ASSERT_NE(web_contents, new_web_contents); + + const GURL& url = new_web_contents->GetURL(); + EXPECT_EQ("http://www.example.com/", url.spec()); +} + +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, Middle) { + LoadTestLinkPdfGetGuestContents(); + + WebContents* web_contents = GetActiveWebContents(); + + content::WindowedNotificationObserver observer( + chrome::NOTIFICATION_TAB_ADDED, + content::NotificationService::AllSources()); + content::SimulateMouseClickAt(web_contents, 0, + blink::WebMouseEvent::Button::kMiddle, + GetLinkPosition()); + observer.Wait(); + + int tab_count = browser()->tab_strip_model()->count(); + ASSERT_EQ(2, tab_count); + + WebContents* active_web_contents = GetActiveWebContents(); + ASSERT_EQ(web_contents, active_web_contents); + + WebContents* new_web_contents = + browser()->tab_strip_model()->GetWebContentsAt(1); + ASSERT_TRUE(new_web_contents); + ASSERT_NE(web_contents, new_web_contents); + + const GURL& url = new_web_contents->GetURL(); + EXPECT_EQ("http://www.example.com/", url.spec()); +} + +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, CtrlShiftLeft) { + LoadTestLinkPdfGetGuestContents(); + + WebContents* web_contents = GetActiveWebContents(); + + const int modifiers = blink::WebInputEvent::kShiftKey | kDefaultKeyModifier; + + content::WindowedNotificationObserver observer( + chrome::NOTIFICATION_TAB_ADDED, + content::NotificationService::AllSources()); + content::SimulateMouseClickAt(web_contents, modifiers, + blink::WebMouseEvent::Button::kLeft, + GetLinkPosition()); + observer.Wait(); + + int tab_count = browser()->tab_strip_model()->count(); + ASSERT_EQ(2, tab_count); + + WebContents* active_web_contents = GetActiveWebContents(); + ASSERT_NE(web_contents, active_web_contents); + + const GURL& url = active_web_contents->GetURL(); + EXPECT_EQ("http://www.example.com/", url.spec()); +} + +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, ShiftMiddle) { + LoadTestLinkPdfGetGuestContents(); + + WebContents* web_contents = GetActiveWebContents(); + + content::WindowedNotificationObserver observer( + chrome::NOTIFICATION_TAB_ADDED, + content::NotificationService::AllSources()); + content::SimulateMouseClickAt(web_contents, blink::WebInputEvent::kShiftKey, + blink::WebMouseEvent::Button::kMiddle, + GetLinkPosition()); + observer.Wait(); + + int tab_count = browser()->tab_strip_model()->count(); + ASSERT_EQ(2, tab_count); + + WebContents* active_web_contents = GetActiveWebContents(); + ASSERT_NE(web_contents, active_web_contents); + + const GURL& url = active_web_contents->GetURL(); + EXPECT_EQ("http://www.example.com/", url.spec()); +} + +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, ShiftLeft) { + LoadTestLinkPdfGetGuestContents(); + + ASSERT_EQ(1U, chrome::GetTotalBrowserCount()); + + WebContents* web_contents = GetActiveWebContents(); + + content::WindowedNotificationObserver observer( + chrome::NOTIFICATION_BROWSER_WINDOW_READY, + content::NotificationService::AllSources()); + content::SimulateMouseClickAt(web_contents, blink::WebInputEvent::kShiftKey, + blink::WebMouseEvent::Button::kLeft, + GetLinkPosition()); + observer.Wait(); + + ASSERT_EQ(2U, chrome::GetTotalBrowserCount()); + + WebContents* active_web_contents = + chrome::FindLastActive()->tab_strip_model()->GetActiveWebContents(); + ASSERT_NE(web_contents, active_web_contents); + + const GURL& url = active_web_contents->GetURL(); + EXPECT_EQ("http://www.example.com/", url.spec()); +} + // This test opens a PDF by clicking a link via javascript and verifies that // the PDF is loaded and functional by clicking a link in the PDF. The link // click in the PDF opens a new tab. The main page handles the pageShow event // and updates the history state. -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, OpenPDFOnLinkClickWithReplaceState) { +IN_PROC_BROWSER_TEST_F(PDFExtensionLinkClickTest, OpenPDFWithReplaceState) { // Navigate to the main page. GURL test_url( embedded_test_server()->GetURL("/pdf/pdf_href_replace_state.html")); @@ -997,19 +1010,14 @@ // tab. content::BrowserPluginGuestManager* guest_manager = web_contents->GetBrowserContext()->GetGuestManager(); - WebContents* guest_contents = guest_manager->GetFullPageGuest(web_contents); - ASSERT_TRUE(guest_contents); - // The link position of the test-link.pdf in page coordinates is (110, 110). - // Convert the link position from page coordinates to screen coordinates. - gfx::Point link_position(110, 110); - ConvertPageCoordToScreenCoord(guest_contents, &link_position); + SetGuestContents(guest_manager->GetFullPageGuest(web_contents)); content::WindowedNotificationObserver observer( chrome::NOTIFICATION_TAB_ADDED, content::NotificationService::AllSources()); content::SimulateMouseClickAt(web_contents, kDefaultKeyModifier, blink::WebMouseEvent::Button::kLeft, - link_position); + GetLinkPosition()); observer.Wait(); // We should have two tabs now. One with the PDF and the second for @@ -1026,16 +1034,5 @@ ASSERT_NE(web_contents, new_web_contents); const GURL& url = new_web_contents->GetURL(); - ASSERT_EQ(GURL("http://www.example.com"), url); -} - -IN_PROC_BROWSER_TEST_F(PDFExtensionTest, OpenFromFTP) { - net::SpawnedTestServer ftp_server( - net::SpawnedTestServer::TYPE_FTP, net::SpawnedTestServer::kLocalhost, - base::FilePath(FILE_PATH_LITERAL("chrome/test/data/pdf"))); - ASSERT_TRUE(ftp_server.Start()); - - GURL url(ftp_server.GetURL("/test.pdf")); - ASSERT_TRUE(LoadPdf(url)); - EXPECT_EQ(base::ASCIIToUTF16("test.pdf"), GetActiveWebContents()->GetTitle()); + EXPECT_EQ("http://www.example.com/", url.spec()); }
diff --git a/chrome/browser/permissions/permission_manager.cc b/chrome/browser/permissions/permission_manager.cc index 5f20517..f2850063 100644 --- a/chrome/browser/permissions/permission_manager.cc +++ b/chrome/browser/permissions/permission_manager.cc
@@ -196,6 +196,46 @@ size_t remaining_results_; }; +// Object to track the callback passed to +// PermissionContextBase::RequestPermission. The callback passed in will never +// be run when a permission prompt has been ignored, but it's important that we +// know when a prompt is ignored to clean up |pending_requests_| correctly. +// If the callback is destroyed without being run, the destructor here will +// cancel the request to clean up. +class PermissionManager::PermissionResponseCallback { + public: + PermissionResponseCallback( + const base::WeakPtr<PermissionManager>& permission_manager, + int request_id, + int permission_id) + : permission_manager_(permission_manager), + request_id_(request_id), + permission_id_(permission_id), + request_answered_(false) {} + + ~PermissionResponseCallback() { + if (!request_answered_ && + permission_manager_->pending_requests_.Lookup(request_id_)) { + permission_manager_->pending_requests_.Remove(request_id_); + } + } + + void OnPermissionsRequestResponseStatus(ContentSetting content_setting) { + request_answered_ = true; + permission_manager_->OnPermissionsRequestResponseStatus( + request_id_, permission_id_, content_setting); + } + + private: + base::WeakPtr<PermissionManager> permission_manager_; + int request_id_; + int permission_id_; + + bool request_answered_; + + DISALLOW_COPY_AND_ASSIGN(PermissionResponseCallback); +}; + struct PermissionManager::Subscription { ContentSettingsType permission; GURL requesting_origin; @@ -250,6 +290,7 @@ } PermissionManager::~PermissionManager() { + DCHECK(pending_requests_.IsEmpty()); DCHECK(subscriptions_.IsEmpty()); } @@ -308,10 +349,13 @@ PermissionContextBase* context = GetPermissionContext(permission); DCHECK(context); + auto callback = base::MakeUnique<PermissionResponseCallback>( + weak_ptr_factory_.GetWeakPtr(), request_id, i); context->RequestPermission( web_contents, request, requesting_origin, user_gesture, - base::Bind(&PermissionManager::OnPermissionsRequestResponseStatus, - weak_ptr_factory_.GetWeakPtr(), request_id, i)); + base::Bind( + &PermissionResponseCallback::OnPermissionsRequestResponseStatus, + base::Passed(&callback))); } // The request might have been resolved already. @@ -413,7 +457,8 @@ continue; context->CancelPermissionRequest(web_contents, request); } - pending_requests_.Remove(request_id); + // The request should be automatically removed from |pending_requests_| as a + // result of it being cancelled but not necessarily immediately. } void PermissionManager::ResetPermission(PermissionType permission,
diff --git a/chrome/browser/permissions/permission_manager.h b/chrome/browser/permissions/permission_manager.h index 339154b..c75d967 100644 --- a/chrome/browser/permissions/permission_manager.h +++ b/chrome/browser/permissions/permission_manager.h
@@ -104,11 +104,14 @@ bool IsPermissionKillSwitchOn(ContentSettingsType); private: + friend class PermissionManagerTest; friend class GeolocationPermissionContextTests; class PendingRequest; using PendingRequestsMap = IDMap<std::unique_ptr<PendingRequest>>; + class PermissionResponseCallback; + struct Subscription; using SubscriptionsMap = IDMap<std::unique_ptr<Subscription>>;
diff --git a/chrome/browser/permissions/permission_manager_unittest.cc b/chrome/browser/permissions/permission_manager_unittest.cc index a24af58..b5911d6b 100644 --- a/chrome/browser/permissions/permission_manager_unittest.cc +++ b/chrome/browser/permissions/permission_manager_unittest.cc
@@ -8,7 +8,9 @@ #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/permissions/permission_manager_factory.h" +#include "chrome/browser/permissions/permission_request_manager.h" #include "chrome/browser/permissions/permission_result.h" +#include "chrome/browser/ui/permission_bubble/mock_permission_prompt_factory.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -105,6 +107,10 @@ callback_result_ = PermissionStatus::ASK; } + bool PendingRequestsEmpty() { + return GetPermissionManager()->pending_requests_.IsEmpty(); + } + private: void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); @@ -435,3 +441,26 @@ EXPECT_EQ(PermissionStatus::GRANTED, callback_result()); } #endif // BUILDFLAG(ENABLE_VR) && defined(OS_ANDROID) + +TEST_F(PermissionManagerTest, PermissionIgnoredCleanup) { + content::WebContents* contents = web_contents(); + PermissionRequestManager::CreateForWebContents(contents); + PermissionRequestManager* manager = + PermissionRequestManager::FromWebContents(contents); + auto prompt_factory = base::MakeUnique<MockPermissionPromptFactory>(manager); + manager->DisplayPendingRequests(); + + NavigateAndCommit(url()); + + GetPermissionManager()->RequestPermission( + PermissionType::VIDEO_CAPTURE, main_rfh(), url(), /*user_gesture=*/true, + base::Bind(&PermissionManagerTest::OnPermissionChange, + base::Unretained(this))); + + EXPECT_FALSE(PendingRequestsEmpty()); + + NavigateAndCommit(GURL("https://foobar.com")); + + EXPECT_FALSE(callback_called()); + EXPECT_TRUE(PendingRequestsEmpty()); +}
diff --git a/chrome/browser/plugins/plugin_info_message_filter.cc b/chrome/browser/plugins/plugin_info_message_filter.cc index db42fc0..176b1bc3b 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.cc +++ b/chrome/browser/plugins/plugin_info_message_filter.cc
@@ -40,8 +40,6 @@ #include "components/keyed_service/content/browser_context_keyed_service_shutdown_notifier_factory.h" #include "components/prefs/pref_service.h" #include "components/rappor/rappor_service_impl.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/plugin_service_filter.h" @@ -50,6 +48,8 @@ #include "extensions/features/features.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "ppapi/features/features.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/gurl.h" #include "url/origin.h" #include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.cc b/chrome/browser/policy/cloud/user_policy_signin_service.cc index 0a5e82188..ee16133 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service.cc
@@ -71,7 +71,7 @@ oauth2_token_service_->RemoveObserver(this); } -void UserPolicySigninService::RegisterForPolicy( +void UserPolicySigninService::RegisterForPolicyWithLoginToken( const std::string& username, const std::string& oauth2_refresh_token, const PolicyRegistrationCallback& callback) { @@ -90,9 +90,9 @@ // request context because the user is not signed in to this profile yet // (we are just doing a test registration to see if policy is supported for // this user). - registration_helper_.reset(new CloudPolicyClientRegistrationHelper( + registration_helper_ = base::MakeUnique<CloudPolicyClientRegistrationHelper>( policy_client.get(), - enterprise_management::DeviceRegisterRequest::BROWSER)); + enterprise_management::DeviceRegisterRequest::BROWSER); registration_helper_->StartRegistrationWithLoginToken( oauth2_refresh_token, base::Bind(&UserPolicySigninService::CallPolicyRegistrationCallback, @@ -101,6 +101,35 @@ callback)); } +void UserPolicySigninService::RegisterForPolicyWithAccountId( + const std::string& username, + const std::string& account_id, + const PolicyRegistrationCallback& callback) { + DCHECK(!account_id.empty()); + + // Create a new CloudPolicyClient for fetching the DMToken. + std::unique_ptr<CloudPolicyClient> policy_client = + CreateClientForRegistrationOnly(username); + if (!policy_client) { + callback.Run(std::string(), std::string()); + return; + } + + // Fire off the registration process. Callback keeps the CloudPolicyClient + // alive for the length of the registration process. Use the system + // request context because the user is not signed in to this profile yet + // (we are just doing a test registration to see if policy is supported for + // this user). + registration_helper_ = base::MakeUnique<CloudPolicyClientRegistrationHelper>( + policy_client.get(), + enterprise_management::DeviceRegisterRequest::BROWSER); + registration_helper_->StartRegistration( + oauth2_token_service_, account_id, + base::Bind(&UserPolicySigninService::CallPolicyRegistrationCallback, + base::Unretained(this), base::Passed(&policy_client), + callback)); +} + void UserPolicySigninService::CallPolicyRegistrationCallback( std::unique_ptr<CloudPolicyClient> client, PolicyRegistrationCallback callback) {
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service.h b/chrome/browser/policy/cloud/user_policy_signin_service.h index 65d94865..7cd00098 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service.h
@@ -47,9 +47,18 @@ // the user is not signed in yet (ProfileOAuth2TokenService does not have // any tokens yet to prevent services from using it until after we've fetched // policy). - void RegisterForPolicy(const std::string& username, - const std::string& oauth2_login_token, - const PolicyRegistrationCallback& callback); + void RegisterForPolicyWithLoginToken( + const std::string& username, + const std::string& oauth2_login_token, + const PolicyRegistrationCallback& callback); + + // Registers a CloudPolicyClient for fetching policy for a user. |username| is + // explicitly passed because the user is not yet authenticated, but the token + // service has a refresh token available for |account_id|. + void RegisterForPolicyWithAccountId( + const std::string& username, + const std::string& account_id, + const PolicyRegistrationCallback& callback); // OAuth2TokenService::Observer implementation: void OnRefreshTokenAvailable(const std::string& account_id) override;
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_base.h b/chrome/browser/policy/cloud/user_policy_signin_service_base.h index 0d86957e7..a151d969 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_base.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_base.h
@@ -72,7 +72,7 @@ ~UserPolicySigninServiceBase() override; // Initiates a policy fetch as part of user signin, using a |dm_token| and - // |client_id| fetched via RegisterForPolicy(). |callback| is invoked + // |client_id| fetched via RegisterForPolicyXXX(). |callback| is invoked // once the policy fetch is complete, passing true if the policy fetch // succeeded. void FetchPolicyForSignedInUser(
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc index 89ca832..7536472 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.cc
@@ -62,36 +62,14 @@ UserPolicySigninService::~UserPolicySigninService() {} -void UserPolicySigninService::RegisterForPolicy( - const std::string& username, - const std::string& account_id, - const PolicyRegistrationCallback& callback) { - RegisterForPolicyInternal(username, account_id, "", callback); -} - -#if !defined(OS_ANDROID) -void UserPolicySigninService::RegisterForPolicyWithAccessToken( - const std::string& username, - const std::string& access_token, - const PolicyRegistrationCallback& callback) { - RegisterForPolicyInternal(username, "", access_token, callback); -} - -// static -std::vector<std::string> UserPolicySigninService::GetScopes() { - return CloudPolicyClientRegistrationHelper::GetScopes(); -} -#endif - void UserPolicySigninService::ShutdownUserCloudPolicyManager() { CancelPendingRegistration(); UserPolicySigninServiceBase::ShutdownUserCloudPolicyManager(); } -void UserPolicySigninService::RegisterForPolicyInternal( +void UserPolicySigninService::RegisterForPolicyWithAccountId( const std::string& username, const std::string& account_id, - const std::string& access_token, const PolicyRegistrationCallback& callback) { // Create a new CloudPolicyClient for fetching the DMToken. std::unique_ptr<CloudPolicyClient> policy_client = @@ -114,17 +92,8 @@ auto registration_callback = base::Bind( &UserPolicySigninService::CallPolicyRegistrationCallback, base::Unretained(this), base::Passed(&policy_client), callback); - if (access_token.empty()) { - registration_helper_->StartRegistration( - oauth2_token_service_, account_id, registration_callback); - } else { -#if defined(OS_ANDROID) - NOTREACHED(); -#else - registration_helper_->StartRegistrationWithAccessToken( - access_token, registration_callback); -#endif - } + registration_helper_->StartRegistration(oauth2_token_service_, account_id, + registration_callback); } void UserPolicySigninService::CallPolicyRegistrationCallback(
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h index c024376..1c3e4c8 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h +++ b/chrome/browser/policy/cloud/user_policy_signin_service_mobile.h
@@ -27,8 +27,7 @@ class CloudPolicyClientRegistrationHelper; -// A specialization of the UserPolicySigninServiceBase for the mobile platforms -// (currently Android and iOS). +// A specialization of UserPolicySigninServiceBase for the Android. class UserPolicySigninService : public UserPolicySigninServiceBase { public: // Creates a UserPolicySigninService associated with the passed |profile|. @@ -49,25 +48,11 @@ // token services. // |callback| is invoked once we have registered this device to fetch policy, // or once it is determined that |username| is not a managed account. - void RegisterForPolicy(const std::string& username, - const std::string& account_id, - const PolicyRegistrationCallback& callback); - -#if !defined(OS_ANDROID) - // Registers a CloudPolicyClient for fetching policy for |username|. - // This requires a valid OAuth access token for the scopes returned by the - // |GetScopes| static function. |callback| is invoked once we have - // registered this device to fetch policy, or once it is determined that - // |username| is not a managed account. - void RegisterForPolicyWithAccessToken( + void RegisterForPolicyWithAccountId( const std::string& username, - const std::string& access_token, + const std::string& account_id, const PolicyRegistrationCallback& callback); - // Returns the list of OAuth access scopes required for policy fetching. - static std::vector<std::string> GetScopes(); -#endif - // Overridden from UserPolicySigninServiceBase to cancel the pending delayed // registration. void ShutdownUserCloudPolicyManager() override;
diff --git a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc index 55ae8d1..d4fa2fa 100644 --- a/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc +++ b/chrome/browser/policy/cloud/user_policy_signin_service_unittest.cc
@@ -120,21 +120,19 @@ // Policy client registration on Android depends on Token Service having // a valid login token, while on other platforms, the login refresh token // is specified directly. + UserPolicySigninServiceBase::PolicyRegistrationCallback callback = + base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted, + base::Unretained(this)); #if defined(OS_ANDROID) GetTokenService()->UpdateCredentials( AccountTrackerService::PickAccountIdForAccount( profile_.get()->GetPrefs(), kTestGaiaId, kTestUser), "oauth2_login_refresh_token"); -#endif - service->RegisterForPolicy( - kTestUser, -#if defined(OS_ANDROID) - kTestGaiaId, + service->RegisterForPolicyWithAccountId(kTestUser, kTestGaiaId, callback); #else - "mock_oauth_token", + service->RegisterForPolicyWithLoginToken(kTestUser, "mock_oauth_token", + callback); #endif - base::Bind(&UserPolicySigninServiceTest::OnRegisterCompleted, - base::Unretained(this))); ASSERT_TRUE(IsRequestActive()); }
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index ef4466a9..290c131 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -133,6 +133,7 @@ #include "ui/base/l10n/l10n_util.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/arc_service_launcher.h" #include "chrome/browser/chromeos/authpolicy/auth_policy_credentials_manager.h" #include "chrome/browser/chromeos/locale_change_guard.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" @@ -911,10 +912,14 @@ g_browser_process->profile_manager()->InitProfileUserPrefs(this); +#if defined(OS_CHROMEOS) + arc::ArcServiceLauncher::Get()->MaybeSetProfile(this); +#endif + { SCOPED_UMA_HISTOGRAM_TIMER("Profile.CreateBrowserContextServicesTime"); - BrowserContextDependencyManager::GetInstance()-> - CreateBrowserContextServices(this); + BrowserContextDependencyManager::GetInstance() + ->CreateBrowserContextServices(this); } ChromeVersionService::OnProfileLoaded(prefs_.get(), IsNewProfile());
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index 3351f16..a0d16e70 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -2211,11 +2211,31 @@ source_web_contents_->GetBrowserContext(), render_frame_host->GetSiteInstance()); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("render_view_context_menu", R"( + semantics { + sender: "Save Link As" + description: "Saving url to local file." + trigger: + "The user selects the 'Save link as...' command in the context " + "menu." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: + "This feature cannot be disabled by settings. The request is made " + "only if user chooses 'Save link as...' in the context menu." + policy_exception_justification: "Not implemented." + })"); + auto dl_params = base::MakeUnique<DownloadUrlParameters>( url, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRenderViewHost()->GetRoutingID(), render_frame_host->GetRoutingID(), - storage_partition->GetURLRequestContext(), NO_TRAFFIC_ANNOTATION_YET); + storage_partition->GetURLRequestContext(), traffic_annotation); dl_params->set_referrer(CreateReferrer(url, params_)); dl_params->set_referrer_encoding(params_.frame_charset); dl_params->set_suggested_name(params_.suggested_filename);
diff --git a/chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.cc b/chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.cc index 7adf73b..a8d53c3 100644 --- a/chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.cc +++ b/chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.cc
@@ -6,12 +6,12 @@ #include <utility> -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" #include "services/resource_coordinator/public/cpp/resource_coordinator_features.h" #include "services/resource_coordinator/public/interfaces/service_callbacks.mojom.h" #include "services/resource_coordinator/public/interfaces/service_constants.mojom.h"
diff --git a/chrome/browser/resources/chromeos/login/oobe_screen_voice_interaction_value_prop.js b/chrome/browser/resources/chromeos/login/oobe_screen_voice_interaction_value_prop.js index e2f77741..a9e4f4e 100644 --- a/chrome/browser/resources/chromeos/login/oobe_screen_voice_interaction_value_prop.js +++ b/chrome/browser/resources/chromeos/login/oobe_screen_voice_interaction_value_prop.js
@@ -11,46 +11,12 @@ function() { return { - /** - * Returns a control which should receive an initial focus. - */ - get defaultControl() { - return $('voice-interaction-value-prop-md') - .getElement('continueButton'); - }, - /** @Override */ onBeforeShow: function(data) { - var valueView = $('voice-interaction-value-prop-md') - .getElement('value-prop-view'); - - valueView.addContentScripts([{ - name: 'stripLinks', - matches: ['<all_urls>'], - js: { - code: 'document.querySelectorAll(\'a\').forEach(' + - 'function(anchor){anchor.href=\'javascript:void(0)\';})' - }, - run_at: 'document_end' - }]); - - // TODO(updowndota): provide static content later for the final - // fallback. - valueView.request.onHeadersReceived.addListener(function(details) { - if (details.statusCode == '404') { - if (valueView.src != - 'https://www.gstatic.com/opa-chromeos/oobe/en/value_proposition.html') { - valueView.src = - 'https://www.gstatic.com/opa-chromeos/oobe/en/value_proposition.html'; - } - } - }, {urls: ['<all_urls>'], types: ['main_frame']}); - - var locale = loadTimeData.getString('locale'); - valueView.src = 'https://www.gstatic.com/opa-chromeos/oobe/' + - locale + '/value_proposition.html'; - Oobe.getInstance().headerHidden = true; + $('voice-interaction-value-prop-md').locale = + loadTimeData.getString('locale'); + $('voice-interaction-value-prop-md').onShow(); } }; });
diff --git a/chrome/browser/resources/chromeos/login/oobe_text_button.css b/chrome/browser/resources/chromeos/login/oobe_text_button.css index 4d49b05..47a40e2 100644 --- a/chrome/browser/resources/chromeos/login/oobe_text_button.css +++ b/chrome/browser/resources/chromeos/login/oobe_text_button.css
@@ -20,10 +20,6 @@ height: 31px; } -paper-button[android]:not([border]):not([inverse]) { - height: 13px; -} - #container { border-radius: 2px; padding: 0 16px; @@ -50,6 +46,16 @@ padding: 0 18px; } +#textButton[android][disabled]:not([inverse]) { + background-color: white; + color: rgba(66, 133, 244, .38); +} + +#textButton[android][disabled][inverse] { + background-color: rgba(66, 133, 244, .38); + color: white; +} + ::content * { font: var(--oobe-roboto-medium), sans-serif; font-size: 12px;
diff --git a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.css b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.css index c4846d5..5d36db11 100644 --- a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.css +++ b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.css
@@ -9,10 +9,74 @@ padding: 0; } -#noThanksButton { +.value-prop-loading #retry-button, +.value-prop-loading #skip-button, +.value-prop-loaded #retry-button, +.value-prop-loaded #skip-button, +.value-prop-error #continue-button, +.value-prop-error #no-thanks-button { + display: none; +} + +#loading-container, +#error-container, +#view-container { + position: absolute; + visibility: hidden; + width: 480px; +} + +.value-prop-loading-animation #loading-container, +.value-prop-loaded #view-container, +.value-prop-error #error-container { + visibility: visible; +} + +.value-prop-loading #retry-button, +.value-prop-loading #skip-button, +.value-prop-loading #continue-button, +.value-prop-loading #no-thanks-button { + pointer-events: none; +} + +.title { + font-size: 18px; +} + +#subtitle { + font-size: 12px; + padding: 14px 0 0 0; +} + +#loading-message { + color: rgba(0, 0, 0, .54); + font-size: 12px; + line: 17px; + padding: 168px 0 0 0; +} + +paper-progress { + --paper-progress-active-color: rgb(66, 133, 244); + --paper-progress-container-color: #CEE0FC; + --paper-progress-secondary-color: rgb(66, 133, 244); + display: block; + height: 3px; + padding: 4px 0 0 0; + width: 100%; +} + +#skip-button { color: rgb(66, 133, 244); } -#continueButton { +#no-thanks-button { + color: rgb(66, 133, 244); +} + +#retry-button { + -webkit-margin-end: 18px; +} + +#continue-button { -webkit-margin-end: 18px; }
diff --git a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.html b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.html index e209ae8..06630f0 100644 --- a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.html +++ b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.html
@@ -8,19 +8,43 @@ <template> <link rel="stylesheet" href="oobe_voice_interaction_value_prop.css"> <link rel="stylesheet" href="oobe_dialog_parameters.css"> - <oobe-dialog id="voice-dialog" role="dialog" hide-shadow - has-buttons no-footer-padding android> + <oobe-dialog id="voice-dialog" class="value-prop-loading" role="dialog" + hide-shadow has-buttons no-footer-padding android> <div class = "header"> - <webview id="value-prop-view"></webview> + <div id="view-container"> + <webview id="value-prop-view"></webview> + </div> + <div id="error-container"> + <div class="title" + i18n-content="voiceInteractionValuePropLoadErrorTitle"></div> + <div id="subtitle"> + <div i18n-content="voiceInteractionValuePropLoadErrorMessage"></div> + </div> + </div> + <div id="loading-container"> + <div id="loading-message"> + <div i18n-content="voiceInteractionValuePropLoading"></div> + </div> + <paper-progress class="slow" indeterminate></paper-progress> + </div> </div> <div class="bottom-buttons flex layout horizontal"> - <oobe-text-button id="noThanksButton" android on-tap="onNoThanksTap_"> - <div i18n-content="voiceInteractionValuePropNoThanksButton"></div> + <oobe-text-button id="skip-button" android on-tap="onNoThanksTap_" + disabled="[[valuePropButtonsDisabled]]"> + <div i18n-content="voiceInteractionValuePropSkipButton"></div> + </oobe-text-button> + <oobe-text-button id="no-thanks-button" android on-tap="onNoThanksTap_" + disabled="[[valuePropButtonsDisabled]]"> + <div i18n-content="voiceInteractionValuePropNoThanksButton"></div> </oobe-text-button> <div class="flex"></div> - <oobe-text-button id="continueButton" inverse android - on-tap="onContinueTap_"> - <div i18n-content="voiceInteractionValuePropContinueButton"></div> + <oobe-text-button id="retry-button" inverse android on-tap="onRetryTap_" + disabled="[[valuePropButtonsDisabled]]"> + <div i18n-content="voiceInteractionValuePropRetryButton"></div> + </oobe-text-button> + <oobe-text-button id="continue-button" inverse android + on-tap="onContinueTap_" disabled="[[valuePropButtonsDisabled]]"> + <div i18n-content="voiceInteractionValuePropContinueButton"></div> </oobe-text-button> </div> </oobe-dialog>
diff --git a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.js b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.js index 339fe66..6292871e 100644 --- a/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.js +++ b/chrome/browser/resources/chromeos/login/oobe_voice_interaction_value_prop.js
@@ -10,14 +10,75 @@ Polymer({ is: 'voice-interaction-value-prop-md', - /** - * Returns element by its id. - */ - getElement: function(id) { - return this.$[id]; + properties: { + /** + * Buttons are disabled when the value prop content is loading. + */ + valuePropButtonsDisabled: { + type: Boolean, + value: true, + }, + + /** + * System locale. + */ + locale: { + type: String, + }, + + /** + * Default url for local en. + */ + defaultUrl: { + type: String, + value: + 'https://www.gstatic.com/opa-chromeos/oobe/en/value_proposition.html', + }, }, /** + * Whether try to reload with the default url when a 404 error occurred. + * @type {boolean} + * @private + */ + reloadWithDefaultUrl_: false, + + /** + * Whether an error occurs while the webview is loading. + * @type: {boolean} + * @private + */ + valuePropError_: false, + + /** + * Timeout ID for loading animation. + * @type {number} + * @private + */ + animationTimeout_: null, + + /** + * Timeout ID for loading (will fire an error). + * @type {number} + * @private + */ + loadingTimeout_: null, + + /** + * The value prop view object. + * @type {Object} + * @private + */ + valueView_: null, + + /** + * Whether the screen has been initialized. + * @type {boolean} + * @private + */ + initialized_: false, + + /** * On-tap event handler for no thanks button. * * @private @@ -29,6 +90,15 @@ }, /** + * On-tap event handler for retry button. + * + * @private + */ + onRetryTap_: function() { + this.reloadValueProp(); + }, + + /** * On-tap event handler for continue button. * * @private @@ -38,4 +108,131 @@ 'login.VoiceInteractionValuePropScreen.userActed', ['continue-pressed']); }, + + /** + * Add class to the list of classes of root elements. + * @param {string} className class to add + * + * @private + */ + addClass_: function(className) { + this.$['voice-dialog'].classList.add(className); + }, + + /** + * Remove class to the list of classes of root elements. + * @param {string} className class to remove + * + * @private + */ + removeClass_: function(className) { + this.$['voice-dialog'].classList.remove(className); + }, + + /** + * Reloads value prop. + */ + reloadValueProp: function() { + this.valuePropError_ = false; + this.valueView_.src = 'https://www.gstatic.com/opa-chromeos/oobe/' + + this.locale + '/value_proposition.html'; + + window.clearTimeout(this.animationTimeout_); + window.clearTimeout(this.loadingTimeout_); + this.removeClass_('value-prop-loaded'); + this.removeClass_('value-prop-error'); + this.addClass_('value-prop-loading'); + this.valuePropButtonsDisabled = true; + + this.animationTimeout_ = window.setTimeout(function() { + this.addClass_('value-prop-loading-animation'); + }.bind(this), 500); + this.loadingTimeout_ = window.setTimeout(function() { + this.onValueViewErrorOccurred(); + }.bind(this), 5000); + }, + + /** + * Handles event when value prop view cannot be loaded. + */ + onValueViewErrorOccurred: function(details) { + this.valuePropError_ = true; + window.clearTimeout(this.animationTimeout_); + window.clearTimeout(this.loadingTimeout_); + this.removeClass_('value-prop-loading-animation'); + this.removeClass_('value-prop-loading'); + this.removeClass_('value-prop-loaded'); + this.addClass_('value-prop-error'); + + this.valuePropButtonsDisabled = false; + this.$['retry-button'].focus(); + }, + + /** + * Handles event when value prop view is loaded. + */ + onValueViewContentLoad: function(details) { + if (this.valuePropError_) { + return; + } + if (this.reloadWithDefaultUrl_) { + this.valueView_.src = this.defaultUrl; + this.reloadWithDefaultUrl_ = false; + return; + } + + window.clearTimeout(this.animationTimeout_); + window.clearTimeout(this.loadingTimeout_); + this.removeClass_('value-prop-loading-animation'); + this.removeClass_('value-prop-loading'); + this.removeClass_('value-prop-error'); + this.addClass_('value-prop-loaded'); + + this.valuePropButtonsDisabled = false; + this.$['continue-button'].focus(); + }, + + /** + * Handles event when webview request headers received. + */ + onValueViewHeadersReceived: function(details) { + if (details.statusCode == '404') { + if (details.url != this.defaultUrl) { + this.reloadWithDefaultUrl_ = true; + } else { + this.onValueViewErrorOccurred(); + } + } + }, + + /** + * Signal from host to show the screen. + */ + onShow: function() { + var requestFilter = {urls: ['<all_urls>'], types: ['main_frame']}; + this.valueView_ = this.$['value-prop-view']; + + if (!this.initialized_) { + this.valueView_.request.onErrorOccurred.addListener( + this.onValueViewErrorOccurred.bind(this), requestFilter); + this.valueView_.request.onHeadersReceived.addListener( + this.onValueViewHeadersReceived.bind(this), requestFilter); + this.valueView_.request.onCompleted.addListener( + this.onValueViewContentLoad.bind(this), requestFilter); + + this.valueView_.addContentScripts([{ + name: 'stripLinks', + matches: ['<all_urls>'], + js: { + code: 'document.querySelectorAll(\'a\').forEach(' + + 'function(anchor){anchor.href=\'javascript:void(0)\';})' + }, + run_at: 'document_end' + }]); + + this.initialized_ = true; + } + + this.reloadValueProp(); + }, });
diff --git a/chrome/browser/resources/chromeos/login/screen_gaia_signin.js b/chrome/browser/resources/chromeos/login/screen_gaia_signin.js index d61c68f..08a8364 100644 --- a/chrome/browser/resources/chromeos/login/screen_gaia_signin.js +++ b/chrome/browser/resources/chromeos/login/screen_gaia_signin.js
@@ -698,6 +698,8 @@ this.chromeOSApiVersion_ == 2) { this.classList.toggle('v2', true); } + if (this != Oobe.getInstance().currentScreen) + return; // Switching between signin-frame-dialog and gaia-step-contents // updates screen size. if (old_state != this.classList.contains('v2'))
diff --git a/chrome/browser/resources/md_bookmarks/constants.js b/chrome/browser/resources/md_bookmarks/constants.js index b3e0429c..2987e07 100644 --- a/chrome/browser/resources/md_bookmarks/constants.js +++ b/chrome/browser/resources/md_bookmarks/constants.js
@@ -57,5 +57,8 @@ /** @const */ var ROOT_NODE_ID = '0'; +/** @const */ +var BOOKMARKS_BAR_ID = '1'; + /** @const {number} */ var OPEN_CONFIRMATION_LIMIT = 15;
diff --git a/chrome/browser/resources/md_bookmarks/dnd_chip.html b/chrome/browser/resources/md_bookmarks/dnd_chip.html index 9703e16..cac03f1a 100644 --- a/chrome/browser/resources/md_bookmarks/dnd_chip.html +++ b/chrome/browser/resources/md_bookmarks/dnd_chip.html
@@ -9,24 +9,39 @@ <template> <style include="shared-style"> :host { - align-items: center; - background-color: var(--interactive-color); - border-radius: 20px; - box-shadow: 0 0 8px 0 rgba(0,0,0,0.12), 0 8px 8px 0 rgba(0,0,0,0.24); - display: none; - height: 40px; + --chip-height: 40px; + --chip-padding-x: 20px; + --chip-width: 172px; + left: 0; - padding: 0 20px; pointer-events: none; position: absolute; top: 0; - transform: translate( - calc(var(--mouse-x) - 50%), calc(var(--mouse-y) - 80%)); - width: 132px; + transform: translate(calc(var(--mouse-x) - var(--chip-width) * 0.5), + calc(var(--mouse-y) - var(--chip-height) * 0.8)); + z-index: 2; } - :host([showing_]) { - display: flex; + :host(:not([showing_])) { + display: none; + } + + .chip-container { + background-color: var(--interactive-color); + border-radius: calc(var(--chip-height) / 2); + box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.12), + 0 8px 8px 0 rgba(0, 0, 0, 0.24); + height: var(--chip-height); + left: 0; + padding: 0 var(--chip-padding-x); + position: absolute; + top: 0; + width: calc(var(--chip-width) - var(--chip-padding-x) * 2); + } + + #secondary { + left: 5px; + top: 5px; } #title { @@ -41,13 +56,10 @@ } #icon-wrapper { - align-items: center; background: white; border-radius: 12px; color: var(--secondary-text-color); - display: flex; height: 24px; - justify-content: center; position: relative; width: 24px; } @@ -58,13 +70,42 @@ margin: 2px; width: 16px; } + + .centered { + align-items: center; + display: flex; + justify-content: center; + } + + #count { + background: var(--google-red-500); + border-radius: 12px; + color: white; + font-weight: 500; + height: 24px; + min-width: 14px; + padding: 0 5px; + position: absolute; + right: -170px; + top: -10px; + } + + :host-context([dir='rtl']) #count { + left: 2px; + right: auto; + } </style> - <div id="icon-wrapper"> - <iron-icon id="folder-icon" icon="cr:folder" hidden$="[[!isFolder_]]"> - </iron-icon> - <div id="icon" hidden$="[[isFolder_]]"></div> + <div id="secondary" class="chip-container" hidden$="[[!isMultiItem_]]"> </div> - <div id="title"></div> + <div id="primary" class="chip-container centered"> + <div id="icon-wrapper" class="centered"> + <iron-icon id="folder-icon" icon="cr:folder" hidden$="[[!isFolder_]]"> + </iron-icon> + <div id="icon" hidden$="[[isFolder_]]"></div> + </div> + <div id="title"></div> + </div> + <div id="count" class="centered" hidden$="[[!isMultiItem_]]"></div> </template> <script src="chrome://bookmarks/dnd_chip.js"></script> <dom-module>
diff --git a/chrome/browser/resources/md_bookmarks/dnd_chip.js b/chrome/browser/resources/md_bookmarks/dnd_chip.js index 41bd942..238aa35 100644 --- a/chrome/browser/resources/md_bookmarks/dnd_chip.js +++ b/chrome/browser/resources/md_bookmarks/dnd_chip.js
@@ -14,27 +14,31 @@ /** @private */ isFolder_: Boolean, + + /** @private */ + isMultiItem_: Boolean, }, /** * @param {number} x * @param {number} y * @param {!Array<BookmarkNode>} items + * @param {!BookmarkNode} dragItem */ - showForItems: function(x, y, items) { + showForItems: function(x, y, items, dragItem) { this.style.setProperty('--mouse-x', x + 'px'); this.style.setProperty('--mouse-y', y + 'px'); if (this.showing_) return; - var firstItem = items[0]; - this.isFolder_ = !firstItem.url; - // TODO(calamity): handle multi-item UI. - if (firstItem.url) - this.$.icon.style.backgroundImage = cr.icon.getFavicon(firstItem.url); + this.isFolder_ = !dragItem.url; + this.isMultiItem_ = items.length > 1; + if (dragItem.url) + this.$.icon.style.backgroundImage = cr.icon.getFavicon(dragItem.url); - this.$.title.textContent = firstItem.title; + this.$.title.textContent = dragItem.title; + this.$.count.textContent = items.length; this.showing_ = true; },
diff --git a/chrome/browser/resources/md_bookmarks/dnd_manager.js b/chrome/browser/resources/md_bookmarks/dnd_manager.js index 587a4523..c1a7383 100644 --- a/chrome/browser/resources/md_bookmarks/dnd_manager.js +++ b/chrome/browser/resources/md_bookmarks/dnd_manager.js
@@ -295,6 +295,12 @@ * @private {BookmarksDndChipElement} */ this.chip_ = null; + + /** + * The element that initiated a drag. + * @private {BookmarkElement} + */ + this.dragElement_ = null; } DNDManager.prototype = { @@ -394,6 +400,7 @@ /** @private */ clearDragData_: function() { this.dndChip.hide(); + this.dragElement_ = null; // Defer the clearing of the data so that the bookmark manager API's drop // event doesn't clear the drop data before the web drop event has a @@ -416,6 +423,7 @@ var store = bookmarks.Store.getInstance(); var dragId = dragElement.itemId; + this.dragElement_ = dragElement; // Determine the selected bookmarks. var state = store.data; @@ -489,11 +497,13 @@ if (!this.dragInfo_.isDragValid()) return; + var state = bookmarks.Store.getInstance().data; + var items = this.dragInfo_.dragData.elements.map(function(x) { + return bookmarks.util.normalizeNode(x); + }); this.dndChip.showForItems( - e.clientX, e.clientY, - this.dragInfo_.dragData.elements.map(function(x) { - return bookmarks.util.normalizeNode(x); - })); + e.clientX, e.clientY, items, + this.dragElement_ ? state.nodes[this.dragElement_.itemId] : items[0]); var overElement = getBookmarkElement(e.path); this.autoExpander_.update(e, overElement);
diff --git a/chrome/browser/resources/md_bookmarks/item.js b/chrome/browser/resources/md_bookmarks/item.js index 7f0466f3..99c3faa 100644 --- a/chrome/browser/resources/md_bookmarks/item.js +++ b/chrome/browser/resources/md_bookmarks/item.js
@@ -148,6 +148,9 @@ * @private */ onDblClick_: function(e) { + if (!this.isSelectedItem_) + this.selectThisItem_(); + var commandManager = bookmarks.CommandManager.getInstance(); var itemSet = this.getState().selection.items; if (commandManager.canExecute(Command.OPEN, itemSet))
diff --git a/chrome/browser/resources/md_bookmarks/list.js b/chrome/browser/resources/md_bookmarks/list.js index e011bbc..7d772a19 100644 --- a/chrome/browser/resources/md_bookmarks/list.js +++ b/chrome/browser/resources/md_bookmarks/list.js
@@ -159,7 +159,7 @@ if (e.key == 'ArrowUp') { focusedIndex--; focusMoved = true; - } else if (e.key == 'ArrowDown') { + } else if (e.key == 'ArrowDown' && !(cr.isMac && e.metaKey)) { focusedIndex++; focusMoved = true; e.preventDefault();
diff --git a/chrome/browser/resources/md_bookmarks/reducers.js b/chrome/browser/resources/md_bookmarks/reducers.js index 8337e57..7154b83 100644 --- a/chrome/browser/resources/md_bookmarks/reducers.js +++ b/chrome/browser/resources/md_bookmarks/reducers.js
@@ -118,7 +118,7 @@ return { term: action.term, inProgress: true, - results: [], + results: search.results, }; }; @@ -139,7 +139,7 @@ return { term: '', inProgress: false, - results: [], + results: null, }; }; @@ -149,6 +149,9 @@ * @return {SearchState} */ SearchState.removeDeletedResults = function(search, deletedIds) { + if (!search.results) + return search; + var newResults = []; search.results.forEach(function(id) { if (!deletedIds.has(id))
diff --git a/chrome/browser/resources/md_bookmarks/router.html b/chrome/browser/resources/md_bookmarks/router.html index f9308fdc..ba6454b 100644 --- a/chrome/browser/resources/md_bookmarks/router.html +++ b/chrome/browser/resources/md_bookmarks/router.html
@@ -7,7 +7,7 @@ <dom-module id="bookmarks-router"> <template> - <iron-location query="{{query}}"></iron-location> + <iron-location query="{{query}}" dwell-time="200"></iron-location> <iron-query-params params-string="{{query}}" params-object="{{queryParams_}}"></iron-query-params> </template>
diff --git a/chrome/browser/resources/md_bookmarks/router.js b/chrome/browser/resources/md_bookmarks/router.js index 2634fb3..431331e 100644 --- a/chrome/browser/resources/md_bookmarks/router.js +++ b/chrome/browser/resources/md_bookmarks/router.js
@@ -23,15 +23,17 @@ queryParams_: Object, /** @private */ - searchTerm_: String, + searchTerm_: { + type: String, + value: '', + }, /** @private {?string} */ selectedId_: String, }, observers: [ - 'onQueryChanged_(queryParams_.q)', - 'onFolderChanged_(queryParams_.id)', + 'onQueryParamsChanged_(queryParams_)', 'onStateChanged_(searchTerm_, selectedId_)', ], @@ -46,17 +48,17 @@ }, /** @private */ - onQueryChanged_: function() { + onQueryParamsChanged_: function() { var searchTerm = this.queryParams_.q || ''; - if (searchTerm && searchTerm != this.searchTerm_) { + var selectedId = this.queryParams_.id; + if (!selectedId && !searchTerm) + selectedId = BOOKMARKS_BAR_ID; + + if (searchTerm != this.searchTerm_) { this.searchTerm_ = searchTerm; this.dispatch(bookmarks.actions.setSearchTerm(searchTerm)); } - }, - /** @private */ - onFolderChanged_: function() { - var selectedId = this.queryParams_.id; if (selectedId && selectedId != this.selectedId_) { this.selectedId_ = selectedId; // Need to dispatch a deferred action so that during page load @@ -77,7 +79,9 @@ updateQueryParams_: function() { if (this.searchTerm_) this.queryParams_ = {q: this.searchTerm_}; - else + else if (this.selectedId_ != BOOKMARKS_BAR_ID) this.queryParams_ = {id: this.selectedId_}; + else + this.queryParams_ = {}; }, });
diff --git a/chrome/browser/resources/md_bookmarks/shared_style.html b/chrome/browser/resources/md_bookmarks/shared_style.html index c73d4fc0..7f7aa8ba 100644 --- a/chrome/browser/resources/md_bookmarks/shared_style.html +++ b/chrome/browser/resources/md_bookmarks/shared_style.html
@@ -38,7 +38,7 @@ left: 0; position: absolute; right: 0; - z-index: 10; + z-index: 1; } .drag-above::before {
diff --git a/chrome/browser/resources/md_bookmarks/types.js b/chrome/browser/resources/md_bookmarks/types.js index cf857680..6361f9d 100644 --- a/chrome/browser/resources/md_bookmarks/types.js +++ b/chrome/browser/resources/md_bookmarks/types.js
@@ -37,10 +37,20 @@ var SelectionState; /** + * Note: + * - If |results| is null, it means no search results have been returned. This + * is different to |results| being [], which means the last search returned 0 + * results. + * - |term| is the last search that was performed by the user, and |results| are + * the last results that were returned from the backend. We don't clear + * |results| on incremental searches, meaning that |results| can be 'stale' + * data from a previous search term (while |inProgress| is true). If you need + * to know the exact search term used to generate |results|, you'll need to + * add a new field to the state to track it (eg, SearchState.resultsTerm). * @typedef {{ * term: string, * inProgress: boolean, - * results: !Array<string>, + * results: ?Array<string>, * }} */ var SearchState;
diff --git a/chrome/browser/resources/md_bookmarks/util.js b/chrome/browser/resources/md_bookmarks/util.js index 4b581e4..3760bde 100644 --- a/chrome/browser/resources/md_bookmarks/util.js +++ b/chrome/browser/resources/md_bookmarks/util.js
@@ -14,10 +14,10 @@ * @return {!Array<string>} */ function getDisplayedList(state) { - if (!isShowingSearch(state)) - return assert(state.nodes[state.selectedFolder].children); + if (isShowingSearch(state)) + return assert(state.search.results); - return state.search.results; + return assert(state.nodes[state.selectedFolder].children); } /** @@ -68,7 +68,7 @@ function createEmptyState() { return { nodes: {}, - selectedFolder: '0', + selectedFolder: BOOKMARKS_BAR_ID, closedFolders: new Set(), prefs: { canEdit: true, @@ -77,7 +77,7 @@ search: { term: '', inProgress: false, - results: [], + results: null, }, selection: { items: new Set(), @@ -91,7 +91,7 @@ * @return {boolean} */ function isShowingSearch(state) { - return !!state.search.term && !state.search.inProgress; + return state.search.results != null; } /**
diff --git a/chrome/browser/resources/md_extensions/animation_helper.js b/chrome/browser/resources/md_extensions/animation_helper.js index a429f184..00483b37 100644 --- a/chrome/browser/resources/md_extensions/animation_helper.js +++ b/chrome/browser/resources/md_extensions/animation_helper.js
@@ -22,24 +22,25 @@ * A helper object for setting entry/exit animations. Polymer's support of * this is pretty limited, since it doesn't allow for things like specifying * hero properties or nodes. - * @param {!HTMLElement} element The parent element to set the animations on. - * This will be used as the page in to/fromPage. - * @param {?HTMLElement} node The node to use for scaling and fading - * animations. - * @constructor */ - function AnimationHelper(element, node) { - this.element_ = element; - this.node_ = node; - element.animationConfig = {}; - } + class AnimationHelper { + /** + * @param {!HTMLElement} element The parent element to set the animations + * on. This will be used as the page in to/fromPage. + * @param {?HTMLElement} node The node to use for scaling and fading + * animations. + */ + constructor(element, node) { + this.element_ = element; + this.node_ = node; + element.animationConfig = {}; + } - AnimationHelper.prototype = { /** * Set the entry animation for the element. * @param {!Array<extensions.Animation>} animations */ - setEntryAnimations: function(animations) { + setEntryAnimations(animations) { var configs = []; for (let animation of animations) { switch (animation) { @@ -56,13 +57,13 @@ } } this.element_.animationConfig.entry = configs; - }, + } /** * Set the exit animation for the element. * @param {!Array<extensions.Animation>} animations */ - setExitAnimations: function(animations) { + setExitAnimations(animations) { var configs = []; for (let animation of animations) { switch (animation) { @@ -88,8 +89,8 @@ } } this.element_.animationConfig.exit = configs; - }, - }; + } + } return {AnimationHelper: AnimationHelper}; });
diff --git a/chrome/browser/resources/md_extensions/detail_view.html b/chrome/browser/resources/md_extensions/detail_view.html index d9fb22a..5c9c12f 100644 --- a/chrome/browser/resources/md_extensions/detail_view.html +++ b/chrome/browser/resources/md_extensions/detail_view.html
@@ -11,9 +11,8 @@ <link rel="import" href="chrome://extensions/item_util.html"> <dom-module id="extensions-detail-view"> - <style include="iron-flex"></style> <template> - <style> + <style include="iron-flex"> [hidden] { display: none !important; }
diff --git a/chrome/browser/resources/md_extensions/item.html b/chrome/browser/resources/md_extensions/item.html index 6709a81e..11c5649 100644 --- a/chrome/browser/resources/md_extensions/item.html +++ b/chrome/browser/resources/md_extensions/item.html
@@ -14,9 +14,8 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html"> <dom-module id="extensions-item"> - <style include="iron-flex"></style> <template> - <style> + <style include="iron-flex"> [hidden] { display: none !important; }
diff --git a/chrome/browser/resources/md_extensions/manager.js b/chrome/browser/resources/md_extensions/manager.js index f4070d3..4bac6d8 100644 --- a/chrome/browser/resources/md_extensions/manager.js +++ b/chrome/browser/resources/md_extensions/manager.js
@@ -422,18 +422,15 @@ } }); - /** - * @param {extensions.Manager} manager - * @constructor - * @implements {extensions.SidebarListDelegate} - */ - function ListHelper(manager) { - this.manager_ = manager; - } + /** @implements {extensions.SidebarListDelegate} */ + class ListHelper { + /** @param {extensions.Manager} manager */ + constructor(manager) { + this.manager_ = manager; + } - ListHelper.prototype = { /** @override */ - showType: function(type) { + showType(type) { var items; switch (type) { case extensions.ShowingType.EXTENSIONS: @@ -446,13 +443,13 @@ this.manager_.$ /* hack */['items-list'].set('items', assert(items)); this.manager_.changePage({page: Page.LIST}); - }, + } /** @override */ - showKeyboardShortcuts: function() { + showKeyboardShortcuts() { this.manager_.changePage({page: Page.SHORTCUTS}); - }, - }; + } + } return {Manager: Manager}; });
diff --git a/chrome/browser/resources/md_extensions/navigation_helper.js b/chrome/browser/resources/md_extensions/navigation_helper.js index 43e2382..d15ca5996 100644 --- a/chrome/browser/resources/md_extensions/navigation_helper.js +++ b/chrome/browser/resources/md_extensions/navigation_helper.js
@@ -31,26 +31,28 @@ * A helper object to manage in-page navigations. Since the extensions page * needs to support different urls for different subpages (like the details * page), we use this object to manage the history and url conversions. - * @param {!function(!PageState):void} onHistoryChange A function to call when - * the page has changed as a result of the user going back or forward in - * history; called with the new active page. - * @constructor */ - function NavigationHelper(onHistoryChange) { - this.onHistoryChange_ = onHistoryChange; - window.addEventListener('popstate', this.onPopState_.bind(this)); - } + */ + class NavigationHelper { + /** + * @param {!function(!PageState):void} onHistoryChange A function to call + * when the page has changed as a result of the user going back or + * forward in history; called with the new active page. + */ + constructor(onHistoryChange) { + this.onHistoryChange_ = onHistoryChange; + window.addEventListener('popstate', this.onPopState_.bind(this)); + } - NavigationHelper.prototype = { /** @private */ - onPopState_: function() { + onPopState_() { this.onHistoryChange_(this.getCurrentPage()); - }, + } /** - * Returns the page that should be displayed for the current URL. - * @return {!PageState} + * @return {!PageState} The page that should be displayed for the current + * URL. */ - getCurrentPage: function() { + getCurrentPage() { var search = new URLSearchParams(location.search); var id = search.get('id'); if (id) @@ -66,13 +68,13 @@ return {page: Page.SHORTCUTS}; return {page: Page.LIST}; - }, + } /** * Called when a page changes, and pushes state to history to reflect it. * @param {!PageState} entry */ - updateHistory: function(entry) { + updateHistory(entry) { var path; switch (entry.page) { case Page.LIST: @@ -106,8 +108,8 @@ history.replaceState(state, '', path); else history.pushState(state, '', path); - }, - }; + } + } return {NavigationHelper: NavigationHelper}; });
diff --git a/chrome/browser/resources/md_extensions/service.js b/chrome/browser/resources/md_extensions/service.js index c65380f..9694a3a 100644 --- a/chrome/browser/resources/md_extensions/service.js +++ b/chrome/browser/resources/md_extensions/service.js
@@ -6,22 +6,26 @@ 'use strict'; /** - * @constructor * @implements {extensions.ErrorPageDelegate} * @implements {extensions.ItemDelegate} * @implements {extensions.LoadErrorDelegate} * @implements {extensions.PackDialogDelegate} * @implements {extensions.ToolbarDelegate} */ - function Service() {} + class Service { + constructor() { + /** @private {boolean} */ + this.isDeleting_ = false; - Service.prototype = { - /** @private {boolean} */ - isDeleting_: false, + /** @private {extensions.Manager} */ + this.manager_; + + /** @private {Array<chrome.developerPrivate.ExtensionInfo>} */ + this.extensions_; + } /** @param {extensions.Manager} manager */ - managerReady: function(manager) { - /** @private {extensions.Manager} */ + managerReady(manager) { this.manager_ = manager; this.manager_.toolbar.setDelegate(this); this.manager_.set('itemDelegate', this); @@ -44,7 +48,6 @@ chrome.developerPrivate.getExtensionsInfo( {includeDisabled: true, includeTerminated: true}, function(extensions) { - /** @private {Array<chrome.developerPrivate.ExtensionInfo>} */ this.extensions_ = extensions; for (let extension of extensions) this.manager_.addItem(extension); @@ -53,21 +56,21 @@ }.bind(this)); chrome.developerPrivate.getProfileConfiguration( this.onProfileStateChanged_.bind(this)); - }, + } /** * @param {chrome.developerPrivate.ProfileInfo} profileInfo * @private */ - onProfileStateChanged_: function(profileInfo) { + onProfileStateChanged_(profileInfo) { this.manager_.set('inDevMode', profileInfo.inDeveloperMode); - }, + } /** * @param {chrome.developerPrivate.EventData} eventData * @private */ - onItemStateChanged_: function(eventData) { + onItemStateChanged_(eventData) { var currentIndex = this.extensions_.findIndex(function(extension) { return extension.id == eventData.item_id; }); @@ -103,7 +106,7 @@ default: assertNotReached(); } - }, + } /** * Opens a file browser dialog for the user to select a file (or directory). @@ -112,7 +115,7 @@ * @return {Promise<string>} The promise to be resolved with the selected * path. */ - chooseFilePath_: function(selectType, fileType) { + chooseFilePath_(selectType, fileType) { return new Promise(function(resolve, reject) { chrome.developerPrivate.choosePath( selectType, fileType, function(path) { @@ -124,20 +127,20 @@ } }); }); - }, + } /** * Updates an extension command. * @param {!CustomEvent} e * @private */ - onExtensionCommandUpdated_: function(e) { + onExtensionCommandUpdated_(e) { chrome.developerPrivate.updateExtensionCommand({ extensionId: e.detail.item, commandName: e.detail.commandName, keybinding: e.detail.keybinding, }); - }, + } /** * Called when shortcut capturing changes in order to suspend or re-enable @@ -150,9 +153,9 @@ * @param {!CustomEvent} e * @private */ - onShortcutCaptureChanged_: function(isCapturing, e) { + onShortcutCaptureChanged_(isCapturing, e) { chrome.developerPrivate.setShortcutHandlingSuspended(isCapturing); - }, + } /** * Attempts to load an unpacked extension, optionally as another attempt at @@ -160,7 +163,7 @@ * @param {string=} opt_retryGuid * @private */ - loadUnpackedHelper_: function(opt_retryGuid) { + loadUnpackedHelper_(opt_retryGuid) { chrome.developerPrivate.loadUnpacked( {failQuietly: true, populateError: true, retryGuid: opt_retryGuid}, (loadError) => { @@ -174,10 +177,10 @@ this.manager_.loadError.show(); } }); - }, + } /** @override */ - deleteItem: function(id) { + deleteItem(id) { if (this.isDeleting_) return; this.isDeleting_ = true; @@ -188,67 +191,67 @@ chrome.runtime.lastError; this.isDeleting_ = false; }.bind(this)); - }, + } /** @override */ - setItemEnabled: function(id, isEnabled) { + setItemEnabled(id, isEnabled) { chrome.management.setEnabled(id, isEnabled); - }, + } /** @override */ - setItemAllowedIncognito: function(id, isAllowedIncognito) { + setItemAllowedIncognito(id, isAllowedIncognito) { chrome.developerPrivate.updateExtensionConfiguration({ extensionId: id, incognitoAccess: isAllowedIncognito, }); - }, + } /** @override */ - setItemAllowedOnFileUrls: function(id, isAllowedOnFileUrls) { + setItemAllowedOnFileUrls(id, isAllowedOnFileUrls) { chrome.developerPrivate.updateExtensionConfiguration({ extensionId: id, fileAccess: isAllowedOnFileUrls, }); - }, + } /** @override */ - setItemAllowedOnAllSites: function(id, isAllowedOnAllSites) { + setItemAllowedOnAllSites(id, isAllowedOnAllSites) { chrome.developerPrivate.updateExtensionConfiguration({ extensionId: id, runOnAllUrls: isAllowedOnAllSites, }); - }, + } /** @override */ - setItemCollectsErrors: function(id, collectsErrors) { + setItemCollectsErrors(id, collectsErrors) { chrome.developerPrivate.updateExtensionConfiguration({ extensionId: id, errorCollection: collectsErrors, }); - }, + } /** @override */ - inspectItemView: function(id, view) { + inspectItemView(id, view) { chrome.developerPrivate.openDevTools({ extensionId: id, renderProcessId: view.renderProcessId, renderViewId: view.renderViewId, incognito: view.incognito, }); - }, + } /** @override */ - reloadItem: function(id) { + reloadItem(id) { chrome.developerPrivate.reload(id, {failQuietly: false}); - }, + } /** @override */ - repairItem: function(id) { + repairItem(id) { chrome.developerPrivate.repairExtension(id); - }, + } /** @override */ - showItemOptionsPage: function(id) { + showItemOptionsPage(id) { var extension = this.extensions_.find(function(e) { return e.id == id; }); @@ -259,66 +262,66 @@ this.manager_.changePage( {page: Page.DETAILS, subpage: Dialog.OPTIONS, extensionId: id}); } - }, + } /** @override */ - setProfileInDevMode: function(inDevMode) { + setProfileInDevMode(inDevMode) { chrome.developerPrivate.updateProfileConfiguration( {inDeveloperMode: inDevMode}); - }, + } /** @override */ - loadUnpacked: function() { + loadUnpacked() { this.loadUnpackedHelper_(); - }, + } /** @override */ - retryLoadUnpacked: function(retryGuid) { + retryLoadUnpacked(retryGuid) { this.loadUnpackedHelper_(retryGuid); - }, + } /** @override */ - choosePackRootDirectory: function() { + choosePackRootDirectory() { return this.chooseFilePath_( chrome.developerPrivate.SelectType.FOLDER, chrome.developerPrivate.FileType.LOAD); - }, + } /** @override */ - choosePrivateKeyPath: function() { + choosePrivateKeyPath() { return this.chooseFilePath_( chrome.developerPrivate.SelectType.FILE, chrome.developerPrivate.FileType.PEM); - }, + } /** @override */ - packExtension: function(rootPath, keyPath) { + packExtension(rootPath, keyPath) { chrome.developerPrivate.packDirectory(rootPath, keyPath); - }, + } /** @override */ - updateAllExtensions: function() { + updateAllExtensions() { chrome.developerPrivate.autoUpdate(); - }, + } /** @override */ - deleteErrors: function(extensionId, errorIds, type) { + deleteErrors(extensionId, errorIds, type) { chrome.developerPrivate.deleteExtensionErrors({ extensionId: extensionId, errorIds: errorIds, type: type, }); - }, + } /** @override */ - requestFileSource: function(args) { + requestFileSource(args) { return new Promise(function(resolve, reject) { chrome.developerPrivate.requestFileSource(args, function(code) { resolve(code); }); }); - }, - }; + } + } cr.addSingletonGetter(Service);
diff --git a/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html b/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html index acd4920b..79bf12d 100644 --- a/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html +++ b/chrome/browser/resources/settings/bluetooth_page/bluetooth_device_list_item.html
@@ -8,16 +8,16 @@ <link rel="import" href="../settings_shared_css.html"> <dom-module id="bluetooth-device-list-item"> - <style include="settings-shared"> - .name[connected] { - font-weight: 500; - } - - .state[connected] { - color: var(--google-green-500); - } - </style> <template> + <style include="settings-shared"> + .name[connected] { + font-weight: 500; + } + + .state[connected] { + color: var(--google-green-500); + } + </style> <div class="list-item"> <iron-icon id="deviceIcon" icon="[[getDeviceIcon_(device)]]"> </iron-icon>
diff --git a/chrome/browser/resources/settings/compiled_resources2.gyp b/chrome/browser/resources/settings/compiled_resources2.gyp index 836fde5..a3f4a15 100644 --- a/chrome/browser/resources/settings/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/compiled_resources2.gyp
@@ -6,7 +6,6 @@ { 'target_name': 'direction_delegate', 'dependencies': [ - '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', ],
diff --git a/chrome/browser/resources/settings/controls/settings_radio_group.html b/chrome/browser/resources/settings/controls/settings_radio_group.html index 9d6bf89..9463920f 100644 --- a/chrome/browser/resources/settings/controls/settings_radio_group.html +++ b/chrome/browser/resources/settings/controls/settings_radio_group.html
@@ -7,8 +7,8 @@ <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-radio-group"> - <style include="settings-shared"></style> <template> + <style include="settings-shared"></style> <div>[[label]]</div> <paper-radio-group selected="{{selected}}" selectable="paper-radio-button, controlled-radio-button">
diff --git a/chrome/browser/resources/settings/direction_delegate.js b/chrome/browser/resources/settings/direction_delegate.js index 3b8020a..6d52753 100644 --- a/chrome/browser/resources/settings/direction_delegate.js +++ b/chrome/browser/resources/settings/direction_delegate.js
@@ -4,26 +4,26 @@ cr.exportPath('settings'); -/** @interface */ -settings.DirectionDelegate = function() {}; +cr.define('settings', function() { + /** @interface */ + class DirectionDelegate { + /** + * @return {boolean} Whether the direction of the settings UI is + * right-to-left. + */ + isRtl() {} + } -settings.DirectionDelegate.prototype = { - /** - * @return {boolean} Whether the direction of the settings UI is - * right-to-left. - */ - isRtl: assertNotReached, -}; + /** @implements {settings.DirectionDelegate} */ + class DirectionDelegateImpl { + /** @override */ + isRtl() { + return loadTimeData.getString('textdirection') == 'rtl'; + } + } -/** - * @implements {settings.DirectionDelegate} - * @constructor - */ -settings.DirectionDelegateImpl = function() {}; - -settings.DirectionDelegateImpl.prototype = { - /** @override */ - isRtl: function() { - return loadTimeData.getString('textdirection') == 'rtl'; - }, -}; + return { + DirectionDelegate: DirectionDelegate, + DirectionDelegateImpl: DirectionDelegateImpl, + }; +});
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js b/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js index ca28ebf..ed4ac43 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/address_edit_dialog.js
@@ -200,32 +200,33 @@ cr.define('settings.address', function() { /** * Creates a wrapper against a single data member for an address. - * @param {!chrome.autofillPrivate.AddressEntry} address - * @param {!chrome.autofillPrivate.AddressComponent} component - * @constructor */ - function AddressComponentUI(address, component) { - Object.defineProperty(this, 'value', { - get: function() { - return this.getValue_(); - }, - set: function(newValue) { - this.setValue_(newValue); - }, - }); - this.address_ = address; - this.component = component; - this.isTextArea = - component.field == chrome.autofillPrivate.AddressField.ADDRESS_LINES; - } + class AddressComponentUI { + /** + * @param {!chrome.autofillPrivate.AddressEntry} address + * @param {!chrome.autofillPrivate.AddressComponent} component + */ + constructor(address, component) { + Object.defineProperty(this, 'value', { + get: function() { + return this.getValue_(); + }, + set: function(newValue) { + this.setValue_(newValue); + }, + }); + this.address_ = address; + this.component = component; + this.isTextArea = + component.field == chrome.autofillPrivate.AddressField.ADDRESS_LINES; + } - AddressComponentUI.prototype = { /** * Gets the value from the address that's associated with this component. * @return {string|undefined} * @private */ - getValue_: function() { + getValue_() { var address = this.address_; switch (this.component.field) { case chrome.autofillPrivate.AddressField.FULL_NAME: @@ -251,14 +252,14 @@ default: assertNotReached(); } - }, + } /** * Sets the value in the address that's associated with this component. * @param {string} value * @private */ - setValue_: function(value) { + setValue_(value) { var address = this.address_; switch (this.component.field) { case chrome.autofillPrivate.AddressField.FULL_NAME: @@ -291,52 +292,48 @@ default: assertNotReached(); } - }, - }; + } + } /** @interface */ - function CountryDetailManager() {} - CountryDetailManager.prototype = { + class CountryDetailManager { /** * Gets the list of available countries. * The default country will be first, followed by a separator, followed by * an alphabetized list of countries available. * @return {!Promise<!Array<!chrome.autofillPrivate.CountryEntry>>} */ - getCountryList: assertNotReached, + getCountryList() {} /** * Gets the address format for a given country code. * @param {string} countryCode * @return {!Promise<!chrome.autofillPrivate.AddressComponents>} */ - getAddressFormat: assertNotReached, - }; + getAddressFormat(countryCode) {} + } /** * Default implementation. Override for testing. * @implements {settings.address.CountryDetailManager} - * @constructor */ - function CountryDetailManagerImpl() {} - cr.addSingletonGetter(CountryDetailManagerImpl); - CountryDetailManagerImpl.prototype = { - __proto__: CountryDetailManager, - + class CountryDetailManagerImpl { /** @override */ - getCountryList: function() { + getCountryList() { return new Promise(function(callback) { chrome.autofillPrivate.getCountryList(callback); }); - }, + } /** @override */ - getAddressFormat: function(countryCode) { + getAddressFormat(countryCode) { return new Promise(function(callback) { chrome.autofillPrivate.getAddressComponents(countryCode, callback); }); - }, - }; + } + } + + cr.addSingletonGetter(CountryDetailManagerImpl); return { AddressComponentUI: AddressComponentUI,
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js index 0a7dff7..76f7afa 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/autofill_section.js
@@ -11,7 +11,64 @@ * Interface for all callbacks to the autofill API. * @interface */ -function AutofillManager() {} +class AutofillManager { + /** + * Add an observer to the list of addresses. + * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener + */ + addAddressListChangedListener(listener) {} + + /** + * Remove an observer from the list of addresses. + * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener + */ + removeAddressListChangedListener(listener) {} + + /** + * Request the list of addresses. + * @param {function(!Array<!AutofillManager.AddressEntry>):void} callback + */ + getAddressList(callback) {} + + /** + * Saves the given address. + * @param {!AutofillManager.AddressEntry} address + */ + saveAddress(address) {} + + /** @param {string} guid The guid of the address to remove. */ + removeAddress(guid) {} + + /** + * Add an observer to the list of credit cards. + * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener + */ + addCreditCardListChangedListener(listener) {} + + /** + * Remove an observer from the list of credit cards. + * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener + */ + removeCreditCardListChangedListener(listener) {} + + /** + * Request the list of credit cards. + * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} callback + */ + getCreditCardList(callback) {} + + /** @param {string} guid The GUID of the credit card to remove. */ + removeCreditCard(guid) {} + + /** @param {string} guid The GUID to credit card to remove from the cache. */ + clearCachedCreditCard(guid) {} + + /** + * Saves the given credit card. + * @param {!AutofillManager.CreditCardEntry} creditCard + */ + saveCreditCard(creditCard) {} +} /** @typedef {chrome.autofillPrivate.AddressEntry} */ AutofillManager.AddressEntry; @@ -19,131 +76,68 @@ /** @typedef {chrome.autofillPrivate.CreditCardEntry} */ AutofillManager.CreditCardEntry; -AutofillManager.prototype = { - /** - * Add an observer to the list of addresses. - * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener - */ - addAddressListChangedListener: assertNotReached, - - /** - * Remove an observer from the list of addresses. - * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener - */ - removeAddressListChangedListener: assertNotReached, - - /** - * Request the list of addresses. - * @param {function(!Array<!AutofillManager.AddressEntry>):void} callback - */ - getAddressList: assertNotReached, - - /** - * Saves the given address. - * @param {!AutofillManager.AddressEntry} address - */ - saveAddress: assertNotReached, - - /** @param {string} guid The guid of the address to remove. */ - removeAddress: assertNotReached, - - /** - * Add an observer to the list of credit cards. - * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener - */ - addCreditCardListChangedListener: assertNotReached, - - /** - * Remove an observer from the list of credit cards. - * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener - */ - removeCreditCardListChangedListener: assertNotReached, - - /** - * Request the list of credit cards. - * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} callback - */ - getCreditCardList: assertNotReached, - - /** @param {string} guid The GUID of the credit card to remove. */ - removeCreditCard: assertNotReached, - - /** @param {string} guid The GUID to credit card to remove from the cache. */ - clearCachedCreditCard: assertNotReached, - - /** - * Saves the given credit card. - * @param {!AutofillManager.CreditCardEntry} creditCard - */ - saveCreditCard: assertNotReached, -}; - /** * Implementation that accesses the private API. * @implements {AutofillManager} - * @constructor */ -function AutofillManagerImpl() {} -cr.addSingletonGetter(AutofillManagerImpl); - -AutofillManagerImpl.prototype = { - __proto__: AutofillManager, - +class AutofillManagerImpl { /** @override */ - addAddressListChangedListener: function(listener) { + addAddressListChangedListener(listener) { chrome.autofillPrivate.onAddressListChanged.addListener(listener); - }, + } /** @override */ - removeAddressListChangedListener: function(listener) { + removeAddressListChangedListener(listener) { chrome.autofillPrivate.onAddressListChanged.removeListener(listener); - }, + } /** @override */ - getAddressList: function(callback) { + getAddressList(callback) { chrome.autofillPrivate.getAddressList(callback); - }, + } /** @override */ - saveAddress: function(address) { + saveAddress(address) { chrome.autofillPrivate.saveAddress(address); - }, + } /** @override */ - removeAddress: function(guid) { + removeAddress(guid) { chrome.autofillPrivate.removeEntry(assert(guid)); - }, + } /** @override */ - addCreditCardListChangedListener: function(listener) { + addCreditCardListChangedListener(listener) { chrome.autofillPrivate.onCreditCardListChanged.addListener(listener); - }, + } /** @override */ - removeCreditCardListChangedListener: function(listener) { + removeCreditCardListChangedListener(listener) { chrome.autofillPrivate.onCreditCardListChanged.removeListener(listener); - }, + } /** @override */ - getCreditCardList: function(callback) { + getCreditCardList(callback) { chrome.autofillPrivate.getCreditCardList(callback); - }, + } /** @override */ - removeCreditCard: function(guid) { + removeCreditCard(guid) { chrome.autofillPrivate.removeEntry(assert(guid)); - }, + } /** @override */ - clearCachedCreditCard: function(guid) { + clearCachedCreditCard(guid) { chrome.autofillPrivate.maskCreditCard(assert(guid)); - }, + } /** @override */ - saveCreditCard: function(creditCard) { + saveCreditCard(creditCard) { chrome.autofillPrivate.saveCreditCard(creditCard); } -}; +} + +cr.addSingletonGetter(AutofillManagerImpl); (function() { 'use strict';
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html b/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html index 11d65df..d230f3a 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html +++ b/chrome/browser/resources/settings/passwords_and_forms_page/credit_card_edit_dialog.html
@@ -9,46 +9,46 @@ <link rel="import" href="../settings_shared_css.html"> <dom-module id="settings-credit-card-edit-dialog"> - <style include="settings-shared md-select"> - paper-input { - width: var(--paper-input-max-width); - } - - .md-select-wrapper { - /* Mitigate for md-select's start padding, to make it look aligned with - * other elements on the page. */ - -webkit-margin-start: calc(-1 * var(--md-select-side-padding)); - } - - .md-select-wrapper + .md-select-wrapper { - -webkit-margin-start: 8px; - } - - #expired { - align-items: center; - background-color: var(--paper-red-50); - color: var(--settings-error-color); - display: flex; - height: 40px; - margin-top: 12px; - padding: 0 0 0 8px; - } - - #month { - width: 70px; - } - - #year { - width: 100px; - } - - label { - color: var(--light-theme-secondary-color); - display: block; - padding-top: 8px; - } - </style> <template> + <style include="settings-shared md-select"> + paper-input { + width: var(--paper-input-max-width); + } + + .md-select-wrapper { + /* Mitigate for md-select's start padding, to make it look aligned with + * other elements on the page. */ + -webkit-margin-start: calc(-1 * var(--md-select-side-padding)); + } + + .md-select-wrapper + .md-select-wrapper { + -webkit-margin-start: 8px; + } + + #expired { + align-items: center; + background-color: var(--paper-red-50); + color: var(--settings-error-color); + display: flex; + height: 40px; + margin-top: 12px; + padding: 0 0 0 8px; + } + + #month { + width: 70px; + } + + #year { + width: 100px; + } + + label { + color: var(--light-theme-secondary-color); + display: block; + padding-top: 8px; + } + </style> <dialog is="cr-dialog" id="dialog" close-text="$i18n{close}"> <div class="title">[[title_]]</div> <div class="body">
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js index 2cf10b1..f47dbec 100644 --- a/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js +++ b/chrome/browser/resources/settings/passwords_and_forms_page/passwords_section.js
@@ -12,7 +12,65 @@ * Interface for all callbacks to the password API. * @interface */ -function PasswordManager() {} +class PasswordManager { + /** + * Add an observer to the list of saved passwords. + * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} listener + */ + addSavedPasswordListChangedListener(listener) {} + + /** + * Remove an observer from the list of saved passwords. + * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} listener + */ + removeSavedPasswordListChangedListener(listener) {} + + /** + * Request the list of saved passwords. + * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} callback + */ + getSavedPasswordList(callback) {} + + /** + * Should remove the saved password and notify that the list has changed. + * @param {!PasswordManager.LoginPair} loginPair The saved password that + * should be removed from the list. No-op if |loginPair| is not found. + */ + removeSavedPassword(loginPair) {} + + /** + * Add an observer to the list of password exceptions. + * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} listener + */ + addExceptionListChangedListener(listener) {} + + /** + * Remove an observer from the list of password exceptions. + * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} listener + */ + removeExceptionListChangedListener(listener) {} + + /** + * Request the list of password exceptions. + * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} callback + */ + getExceptionList(callback) {} + + /** + * Should remove the password exception and notify that the list has changed. + * @param {string} exception The exception that should be removed from the + * list. No-op if |exception| is not in the list. + */ + removeException(exception) {} + + /** + * Gets the saved password for a given login pair. + * @param {!PasswordManager.LoginPair} loginPair The saved password that + * should be retrieved. + * @param {function(!PasswordManager.PlaintextPasswordEvent):void} callback + */ + getPlaintextPassword(loginPair, callback) {} +} /** @typedef {chrome.passwordsPrivate.PasswordUiEntry} */ PasswordManager.PasswordUiEntry; @@ -26,122 +84,56 @@ /** @typedef {chrome.passwordsPrivate.PlaintextPasswordEventParameters} */ PasswordManager.PlaintextPasswordEvent; -PasswordManager.prototype = { - /** - * Add an observer to the list of saved passwords. - * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} listener - */ - addSavedPasswordListChangedListener: assertNotReached, - - /** - * Remove an observer from the list of saved passwords. - * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} listener - */ - removeSavedPasswordListChangedListener: assertNotReached, - - /** - * Request the list of saved passwords. - * @param {function(!Array<!PasswordManager.PasswordUiEntry>):void} callback - */ - getSavedPasswordList: assertNotReached, - - /** - * Should remove the saved password and notify that the list has changed. - * @param {!PasswordManager.LoginPair} loginPair The saved password that - * should be removed from the list. No-op if |loginPair| is not found. - */ - removeSavedPassword: assertNotReached, - - /** - * Add an observer to the list of password exceptions. - * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} listener - */ - addExceptionListChangedListener: assertNotReached, - - /** - * Remove an observer from the list of password exceptions. - * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} listener - */ - removeExceptionListChangedListener: assertNotReached, - - /** - * Request the list of password exceptions. - * @param {function(!Array<!PasswordManager.ExceptionEntry>):void} callback - */ - getExceptionList: assertNotReached, - - /** - * Should remove the password exception and notify that the list has changed. - * @param {string} exception The exception that should be removed from the - * list. No-op if |exception| is not in the list. - */ - removeException: assertNotReached, - - /** - * Gets the saved password for a given login pair. - * @param {!PasswordManager.LoginPair} loginPair The saved password that - * should be retrieved. - * @param {function(!PasswordManager.PlaintextPasswordEvent):void} callback - */ - getPlaintextPassword: assertNotReached, -}; - /** * Implementation that accesses the private API. * @implements {PasswordManager} - * @constructor */ -function PasswordManagerImpl() {} -cr.addSingletonGetter(PasswordManagerImpl); - -PasswordManagerImpl.prototype = { - __proto__: PasswordManager, - +class PasswordManagerImpl { /** @override */ - addSavedPasswordListChangedListener: function(listener) { + addSavedPasswordListChangedListener(listener) { chrome.passwordsPrivate.onSavedPasswordsListChanged.addListener(listener); - }, + } /** @override */ - removeSavedPasswordListChangedListener: function(listener) { + removeSavedPasswordListChangedListener(listener) { chrome.passwordsPrivate.onSavedPasswordsListChanged.removeListener( listener); - }, + } /** @override */ - getSavedPasswordList: function(callback) { + getSavedPasswordList(callback) { chrome.passwordsPrivate.getSavedPasswordList(callback); - }, + } /** @override */ - removeSavedPassword: function(loginPair) { + removeSavedPassword(loginPair) { chrome.passwordsPrivate.removeSavedPassword(loginPair); - }, + } /** @override */ - addExceptionListChangedListener: function(listener) { + addExceptionListChangedListener(listener) { chrome.passwordsPrivate.onPasswordExceptionsListChanged.addListener( listener); - }, + } /** @override */ - removeExceptionListChangedListener: function(listener) { + removeExceptionListChangedListener(listener) { chrome.passwordsPrivate.onPasswordExceptionsListChanged.removeListener( listener); - }, + } /** @override */ - getExceptionList: function(callback) { + getExceptionList(callback) { chrome.passwordsPrivate.getPasswordExceptionList(callback); - }, + } /** @override */ - removeException: function(exception) { + removeException(exception) { chrome.passwordsPrivate.removePasswordException(exception); - }, + } /** @override */ - getPlaintextPassword: function(loginPair, callback) { + getPlaintextPassword(loginPair, callback) { var listener = function(reply) { // Only handle the reply for our loginPair request. if (reply.loginPair.urls.origin == loginPair.urls.origin && @@ -153,8 +145,10 @@ }; chrome.passwordsPrivate.onPlaintextPasswordRetrieved.addListener(listener); chrome.passwordsPrivate.requestPlaintextPassword(loginPair); - }, -}; + } +} + +cr.addSingletonGetter(PasswordManagerImpl); /** @typedef {!{model: !{item: !chrome.passwordsPrivate.PasswordUiEntry}}} */ var PasswordUiEntryEvent;
diff --git a/chrome/browser/resources/settings/site_settings/cookie_tree_node.js b/chrome/browser/resources/settings/site_settings/cookie_tree_node.js index 809ee7f..2e27145 100644 --- a/chrome/browser/resources/settings/site_settings/cookie_tree_node.js +++ b/chrome/browser/resources/settings/site_settings/cookie_tree_node.js
@@ -59,24 +59,21 @@ cr.define('settings', function() { 'use strict'; - /** - * @constructor - */ - function CookieTreeNode(data) { - /** - * The data for this cookie node. - * @type {CookieDetails} - */ - this.data = data; + class CookieTreeNode { + constructor(data) { + /** + * The data for this cookie node. + * @type {CookieDetails} + */ + this.data = data; - /** - * The child cookie nodes. - * @private {!Array<!settings.CookieTreeNode>} - */ - this.children_ = []; - } + /** + * The child cookie nodes. + * @private {!Array<!settings.CookieTreeNode>} + */ + this.children_ = []; + } - CookieTreeNode.prototype = { /** * Converts a list of cookies and add them as CookieTreeNode children to * the given parent node. @@ -85,12 +82,12 @@ * @param {!Array<!CookieDetails>} newNodes The list containing the data to * add. */ - addChildNodes: function(parentNode, newNodes) { + addChildNodes(parentNode, newNodes) { var nodes = newNodes.map(function(x) { return new settings.CookieTreeNode(x); }); parentNode.children_ = nodes; - }, + } /** * Looks up a parent node and adds a list of CookieTreeNodes to them. @@ -101,7 +98,7 @@ add. * @return {boolean} True if the parent node was found. */ - populateChildNodes: function(parentId, startingNode, newNodes) { + populateChildNodes(parentId, startingNode, newNodes) { for (var i = 0; i < startingNode.children_.length; ++i) { if (startingNode.children_[i].data.id == parentId) { this.addChildNodes(startingNode.children_[i], newNodes); @@ -114,7 +111,7 @@ } } return false; - }, + } /** * Removes child nodes from a node with a given id. @@ -123,16 +120,16 @@ * from. * @param {number} count The number of children to delete. */ - removeByParentId: function(id, firstChild, count) { + removeByParentId(id, firstChild, count) { var node = id == null ? this : this.fetchNodeById(id, true); node.children_.splice(firstChild, count); - }, + } /** * Returns an array of cookies from the current node within the cookie tree. * @return {!Array<!CookieDataItem>} The Cookie List. */ - getCookieList: function() { + getCookieList() { var list = []; for (var i = 0; i < this.children_.length; i++) { var child = this.children_[i]; @@ -147,13 +144,13 @@ } return list; - }, + } /** * Get a summary list of all sites and their stored data. * @return {!Array<!CookieDataSummaryItem>} The summary list. */ - getSummaryList: function() { + getSummaryList() { var list = []; for (var i = 0; i < this.children_.length; ++i) { var siteEntry = this.children_[i]; @@ -194,7 +191,7 @@ return a.site.localeCompare(b.site); }); return list; - }, + } /** * Fetch a CookieTreeNode by ID. @@ -202,7 +199,7 @@ * @param {boolean} recursive Whether to search the children also. * @return {settings.CookieTreeNode} The node found, if any. */ - fetchNodeById: function(id, recursive) { + fetchNodeById(id, recursive) { for (var i = 0; i < this.children_.length; ++i) { if (this.children_[i] == null) return null; @@ -215,21 +212,21 @@ } } return null; - }, + } /** * Fetch a CookieTreeNode by site. * @param {string} site The web site to look up. * @return {?settings.CookieTreeNode} The node found, if any. */ - fetchNodeBySite: function(site) { + fetchNodeBySite(site) { for (var i = 0; i < this.children_.length; ++i) { if (this.children_[i].data.title == site) return this.children_[i]; } return null; - }, - }; + } + } return { CookieTreeNode: CookieTreeNode,
diff --git a/chrome/browser/search_engines/template_url_service_android.cc b/chrome/browser/search_engines/template_url_service_android.cc index 5005697..0fd162fb 100644 --- a/chrome/browser/search_engines/template_url_service_android.cc +++ b/chrome/browser/search_engines/template_url_service_android.cc
@@ -8,11 +8,13 @@ #include "base/android/jni_string.h" #include "base/bind.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 "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search_engines/template_url_service_factory.h" +#include "chrome/common/chrome_switches.h" #include "components/google/core/browser/google_util.h" #include "components/search_engines/search_terms_data.h" #include "components/search_engines/template_url.h" @@ -121,6 +123,11 @@ jboolean TemplateUrlServiceAndroid::DoesDefaultSearchEngineHaveLogo( JNIEnv* env, const JavaParamRef<jobject>& obj) { + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kSearchProviderLogoURL)) { + return true; + } + if (IsDefaultSearchEngineGoogle(env, obj)) return true;
diff --git a/chrome/browser/sessions/session_restore.cc b/chrome/browser/sessions/session_restore.cc index 49831a2..05a2a10 100644 --- a/chrome/browser/sessions/session_restore.cc +++ b/chrome/browser/sessions/session_restore.cc
@@ -855,6 +855,12 @@ // static void SessionRestore::AddURLsToOpen(const Profile* profile, const std::vector<GURL>& urls) { + // TODO(eugenebng@yandex-team.ru): crbug/735958 fix callers to not + // call this without session restorers, or reword the NOTREACHED + // assertion to explain why it is OK ignore URLs to open when there + // are no active session restorers. + if (!active_session_restorers) + return; for (auto* session_restorer : *active_session_restorers) { if (session_restorer->profile() == profile) { session_restorer->AddURLsToOpen(urls);
diff --git a/chrome/browser/supervised_user/legacy/supervised_user_registration_utility.cc b/chrome/browser/supervised_user/legacy/supervised_user_registration_utility.cc index 2fa9ccd..243754a5 100644 --- a/chrome/browser/supervised_user/legacy/supervised_user_registration_utility.cc +++ b/chrome/browser/supervised_user/legacy/supervised_user_registration_utility.cc
@@ -153,14 +153,14 @@ // static std::unique_ptr<SupervisedUserRegistrationUtility> SupervisedUserRegistrationUtility::Create(Profile* profile) { + DCHECK(base::FeatureList::IsEnabled(features::kSupervisedUserCreation)); + if (g_instance_for_tests) { SupervisedUserRegistrationUtility* result = g_instance_for_tests; g_instance_for_tests = NULL; return base::WrapUnique(result); } - DCHECK(base::FeatureList::IsEnabled(features::kSupervisedUserCreation)); - ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile); SigninManagerBase* signin_manager =
diff --git a/chrome/browser/thumbnails/simple_thumbnail_crop.h b/chrome/browser/thumbnails/simple_thumbnail_crop.h deleted file mode 100644 index c80721cc..0000000 --- a/chrome/browser/thumbnails/simple_thumbnail_crop.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_THUMBNAILS_SIMPLE_THUMBNAIL_CROP_H_ -#define CHROME_BROWSER_THUMBNAILS_SIMPLE_THUMBNAIL_CROP_H_ - -#include "base/macros.h" -#include "chrome/browser/thumbnails/thumbnailing_algorithm.h" - -namespace thumbnails { - -// The implementation of the 'classic' thumbnail cropping algorithm. It is not -// content-driven in any meaningful way (save for score calculation). Rather, -// the choice of a cropping region is based on relation between source and -// target sizes. The selected source region is then rescaled into the target -// thumbnail image. -class SimpleThumbnailCrop : public ThumbnailingAlgorithm { - public: - explicit SimpleThumbnailCrop(const gfx::Size& target_size); - - ClipResult GetCanvasCopyInfo(const gfx::Size& source_size, - ui::ScaleFactor scale_factor, - gfx::Rect* clipping_rect, - gfx::Size* copy_size) const override; - - // Returns the size copied from the backing store. |thumbnail_size| is in - // DIP, returned size in pixels. - static gfx::Size GetCopySizeForThumbnail(ui::ScaleFactor scale_factor, - const gfx::Size& thumbnail_size); - static gfx::Rect GetClippingRect(const gfx::Size& source_size, - const gfx::Size& desired_size, - ClipResult* clip_result); - - protected: - ~SimpleThumbnailCrop() override; - - private: - // The target size of the captured thumbnails, in DIPs. - const gfx::Size target_size_; - - DISALLOW_COPY_AND_ASSIGN(SimpleThumbnailCrop); -}; - -} // namespace thumbnails - -#endif // CHROME_BROWSER_THUMBNAILS_SIMPLE_THUMBNAIL_CROP_H_
diff --git a/chrome/browser/thumbnails/thumbnail_service.h b/chrome/browser/thumbnails/thumbnail_service.h index 1fd87de..4077d8f 100644 --- a/chrome/browser/thumbnails/thumbnail_service.h +++ b/chrome/browser/thumbnails/thumbnail_service.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_THUMBNAILS_THUMBNAIL_SERVICE_H_ #define CHROME_BROWSER_THUMBNAILS_THUMBNAIL_SERVICE_H_ -#include "components/history/core/common/thumbnail_score.h" #include "components/keyed_service/core/refcounted_keyed_service.h" #include "ui/base/page_transition_types.h" #include "ui/gfx/image/image.h" @@ -18,7 +17,6 @@ namespace thumbnails { -class ThumbnailingAlgorithm; struct ThumbnailingContext; // An interface abstracting access to thumbnails. Intended as a temporary @@ -32,14 +30,6 @@ virtual bool SetPageThumbnail(const ThumbnailingContext& context, const gfx::Image& thumbnail) = 0; - // Returns the ThumbnailingAlgorithm used for processing thumbnails. - // It is always a new instance, the caller owns it. It will encapsulate the - // process of creating a thumbnail from tab contents. The lifetime of these - // instances is limited to the act of processing a single tab image. They - // are permitted to hold the state of such process. - // TODO(treib): Return a scoped_refptr rather than raw pointer. - virtual ThumbnailingAlgorithm* GetThumbnailingAlgorithm() const = 0; - // Gets a thumbnail for a given page. Returns true iff we have the thumbnail. // This may be invoked on any thread. // If an exact thumbnail URL match fails, |prefix_match| specifies whether or
diff --git a/chrome/browser/thumbnails/thumbnail_service_impl.cc b/chrome/browser/thumbnails/thumbnail_service_impl.cc index 632adc1..2ca6786 100644 --- a/chrome/browser/thumbnails/thumbnail_service_impl.cc +++ b/chrome/browser/thumbnails/thumbnail_service_impl.cc
@@ -9,7 +9,6 @@ #include "base/time/time.h" #include "chrome/browser/history/history_utils.h" #include "chrome/browser/history/top_sites_factory.h" -#include "chrome/browser/thumbnails/simple_thumbnail_crop.h" #include "chrome/browser/thumbnails/thumbnailing_context.h" #include "chrome/common/chrome_features.h" #include "content/public/browser/browser_thread.h" @@ -19,13 +18,6 @@ namespace { -// The desired thumbnail size in DIP. Note that ThumbnailAlgorithm -// implementations aren't actually required to respect this size - in -// particular, SimpleThumbnailCrop takes thumbnails of twice that size on 1x -// devices. -const int kThumbnailWidth = 154; -const int kThumbnailHeight = 96; - void AddForcedURLOnUIThread(scoped_refptr<history::TopSites> top_sites, const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -73,11 +65,6 @@ base::Bind(AddForcedURLOnUIThread, local_ptr, url)); } -ThumbnailingAlgorithm* ThumbnailServiceImpl::GetThumbnailingAlgorithm() - const { - return new SimpleThumbnailCrop(gfx::Size(kThumbnailWidth, kThumbnailHeight)); -} - bool ThumbnailServiceImpl::ShouldAcquirePageThumbnail( const GURL& url, ui::PageTransition transition) {
diff --git a/chrome/browser/thumbnails/thumbnail_service_impl.h b/chrome/browser/thumbnails/thumbnail_service_impl.h index 708ed16..5d776886 100644 --- a/chrome/browser/thumbnails/thumbnail_service_impl.h +++ b/chrome/browser/thumbnails/thumbnail_service_impl.h
@@ -27,7 +27,6 @@ // Implementation of ThumbnailService. bool SetPageThumbnail(const ThumbnailingContext& context, const gfx::Image& thumbnail) override; - ThumbnailingAlgorithm* GetThumbnailingAlgorithm() const override; bool GetPageThumbnail(const GURL& url, bool prefix_match, scoped_refptr<base::RefCountedMemory>* bytes) override;
diff --git a/chrome/browser/thumbnails/thumbnail_tab_helper.cc b/chrome/browser/thumbnails/thumbnail_tab_helper.cc index 5c445db..871f1d3 100644 --- a/chrome/browser/thumbnails/thumbnail_tab_helper.cc +++ b/chrome/browser/thumbnails/thumbnail_tab_helper.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/thumbnails/thumbnail_service.h" #include "chrome/browser/thumbnails/thumbnail_service_factory.h" -#include "chrome/browser/thumbnails/thumbnailing_algorithm.h" +#include "chrome/browser/thumbnails/thumbnail_utils.h" #include "chrome/common/chrome_features.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_handle.h" @@ -26,10 +26,14 @@ #include "ui/gfx/scrollbar_size.h" using thumbnails::ThumbnailingContext; -using thumbnails::ThumbnailingAlgorithm; namespace { +// The desired thumbnail size in DIP. Note that on 1x devices, we actually take +// thumbnails of twice that size. +const int kThumbnailWidth = 154; +const int kThumbnailHeight = 96; + void ComputeThumbnailScore(const SkBitmap& thumbnail, scoped_refptr<ThumbnailingContext> context) { base::TimeTicks process_bitmap_start_time = base::TimeTicks::Now(); @@ -210,9 +214,6 @@ return; } - scoped_refptr<ThumbnailingAlgorithm> algorithm( - thumbnail_service->GetThumbnailingAlgorithm()); - thumbnailing_context_ = new ThumbnailingContext(web_contents(), thumbnail_service.get(), load_interrupted_); @@ -220,10 +221,9 @@ ui::ScaleFactor scale_factor = ui::GetSupportedScaleFactor( ui::GetScaleFactorForNativeView(view->GetNativeView())); - thumbnailing_context_->clip_result = algorithm->GetCanvasCopyInfo( - copy_rect.size(), - scale_factor, - ©_rect, + thumbnailing_context_->clip_result = thumbnails::GetCanvasCopyInfo( + copy_rect.size(), scale_factor, + gfx::Size(kThumbnailWidth, kThumbnailHeight), ©_rect, &thumbnailing_context_->requested_copy_size); copy_from_surface_start_time_ = base::TimeTicks::Now(); view->CopyFromSurface(copy_rect, thumbnailing_context_->requested_copy_size,
diff --git a/chrome/browser/thumbnails/simple_thumbnail_crop.cc b/chrome/browser/thumbnails/thumbnail_utils.cc similarity index 70% rename from chrome/browser/thumbnails/simple_thumbnail_crop.cc rename to chrome/browser/thumbnails/thumbnail_utils.cc index 27f0f13..24de13c3 100644 --- a/chrome/browser/thumbnails/simple_thumbnail_crop.cc +++ b/chrome/browser/thumbnails/thumbnail_utils.cc
@@ -2,26 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/thumbnails/simple_thumbnail_crop.h" +#include "chrome/browser/thumbnails/thumbnail_utils.h" +#include "components/history/core/common/thumbnail_score.h" #include "content/public/browser/browser_thread.h" #include "ui/gfx/geometry/size_conversions.h" namespace thumbnails { -SimpleThumbnailCrop::SimpleThumbnailCrop(const gfx::Size& target_size) - : target_size_(target_size) { - DCHECK(!target_size.IsEmpty()); +bool IsGoodClipping(ClipResult clip_result) { + return clip_result == CLIP_RESULT_WIDER_THAN_TALL || + clip_result == CLIP_RESULT_TALLER_THAN_WIDE || + clip_result == CLIP_RESULT_NOT_CLIPPED; } -ClipResult SimpleThumbnailCrop::GetCanvasCopyInfo(const gfx::Size& source_size, - ui::ScaleFactor scale_factor, - gfx::Rect* clipping_rect, - gfx::Size* copy_size) const { +ClipResult GetCanvasCopyInfo(const gfx::Size& source_size, + ui::ScaleFactor scale_factor, + const gfx::Size& target_size, + gfx::Rect* clipping_rect, + gfx::Size* copy_size) { DCHECK(!source_size.IsEmpty()); + DCHECK(!target_size.IsEmpty()); ClipResult clip_result = thumbnails::CLIP_RESULT_NOT_CLIPPED; - *clipping_rect = GetClippingRect(source_size, target_size_, &clip_result); - *copy_size = GetCopySizeForThumbnail(scale_factor, target_size_); + *clipping_rect = GetClippingRect(source_size, target_size, &clip_result); + *copy_size = GetCopySizeForThumbnail(scale_factor, target_size); return clip_result; } @@ -29,10 +33,8 @@ // necessary to read back the web contents image data from GPU. As the cost is // roughly proportional to the number of the copied pixels, the size of the // copied pixels should be as small as possible. -// static -gfx::Size SimpleThumbnailCrop::GetCopySizeForThumbnail( - ui::ScaleFactor scale_factor, - const gfx::Size& thumbnail_size) { +gfx::Size GetCopySizeForThumbnail(ui::ScaleFactor scale_factor, + const gfx::Size& thumbnail_size) { // The copy size returned is the pixel equivalent of |thumbnail_size|, which // is in DIPs. if (scale_factor == ui::SCALE_FACTOR_100P) { @@ -44,9 +46,9 @@ return gfx::ScaleToFlooredSize(thumbnail_size, scale); } -gfx::Rect SimpleThumbnailCrop::GetClippingRect(const gfx::Size& source_size, - const gfx::Size& desired_size, - ClipResult* clip_result) { +gfx::Rect GetClippingRect(const gfx::Size& source_size, + const gfx::Size& desired_size, + ClipResult* clip_result) { DCHECK(clip_result); float desired_aspect = @@ -71,9 +73,9 @@ int new_width = static_cast<int>(source_size.height() * desired_aspect); int x_offset = (source_size.width() - new_width) / 2; clipping_rect.SetRect(x_offset, 0, new_width, source_size.height()); - *clip_result = (src_aspect >= ThumbnailScore::kTooWideAspectRatio) ? - thumbnails::CLIP_RESULT_MUCH_WIDER_THAN_TALL : - thumbnails::CLIP_RESULT_WIDER_THAN_TALL; + *clip_result = (src_aspect >= ThumbnailScore::kTooWideAspectRatio) + ? thumbnails::CLIP_RESULT_MUCH_WIDER_THAN_TALL + : thumbnails::CLIP_RESULT_WIDER_THAN_TALL; } else if (src_aspect < desired_aspect) { clipping_rect = gfx::Rect(source_size.width(), source_size.width() / desired_aspect); @@ -86,6 +88,4 @@ return clipping_rect; } -SimpleThumbnailCrop::~SimpleThumbnailCrop() = default; - -} // namespace thumbnails +} // namespace thumbnails
diff --git a/chrome/browser/thumbnails/thumbnail_utils.h b/chrome/browser/thumbnails/thumbnail_utils.h new file mode 100644 index 0000000..5f39954 --- /dev/null +++ b/chrome/browser/thumbnails/thumbnail_utils.h
@@ -0,0 +1,63 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_THUMBNAILS_THUMBNAIL_UTILS_H_ +#define CHROME_BROWSER_THUMBNAILS_THUMBNAIL_UTILS_H_ + +#include "base/macros.h" +#include "ui/base/resource/scale_factor.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" + +namespace thumbnails { + +// The result of clipping. This can be used to determine if the +// generated thumbnail is good or not. +enum ClipResult { + // Clipping is not done yet. + CLIP_RESULT_UNPROCESSED, + // The source image is smaller. + CLIP_RESULT_SOURCE_IS_SMALLER, + // Wider than tall by twice or more, clip horizontally. + CLIP_RESULT_MUCH_WIDER_THAN_TALL, + // Wider than tall, clip horizontally. + CLIP_RESULT_WIDER_THAN_TALL, + // Taller than wide, clip vertically. + CLIP_RESULT_TALLER_THAN_WIDE, + // The source and destination aspect ratios are identical. + CLIP_RESULT_NOT_CLIPPED, +}; + +bool IsGoodClipping(ClipResult clip_result); + +// The implementation of the 'classic' thumbnail cropping algorithm. It is not +// content-driven in any meaningful way (save for score calculation). Rather, +// the choice of a cropping region is based on relation between source and +// target sizes. The selected source region is then rescaled into the target +// thumbnail image. + +// Provides information necessary to crop-and-resize image data from a source +// canvas of |source_size|. Auxiliary |scale_factor| helps compute the target +// thumbnail size to be copied from the backing store, in pixels. Parameters +// of the required copy operation are assigned to |clipping_rect| (cropping +// rectangle for the source canvas) and |copy_size| (the size of the copied +// bitmap in pixels). The return value indicates the type of clipping that +// will be done. +ClipResult GetCanvasCopyInfo(const gfx::Size& source_size, + ui::ScaleFactor scale_factor, + const gfx::Size& target_size, + gfx::Rect* clipping_rect, + gfx::Size* copy_size); + +// Returns the size copied from the backing store. |thumbnail_size| is in +// DIP, returned size in pixels. +gfx::Size GetCopySizeForThumbnail(ui::ScaleFactor scale_factor, + const gfx::Size& thumbnail_size); +gfx::Rect GetClippingRect(const gfx::Size& source_size, + const gfx::Size& desired_size, + ClipResult* clip_result); + +} // namespace thumbnails + +#endif // CHROME_BROWSER_THUMBNAILS_THUMBNAIL_UTILS_H_
diff --git a/chrome/browser/thumbnails/simple_thumbnail_crop_unittest.cc b/chrome/browser/thumbnails/thumbnail_utils_unittest.cc similarity index 67% rename from chrome/browser/thumbnails/simple_thumbnail_crop_unittest.cc rename to chrome/browser/thumbnails/thumbnail_utils_unittest.cc index f0512ce..15da99f 100644 --- a/chrome/browser/thumbnails/simple_thumbnail_crop_unittest.cc +++ b/chrome/browser/thumbnails/thumbnail_utils_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 "chrome/browser/thumbnails/simple_thumbnail_crop.h" +#include "chrome/browser/thumbnails/thumbnail_utils.h" #include "chrome/browser/thumbnails/thumbnailing_context.h" #include "content/public/browser/notification_service.h" @@ -17,7 +17,6 @@ #include "ui/surface/transport_dib.h" using content::WebContents; -using thumbnails::SimpleThumbnailCrop; typedef testing::Test SimpleThumbnailCropTest; @@ -26,16 +25,12 @@ gfx::Size expected_2x_size = gfx::ScaleToFlooredSize(thumbnail_size, 2.0); float desired_aspect = static_cast<float>(thumbnail_size.width()) / thumbnail_size.height(); - scoped_refptr<thumbnails::ThumbnailingAlgorithm> algorithm( - new SimpleThumbnailCrop(thumbnail_size)); gfx::Rect clipping_rect_result; gfx::Size target_size_result; - thumbnails::ClipResult clip_result = algorithm->GetCanvasCopyInfo( - gfx::Size(400, 210), - ui::SCALE_FACTOR_200P, - &clipping_rect_result, - &target_size_result); + thumbnails::ClipResult clip_result = thumbnails::GetCanvasCopyInfo( + gfx::Size(400, 210), ui::SCALE_FACTOR_200P, thumbnail_size, + &clipping_rect_result, &target_size_result); gfx::Size clipping_size = clipping_rect_result.size(); float clip_aspect = static_cast<float>(clipping_size.width()) / clipping_size.height(); @@ -43,11 +38,9 @@ EXPECT_EQ(expected_2x_size, target_size_result); EXPECT_NEAR(desired_aspect, clip_aspect, 0.01); - clip_result = algorithm->GetCanvasCopyInfo( - gfx::Size(600, 200), - ui::SCALE_FACTOR_200P, - &clipping_rect_result, - &target_size_result); + clip_result = thumbnails::GetCanvasCopyInfo( + gfx::Size(600, 200), ui::SCALE_FACTOR_200P, thumbnail_size, + &clipping_rect_result, &target_size_result); clipping_size = clipping_rect_result.size(); clip_aspect = static_cast<float>(clipping_size.width()) / clipping_size.height(); @@ -55,11 +48,9 @@ EXPECT_EQ(expected_2x_size, target_size_result); EXPECT_NEAR(desired_aspect, clip_aspect, 0.01); - clip_result = algorithm->GetCanvasCopyInfo( - gfx::Size(300, 600), - ui::SCALE_FACTOR_200P, - &clipping_rect_result, - &target_size_result); + clip_result = thumbnails::GetCanvasCopyInfo( + gfx::Size(300, 600), ui::SCALE_FACTOR_200P, thumbnail_size, + &clipping_rect_result, &target_size_result); clipping_size = clipping_rect_result.size(); clip_aspect = static_cast<float>(clipping_size.width()) / clipping_size.height(); @@ -67,19 +58,15 @@ EXPECT_EQ(expected_2x_size, target_size_result); EXPECT_NEAR(desired_aspect, clip_aspect, 0.01); - clip_result = algorithm->GetCanvasCopyInfo( - gfx::Size(200, 100), - ui::SCALE_FACTOR_200P, - &clipping_rect_result, - &target_size_result); + clip_result = thumbnails::GetCanvasCopyInfo( + gfx::Size(200, 100), ui::SCALE_FACTOR_200P, thumbnail_size, + &clipping_rect_result, &target_size_result); EXPECT_EQ(thumbnails::CLIP_RESULT_SOURCE_IS_SMALLER, clip_result); EXPECT_EQ(expected_2x_size, target_size_result); } TEST_F(SimpleThumbnailCropTest, GetCanvasCopyInfoDifferentScales) { gfx::Size thumbnail_size(200, 120); - scoped_refptr<thumbnails::ThumbnailingAlgorithm> algorithm( - new SimpleThumbnailCrop(thumbnail_size)); gfx::Rect clipping_rect_result; gfx::Size target_size_result; @@ -87,19 +74,22 @@ gfx::Size expected_2x_size = gfx::ScaleToFlooredSize(thumbnail_size, 2.0); // Test at 1x scale. Expect a 2x thumbnail (we do this for quality). - algorithm->GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_100P, - &clipping_rect_result, &target_size_result); + thumbnails::GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_100P, + thumbnail_size, &clipping_rect_result, + &target_size_result); EXPECT_EQ(expected_2x_size, target_size_result); // Test at 2x scale. - algorithm->GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_200P, - &clipping_rect_result, &target_size_result); + thumbnails::GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_200P, + thumbnail_size, &clipping_rect_result, + &target_size_result); EXPECT_EQ(expected_2x_size, target_size_result); // Test at 3x scale. gfx::Size expected_3x_size = gfx::ScaleToFlooredSize(thumbnail_size, 3.0); - algorithm->GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_300P, - &clipping_rect_result, &target_size_result); + thumbnails::GetCanvasCopyInfo(gfx::Size(400, 210), ui::SCALE_FACTOR_300P, + thumbnail_size, &clipping_rect_result, + &target_size_result); EXPECT_EQ(expected_3x_size, target_size_result); } @@ -107,22 +97,22 @@ const gfx::Size desired_size(300, 200); thumbnails::ClipResult clip_result; // Try out 'microsource'. - gfx::Rect clip_rect = SimpleThumbnailCrop::GetClippingRect( - gfx::Size(300, 199), desired_size, &clip_result); + gfx::Rect clip_rect = thumbnails::GetClippingRect(gfx::Size(300, 199), + desired_size, &clip_result); EXPECT_EQ(thumbnails::CLIP_RESULT_SOURCE_IS_SMALLER, clip_result); EXPECT_EQ(gfx::Point(0, 0).ToString(), clip_rect.origin().ToString()); EXPECT_EQ(desired_size.ToString(), clip_rect.size().ToString()); // Portrait source. - clip_rect = SimpleThumbnailCrop::GetClippingRect( - gfx::Size(500, 1200), desired_size, &clip_result); + clip_rect = thumbnails::GetClippingRect(gfx::Size(500, 1200), desired_size, + &clip_result); EXPECT_EQ(thumbnails::CLIP_RESULT_TALLER_THAN_WIDE, clip_result); EXPECT_EQ(gfx::Point(0, 0).ToString(), clip_rect.origin().ToString()); EXPECT_EQ(500, clip_rect.width()); EXPECT_GE(1200, clip_rect.height()); - clip_rect = SimpleThumbnailCrop::GetClippingRect( - gfx::Size(2000, 800), desired_size, &clip_result); + clip_rect = thumbnails::GetClippingRect(gfx::Size(2000, 800), desired_size, + &clip_result); EXPECT_TRUE(clip_result == thumbnails::CLIP_RESULT_WIDER_THAN_TALL || clip_result == thumbnails::CLIP_RESULT_MUCH_WIDER_THAN_TALL); EXPECT_EQ(0, clip_rect.y()); @@ -130,8 +120,8 @@ EXPECT_GE(2000, clip_rect.width()); EXPECT_EQ(800, clip_rect.height()); - clip_rect = SimpleThumbnailCrop::GetClippingRect( - gfx::Size(900, 600), desired_size, &clip_result); + clip_rect = thumbnails::GetClippingRect(gfx::Size(900, 600), desired_size, + &clip_result); EXPECT_EQ(thumbnails::CLIP_RESULT_NOT_CLIPPED, clip_result); EXPECT_EQ(gfx::Point(0, 0).ToString(), clip_rect.origin().ToString()); EXPECT_EQ(gfx::Size(900, 600).ToString(), clip_rect.size().ToString());
diff --git a/chrome/browser/thumbnails/thumbnailing_algorithm.h b/chrome/browser/thumbnails/thumbnailing_algorithm.h deleted file mode 100644 index df9c827b..0000000 --- a/chrome/browser/thumbnails/thumbnailing_algorithm.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_THUMBNAILS_THUMBNAILING_ALGORITHM_H_ -#define CHROME_BROWSER_THUMBNAILS_THUMBNAILING_ALGORITHM_H_ - -#include "base/memory/ref_counted.h" -#include "chrome/browser/thumbnails/thumbnailing_context.h" -#include "ui/base/resource/scale_factor.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/size.h" - -namespace thumbnails { - -// An interface abstracting thumbnailing algorithms. Instances are intended to -// be created by ThumbnailService's implementations and used by -// ThumbnailTabHelper as consumers of captured source images. -class ThumbnailingAlgorithm - : public base::RefCountedThreadSafe<ThumbnailingAlgorithm> { - public: - // Provides information necessary to crop-and-resize image data from a source - // canvas of |source_size|. Auxiliary |scale_factor| helps compute the target - // thumbnail size to be copied from the backing store, in pixels. Parameters - // of the required copy operation are assigned to |clipping_rect| (cropping - // rectangle for the source canvas) and |copy_size| (the size of the copied - // bitmap in pixels). The return value indicates the type of clipping that - // will be done. - virtual ClipResult GetCanvasCopyInfo(const gfx::Size& source_size, - ui::ScaleFactor scale_factor, - gfx::Rect* clipping_rect, - gfx::Size* copy_size) const = 0; - - protected: - virtual ~ThumbnailingAlgorithm() {} - friend class base::RefCountedThreadSafe<ThumbnailingAlgorithm>; -}; - -} // namespace thumbnails - -#endif // CHROME_BROWSER_THUMBNAILS_THUMBNAILING_ALGORITHM_H_
diff --git a/chrome/browser/thumbnails/thumbnailing_context.cc b/chrome/browser/thumbnails/thumbnailing_context.cc index 28add9fe..04765e6 100644 --- a/chrome/browser/thumbnails/thumbnailing_context.cc +++ b/chrome/browser/thumbnails/thumbnailing_context.cc
@@ -9,12 +9,6 @@ namespace thumbnails { -bool IsGoodClipping(ClipResult clip_result) { - return clip_result == CLIP_RESULT_WIDER_THAN_TALL || - clip_result == CLIP_RESULT_TALLER_THAN_WIDE || - clip_result == CLIP_RESULT_NOT_CLIPPED; -} - ThumbnailingContext::ThumbnailingContext(content::WebContents* web_contents, ThumbnailService* receiving_service, bool load_interrupted)
diff --git a/chrome/browser/thumbnails/thumbnailing_context.h b/chrome/browser/thumbnails/thumbnailing_context.h index e9493b1..796996ca 100644 --- a/chrome/browser/thumbnails/thumbnailing_context.h +++ b/chrome/browser/thumbnails/thumbnailing_context.h
@@ -7,31 +7,13 @@ #include "base/memory/ref_counted.h" #include "chrome/browser/thumbnails/thumbnail_service.h" +#include "chrome/browser/thumbnails/thumbnail_utils.h" #include "components/history/core/common/thumbnail_score.h" #include "content/public/browser/web_contents.h" #include "ui/gfx/geometry/size.h" namespace thumbnails { -// The result of clipping. This can be used to determine if the -// generated thumbnail is good or not. -enum ClipResult { - // Clipping is not done yet. - CLIP_RESULT_UNPROCESSED, - // The source image is smaller. - CLIP_RESULT_SOURCE_IS_SMALLER, - // Wider than tall by twice or more, clip horizontally. - CLIP_RESULT_MUCH_WIDER_THAN_TALL, - // Wider than tall, clip horizontally. - CLIP_RESULT_WIDER_THAN_TALL, - // Taller than wide, clip vertically. - CLIP_RESULT_TALLER_THAN_WIDE, - // The source and destination aspect ratios are identical. - CLIP_RESULT_NOT_CLIPPED, -}; - -bool IsGoodClipping(ClipResult clip_result); - // Holds the information needed for processing a thumbnail. struct ThumbnailingContext : base::RefCountedThreadSafe<ThumbnailingContext> { ThumbnailingContext(content::WebContents* web_contents,
diff --git a/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc b/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc index 629a4cbaf..618c5713 100644 --- a/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc +++ b/chrome/browser/ui/android/autofill/autofill_popup_view_android.cc
@@ -16,7 +16,6 @@ #include "components/autofill/core/browser/suggestion.h" #include "components/autofill/core/common/autofill_util.h" #include "components/security_state/core/security_state.h" -#include "content/public/browser/android/content_view_core.h" #include "jni/AutofillPopupBridge_jni.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h"
diff --git a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc index 729837c3..b174505 100644 --- a/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc +++ b/chrome/browser/ui/android/autofill/credit_card_scanner_view_android.cc
@@ -15,7 +15,6 @@ #include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/field_types.h" -#include "content/public/browser/android/content_view_core.h" #include "jni/CreditCardScannerBridge_jni.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h"
diff --git a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc index e995dc1..1a8193c 100644 --- a/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc +++ b/chrome/browser/ui/android/autofill/password_generation_popup_view_android.cc
@@ -12,7 +12,6 @@ #include "base/logging.h" #include "chrome/browser/ui/android/view_android_helper.h" #include "chrome/browser/ui/autofill/password_generation_popup_controller.h" -#include "content/public/browser/android/content_view_core.h" #include "jni/PasswordGenerationPopupBridge_jni.h" #include "ui/android/view_android.h" #include "ui/android/window_android.h"
diff --git a/chrome/browser/ui/android/infobars/translate_infobar.cc b/chrome/browser/ui/android/infobars/translate_infobar.cc index b49efe28..ad43cd3d 100644 --- a/chrome/browser/ui/android/infobars/translate_infobar.cc +++ b/chrome/browser/ui/android/infobars/translate_infobar.cc
@@ -17,6 +17,7 @@ #include "chrome/browser/translate/android/translate_utils.h" #include "chrome/browser/translate/chrome_translate_client.h" #include "chrome/browser/ui/android/infobars/translate_compact_infobar.h" +#include "components/translate/core/browser/translate_browser_metrics.h" #include "components/translate/core/browser/translate_infobar_delegate.h" #include "jni/TranslateInfoBar_jni.h" @@ -28,12 +29,19 @@ std::unique_ptr<infobars::InfoBar> ChromeTranslateClient::CreateInfoBar( std::unique_ptr<translate::TranslateInfoBarDelegate> delegate) const { + // Log metric to track how many times a brand new infobar was created to + // prompt the user to translate. + if (delegate.get()->translate_step() == + translate::TRANSLATE_STEP_BEFORE_TRANSLATE) { + translate::TranslateBrowserMetrics::ReportInitiationStatus( + translate::TranslateBrowserMetrics::INITIATION_STATUS_CREATE_INFOBAR); + } + if (base::FeatureList::IsEnabled(translate::kTranslateCompactUI)) return base::MakeUnique<TranslateCompactInfoBar>(std::move(delegate)); - else - return base::MakeUnique<TranslateInfoBar>(std::move(delegate)); -} + return base::MakeUnique<TranslateInfoBar>(std::move(delegate)); +} // TranslateInfoBar -----------------------------------------------------------
diff --git a/chrome/browser/ui/app_list/OWNERS b/chrome/browser/ui/app_list/OWNERS index 46b4daee..b3acb36f 100644 --- a/chrome/browser/ui/app_list/OWNERS +++ b/chrome/browser/ui/app_list/OWNERS
@@ -1,7 +1,5 @@ -benwells@chromium.org calamity@chromium.org jennyz@chromium.org -mgiuca@chromium.org +khmel@chromium.org stevenjb@chromium.org -tapted@chromium.org xiyuan@chromium.org
diff --git a/chrome/browser/ui/app_list/app_list_view_delegate.cc b/chrome/browser/ui/app_list/app_list_view_delegate.cc index aae349ce..d4c4c64 100644 --- a/chrome/browser/ui/app_list/app_list_view_delegate.cc +++ b/chrome/browser/ui/app_list/app_list_view_delegate.cc
@@ -8,6 +8,7 @@ #include <vector> +#include "ash/public/interfaces/constants.mojom.h" #include "base/command_line.h" #include "base/metrics/user_metrics.h" #include "base/profiler/scoped_tracker.h" @@ -38,11 +39,13 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/speech_recognition_session_preamble.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/service_manager_connection.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/constants.h" #include "extensions/common/extension_set.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/manifest_handlers/launcher_page_info.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/app_list/app_list_switches.h" #include "ui/app_list/search_box_model.h" #include "ui/app_list/search_controller.h" @@ -105,9 +108,11 @@ AppListViewDelegate::AppListViewDelegate(AppListControllerDelegate* controller) : controller_(controller), - profile_(NULL), - model_(NULL), - template_url_service_observer_(this) { + profile_(nullptr), + model_(nullptr), + template_url_service_observer_(this), + observer_binding_(this), + weak_ptr_factory_(this) { CHECK(controller_); speech_ui_.reset(new app_list::SpeechUIModel); @@ -127,6 +132,13 @@ registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); + + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->BindInterface(ash::mojom::kServiceName, &wallpaper_controller_ptr_); + ash::mojom::WallpaperObserverAssociatedPtrInfo ptr_info; + observer_binding_.Bind(mojo::MakeRequest(&ptr_info)); + wallpaper_controller_ptr_->AddObserver(std::move(ptr_info)); } AppListViewDelegate::~AppListViewDelegate() { @@ -183,6 +195,12 @@ model_ = app_list::AppListSyncableServiceFactory::GetForProfile(profile_) ->GetModel(); + // After |model_| is initialized, make a GetWallpaperColors mojo call to set + // wallpaper colors for |model_|. + wallpaper_controller_ptr_->GetWallpaperColors( + base::Bind(&AppListViewDelegate::OnGetWallpaperColorsCallback, + weak_ptr_factory_.GetWeakPtr())); + app_sync_ui_state_watcher_.reset( new AppSyncUIStateWatcher(profile_, model_)); @@ -195,6 +213,11 @@ model_->search_box()->Update(base::string16(), false); } +void AppListViewDelegate::OnGetWallpaperColorsCallback( + const std::vector<SkColor>& colors) { + OnWallpaperColorsChanged(colors); +} + void AppListViewDelegate::SetUpSearchUI() { app_list::StartPageService* start_page_service = app_list::StartPageService::Get(profile_); @@ -241,6 +264,14 @@ first_launcher_page_app_id)); } +void AppListViewDelegate::OnWallpaperColorsChanged( + const std::vector<SkColor>& prominent_colors) { + if (!model_) + return; + + model_->search_box()->SetWallpaperProminentColors(prominent_colors); +} + void AppListViewDelegate::OnHotwordStateChanged(bool started) { if (started) { if (speech_ui_->state() == app_list::SPEECH_RECOGNITION_READY) {
diff --git a/chrome/browser/ui/app_list/app_list_view_delegate.h b/chrome/browser/ui/app_list/app_list_view_delegate.h index 0a5d7540..67e59f1 100644 --- a/chrome/browser/ui/app_list/app_list_view_delegate.h +++ b/chrome/browser/ui/app_list/app_list_view_delegate.h
@@ -11,9 +11,11 @@ #include <string> #include <vector> +#include "ash/public/interfaces/wallpaper.mojom.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "chrome/browser/search/hotword_client.h" #include "chrome/browser/ui/app_list/start_page_observer.h" @@ -21,6 +23,8 @@ #include "components/search_engines/template_url_service_observer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" +#include "mojo/public/cpp/bindings/associated_binding.h" +#include "mojo/public/cpp/bindings/binding.h" #include "ui/app_list/app_list_view_delegate.h" namespace app_list { @@ -41,6 +45,7 @@ class AppListViewDelegate : public app_list::AppListViewDelegate, public app_list::StartPageObserver, + public ash::mojom::WallpaperObserver, public HotwordClient, public content::NotificationObserver, public TemplateURLServiceObserver { @@ -87,6 +92,9 @@ void OnTemplateURLServiceChanged() override; private: + // Callback for ash::mojom::GetWallpaperColors. + void OnGetWallpaperColorsCallback(const std::vector<SkColor>& colors); + // Updates the speech webview and start page for the current |profile_|. void SetUpSearchUI(); @@ -99,6 +107,10 @@ void OnSpeechRecognitionStateChanged( app_list::SpeechRecognitionState new_state) override; + // Overridden from ash::mojom::WallpaperObserver: + void OnWallpaperColorsChanged( + const std::vector<SkColor>& prominent_colors) override; + // Overridden from HotwordClient: void OnHotwordStateChanged(bool started) override; void OnHotwordRecognized( @@ -142,6 +154,14 @@ // Registers for NOTIFICATION_APP_TERMINATING to unload custom launcher pages. content::NotificationRegistrar registrar_; + // The binding this instance uses to implement mojom::WallpaperObserver. + mojo::AssociatedBinding<ash::mojom::WallpaperObserver> observer_binding_; + + // Ash's mojom::WallpaperController. + ash::mojom::WallpaperControllerPtr wallpaper_controller_ptr_; + + base::WeakPtrFactory<AppListViewDelegate> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(AppListViewDelegate); };
diff --git a/chrome/browser/ui/ash/app_list/OWNERS b/chrome/browser/ui/ash/app_list/OWNERS index 5a29154..403dd3f 100644 --- a/chrome/browser/ui/ash/app_list/OWNERS +++ b/chrome/browser/ui/ash/app_list/OWNERS
@@ -1,4 +1,3 @@ calamity@chromium.org -mgiuca@chromium.org -tapted@chromium.org +khmel@chromium.org xiyuan@chromium.org
diff --git a/chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.cc b/chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.cc index ba7dd3c..5011888 100644 --- a/chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.cc +++ b/chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.cc
@@ -191,10 +191,10 @@ const arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); DCHECK(arc_session_manager); - DCHECK(arc_session_manager->state() != - arc::ArcSessionManager::State::STOPPED); - DCHECK(arc_session_manager->state() != - arc::ArcSessionManager::State::NOT_INITIALIZED); + DCHECK_NE(arc_session_manager->state(), + arc::ArcSessionManager::State::STOPPED); + DCHECK_NE(arc_session_manager->state(), + arc::ArcSessionManager::State::NOT_INITIALIZED); const ash::ShelfID shelf_id(app_id);
diff --git a/chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc b/chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc index 22bf4c8..2cbd64d 100644 --- a/chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc +++ b/chrome/browser/ui/ash/launcher/arc_app_launcher_browsertest.cc
@@ -240,8 +240,13 @@ } void StartInstance() { - if (arc_session_manager()->profile() != profile()) + if (!arc_session_manager()->profile()) { + // This situation happens when StartInstance() is called after + // StopInstance(). + // TODO(hidehiko): The emulation is not implemented correctly. Fix it. + arc_session_manager()->SetProfile(profile()); arc::ArcServiceLauncher::Get()->OnPrimaryUserProfilePrepared(profile()); + } app_instance_observer()->OnInstanceReady(); }
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc index 2fee515..6535032 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_browsertest.cc
@@ -2191,6 +2191,37 @@ EXPECT_FALSE(test.IsOverflowButtonVisible()); } +// Validates that context menu is shown on right click and drag context is not +// set in this case and set on left click. +IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ShelfButtonContextMenu) { + ui::test::EventGenerator generator(ash::Shell::GetPrimaryRootWindow(), + gfx::Point()); + ash::test::ShelfViewTestAPI test(shelf_->GetShelfViewForTesting()); + const int browser_index = GetIndexOfShelfItemType(ash::TYPE_BROWSER_SHORTCUT); + ASSERT_LE(0, browser_index); + ash::ShelfButton* button = test.GetButton(browser_index); + ASSERT_TRUE(button); + + // No context menu is shown at this time. + EXPECT_FALSE(test.shelf_view()->IsShowingMenu()); + const gfx::Rect bounds = button->GetBoundsInScreen(); + generator.MoveMouseTo(bounds.CenterPoint().x(), bounds.CenterPoint().y()); + generator.PressRightButton(); + // Context menu is shown on right button press and no drag context is set. + EXPECT_TRUE(test.shelf_view()->IsShowingMenu()); + EXPECT_FALSE(test.shelf_view()->drag_view()); + generator.ReleaseRightButton(); + EXPECT_FALSE(test.shelf_view()->drag_view()); + + // Press left button. Menu should close and drag context is set to |button|. + generator.PressLeftButton(); + EXPECT_FALSE(test.shelf_view()->IsShowingMenu()); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(test.shelf_view()->drag_view(), button); + generator.ReleaseLeftButton(); + EXPECT_FALSE(test.shelf_view()->drag_view()); +} + // Check that clicking on an app shelf item launches a new browser. IN_PROC_BROWSER_TEST_F(ShelfAppBrowserTest, ClickItem) { // Get a number of interfaces we need.
diff --git a/chrome/browser/ui/chrome_pages.cc b/chrome/browser/ui/chrome_pages.cc index d9880d5..f04527b 100644 --- a/chrome/browser/ui/chrome_pages.cc +++ b/chrome/browser/ui/chrome_pages.cc
@@ -169,17 +169,10 @@ void ShowBookmarkManager(Browser* browser) { base::RecordAction(UserMetricsAction("ShowBookmarkManager")); - if (MdBookmarksUI::IsEnabled()) { - const bookmarks::BookmarkNode* bookmark_bar_node = - BookmarkModelFactory::GetForBrowserContext(browser->profile()) - ->bookmark_bar_node(); - OpenBookmarkManagerForNode(browser, bookmark_bar_node->id()); - return; - } - - ShowSingletonTabOverwritingNTP( - browser, + NavigateParams params( GetSingletonTabNavigateParams(browser, GURL(kChromeUIBookmarksURL))); + params.path_behavior = NavigateParams::IGNORE_AND_STAY_PUT; + ShowSingletonTabOverwritingNTP(browser, params); } void ShowBookmarkManagerForNode(Browser* browser, int64_t node_id) {
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 00a78454..9e9dc9b 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field.mm
@@ -291,13 +291,10 @@ if (!ui::MaterialDesignController::IsSecondaryUiMaterial()) return [self arrowAnchorPointForDecoration:decoration]; - // Under MD, dialogs have no arrow and anchor to corner of the decoration + // Under MD, dialogs have no arrow and anchor to corner of the location bar // 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]; + BOOL isLeftDecoration = [[self cell] isLeftDecoration:decoration]; + const NSRect frame = [self bounds]; NSPoint point = NSMakePoint(isLeftDecoration ? NSMinX(frame) : NSMaxX(frame), NSMaxY(frame)); return [self convertPoint:point toView:nil];
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h index dc0758e..5529d371 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.h
@@ -75,12 +75,9 @@ - (NSRect)frameForDecoration:(const LocationBarDecoration*)aDecoration inFrame:(NSRect)cellFrame; -// Returns the frame representing the background of |decoration|. Also sets -// |isLeftDecoration| according to whether the decoration appears on the left or -// the right side of the text field. -- (NSRect)backgroundFrameForDecoration:(LocationBarDecoration*)decoration - inFrame:(NSRect)cellFrame - isLeftDecoration:(BOOL*)isLeftDecoration; +// Returns whether |decoration| appears on the left or the right side of the +// text field. +- (BOOL)isLeftDecoration:(LocationBarDecoration*)decoration; // Returns true if it's okay to drop dragged data into the view at the // given location.
diff --git a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm index 5edf8f3..4f74bb5a 100644 --- a/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm +++ b/chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_cell.mm
@@ -274,16 +274,11 @@ return NSZeroRect; } -- (NSRect)backgroundFrameForDecoration:(LocationBarDecoration*)decoration - inFrame:(NSRect)cellFrame - isLeftDecoration:(BOOL*)isLeftDecoration { - NSRect decorationFrame = - [self frameForDecoration:decoration inFrame:cellFrame]; +- (BOOL)isLeftDecoration:(LocationBarDecoration*)decoration { std::vector<LocationBarDecoration*>& left_decorations = cocoa_l10n_util::ShouldDoExperimentalRTLLayout() ? trailingDecorations_ : leadingDecorations_; - *isLeftDecoration = base::ContainsValue(left_decorations, decoration); - return decoration->GetBackgroundFrame(decorationFrame); + return base::ContainsValue(left_decorations, decoration); } // Overriden to account for the decorations.
diff --git a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm index 160f4ff..ed9a57af 100644 --- a/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/content_setting_decoration.mm
@@ -17,6 +17,7 @@ #import "chrome/browser/ui/cocoa/l10n_util.h" #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h" #import "chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h" +#import "chrome/browser/ui/cocoa/location_bar/star_decoration.h" #import "chrome/browser/ui/cocoa/themed_window.h" #include "chrome/browser/ui/content_settings/content_setting_bubble_model.h" #include "chrome/browser/ui/content_settings/content_setting_image_model.h" @@ -37,10 +38,6 @@ namespace { -// The bubble point should look like it points to the bottom of the respective -// icon. The offset should be 2px. -const CGFloat kPageBubblePointYOffset = 2.0; - // Duration of animation, 3 seconds. The ContentSettingAnimationState breaks // this up into different states of varying lengths. const NSTimeInterval kAnimationDuration = 3.0; @@ -269,9 +266,9 @@ if (!cocoa_l10n_util::ShouldDoExperimentalRTLLayout()) frame.origin.x += frame.size.width - image_size.width; frame.size = image_size; - const NSRect draw_frame = GetDrawRectInFrame(frame); - return NSMakePoint(NSMidX(draw_frame), - NSMaxY(draw_frame) + kPageBubblePointYOffset); + + // Position the same way as the bookmark star. + return StarDecoration::GetStarBubblePointInFrame(GetDrawRectInFrame(frame)); } bool ContentSettingDecoration::AcceptsMousePress() { @@ -285,14 +282,8 @@ if (!web_contents) return true; - // Find point for bubble's arrow in screen coordinates. - // TODO(shess): |owner_| is only being used to fetch |field|. - // Consider passing in |control_view|. Or refactoring to be - // consistent with other decorations (which don't currently bring up - // their bubble directly). AutocompleteTextField* field = owner_->GetAutocompleteTextField(); - NSPoint anchor = GetBubblePointInFrame(frame); - anchor = [field convertPoint:anchor toView:nil]; + NSPoint anchor = [field bubblePointForDecoration:this]; anchor = ui::ConvertPointFromWindowToScreen([field window], anchor); // Open bubble.
diff --git a/chrome/browser/ui/cocoa/location_bar/star_decoration.h b/chrome/browser/ui/cocoa/location_bar/star_decoration.h index f0a6661..06d7726a 100644 --- a/chrome/browser/ui/cocoa/location_bar/star_decoration.h +++ b/chrome/browser/ui/cocoa/location_bar/star_decoration.h
@@ -22,6 +22,10 @@ // Sets the image and tooltip based on |starred|. void SetStarred(bool starred, bool locationBarIsDark); + // Returns an anchor for GetBubblePointInFrame which points between the star + // icon's legs. + static NSPoint GetStarBubblePointInFrame(NSRect draw_frame); + // Returns true if the star is lit. bool starred() const { return starred_; }
diff --git a/chrome/browser/ui/cocoa/location_bar/star_decoration.mm b/chrome/browser/ui/cocoa/location_bar/star_decoration.mm index c0ef97149..ce2ad68a 100644 --- a/chrome/browser/ui/cocoa/location_bar/star_decoration.mm +++ b/chrome/browser/ui/cocoa/location_bar/star_decoration.mm
@@ -41,8 +41,7 @@ tooltip_.reset([l10n_util::GetNSStringWithFixup(tip_id) retain]); } -NSPoint StarDecoration::GetBubblePointInFrame(NSRect frame) { - const NSRect draw_frame = GetDrawRectInFrame(frame); +NSPoint StarDecoration::GetStarBubblePointInFrame(NSRect draw_frame) { return NSMakePoint(NSMidX(draw_frame), NSMaxY(draw_frame) - kStarPointYOffset); } @@ -60,6 +59,10 @@ return tooltip_.get(); } +NSPoint StarDecoration::GetBubblePointInFrame(NSRect frame) { + return GetStarBubblePointInFrame(GetDrawRectInFrame(frame)); +} + SkColor StarDecoration::GetMaterialIconColor(bool location_bar_is_dark) const { if (location_bar_is_dark) { return starred_ ? gfx::kGoogleBlue300 : SkColorSetA(SK_ColorWHITE, 0xCC);
diff --git a/chrome/browser/ui/sync/one_click_signin_sync_starter.cc b/chrome/browser/ui/sync/one_click_signin_sync_starter.cc index 3373b31..14b96261 100644 --- a/chrome/browser/ui/sync/one_click_signin_sync_starter.cc +++ b/chrome/browser/ui/sync/one_click_signin_sync_starter.cc
@@ -37,6 +37,7 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/core/common/profile_management_switches.h" #include "components/sync/base/sync_prefs.h" #include "net/base/url_util.h" #include "net/url_request/url_request_context_getter.h" @@ -98,6 +99,7 @@ BrowserList::AddObserver(this); Initialize(profile, browser); + DCHECK(!refresh_token.empty() || switches::IsAccountConsistencyDiceEnabled()); SigninManagerFactory::GetForProfile(profile_)->StartSignInWithRefreshToken( refresh_token, gaia_id, email, password, base::Bind(&OneClickSigninSyncStarter::ConfirmSignin, @@ -141,7 +143,6 @@ void OneClickSigninSyncStarter::ConfirmSignin(ProfileMode profile_mode, const std::string& oauth_token) { - DCHECK(!oauth_token.empty()); SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); if (signin->IsAuthenticated()) { // The user is already signed in - just tell SigninManager to continue @@ -158,10 +159,19 @@ // initialized. policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); - policy_service->RegisterForPolicy( - signin->GetUsernameForAuthInProgress(), oauth_token, - base::Bind(&OneClickSigninSyncStarter::OnRegisteredForPolicy, - weak_pointer_factory_.GetWeakPtr())); + if (oauth_token.empty()) { + DCHECK(switches::IsAccountConsistencyDiceEnabled()); + policy_service->RegisterForPolicyWithAccountId( + signin->GetUsernameForAuthInProgress(), + signin->GetAccountIdForAuthInProgress(), + base::Bind(&OneClickSigninSyncStarter::OnRegisteredForPolicy, + weak_pointer_factory_.GetWeakPtr())); + } else { + policy_service->RegisterForPolicyWithLoginToken( + signin->GetUsernameForAuthInProgress(), oauth_token, + base::Bind(&OneClickSigninSyncStarter::OnRegisteredForPolicy, + weak_pointer_factory_.GetWeakPtr())); + } break; } case NEW_PROFILE:
diff --git a/chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc b/chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc index b017fc6..ff960d9f 100644 --- a/chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc +++ b/chrome/browser/ui/views/payments/payment_request_journey_logger_browsertest.cc
@@ -188,4 +188,273 @@ JourneyLogger::NOT_SHOWN_REASON_CONCURRENT_REQUESTS, 1); } +class PaymentRequestJourneyLoggerAllSectionStatsTest + : public PaymentRequestBrowserTestBase { + protected: + PaymentRequestJourneyLoggerAllSectionStatsTest() + : PaymentRequestBrowserTestBase( + "/payment_request_contact_details_and_free_shipping_test.html") {} + + private: + DISALLOW_COPY_AND_ASSIGN(PaymentRequestJourneyLoggerAllSectionStatsTest); +}; + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is completed. +IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerAllSectionStatsTest, + NumberOfSuggestionsShown_Completed) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // Complete the Payment Request. + InvokePaymentRequestUI(); + ResetEventObserver(DialogEvent::DIALOG_CLOSED); + PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.Completed", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2, + 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2, 1); +} + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is aborted by the user. +IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerAllSectionStatsTest, + NumberOfSuggestionsShown_UserAborted) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // The user aborts the Payment Request. + InvokePaymentRequestUI(); + ClickOnCancel(); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.UserAborted", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2, + 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 2, 1); +} + +class PaymentRequestJourneyLoggerNoShippingSectionStatsTest + : public PaymentRequestBrowserTestBase { + protected: + PaymentRequestJourneyLoggerNoShippingSectionStatsTest() + : PaymentRequestBrowserTestBase( + "/payment_request_contact_details_test.html") {} + + private: + DISALLOW_COPY_AND_ASSIGN( + PaymentRequestJourneyLoggerNoShippingSectionStatsTest); +}; + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is completed. +IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerNoShippingSectionStatsTest, + NumberOfSuggestionsShown_Completed) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // Complete the Payment Request. + InvokePaymentRequestUI(); + ResetEventObserver(DialogEvent::DIALOG_CLOSED); + PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.Completed", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 2, 1); + + // There should be no log for shipping address since it was not requested. + histogram_tester.ExpectTotalCount( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 0); +} + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is aborted by the user. +IN_PROC_BROWSER_TEST_F(PaymentRequestJourneyLoggerNoShippingSectionStatsTest, + NumberOfSuggestionsShown_UserAborted) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // The user aborts the Payment Request. + InvokePaymentRequestUI(); + ClickOnCancel(); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.UserAborted", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 2, 1); + + // There should be no log for shipping address since it was not requested. + histogram_tester.ExpectTotalCount( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 0); +} + +class PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest + : public PaymentRequestBrowserTestBase { + protected: + PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest() + : PaymentRequestBrowserTestBase( + "/payment_request_free_shipping_test.html") {} + + private: + DISALLOW_COPY_AND_ASSIGN( + PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest); +}; + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is completed. +IN_PROC_BROWSER_TEST_F( + PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest, + NumberOfSuggestionsShown_Completed) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // Complete the Payment Request. + InvokePaymentRequestUI(); + ResetEventObserver(DialogEvent::DIALOG_CLOSED); + PayWithCreditCardAndWait(base::ASCIIToUTF16("123")); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.Completed", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.Completed", 2, + 1); + + // There should be no log for contact info since it was not requested. + histogram_tester.ExpectTotalCount( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.Completed", 0); +} + +// Tests that the correct number of suggestions shown for each section is logged +// when a Payment Request is aborted by the user. +IN_PROC_BROWSER_TEST_F( + PaymentRequestJourneyLoggerNoContactDetailSectionStatsTest, + NumberOfSuggestionsShown_UserAborted) { + base::HistogramTester histogram_tester; + + // Setup a credit card with an associated billing address. + autofill::AutofillProfile billing_address = autofill::test::GetFullProfile(); + AddAutofillProfile(billing_address); + autofill::CreditCard card = autofill::test::GetCreditCard(); + card.set_billing_address_id(billing_address.guid()); + AddCreditCard(card); // Visa. + + // Add another address. + AddAutofillProfile(autofill::test::GetFullProfile2()); + + // The user aborts the Payment Request. + InvokePaymentRequestUI(); + ClickOnCancel(); + + // Expect the appropriate number of suggestions shown to be logged. + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.CreditCards.UserAborted", 1, 1); + histogram_tester.ExpectUniqueSample( + "PaymentRequest.NumberOfSuggestionsShown.ShippingAddress.UserAborted", 2, + 1); + + // There should be no log for contact info since it was not requested. + histogram_tester.ExpectTotalCount( + "PaymentRequest.NumberOfSuggestionsShown.ContactInfo.UserAborted", 0); +} + +class PaymentRequestNotShownTest : public PaymentRequestBrowserTestBase { + protected: + PaymentRequestNotShownTest() + : PaymentRequestBrowserTestBase( + "/payment_request_can_make_payment_metrics_test.html") {} + + private: + DISALLOW_COPY_AND_ASSIGN(PaymentRequestNotShownTest); +}; + +IN_PROC_BROWSER_TEST_F(PaymentRequestNotShownTest, OnlyNotShownMetricsLogged) { + base::HistogramTester histogram_tester; + + // Initiate a Payment Request without showing it. + ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "queryNoShow();")); + + // Navigate away to abort the Payment Request and trigger the logs. + NavigateTo("/payment_request_email_test.html"); + + // Initiated should be logged. + histogram_tester.ExpectBucketCount("PaymentRequest.CheckoutFunnel.Initiated", + 1, 1); + // Show should not be logged. + histogram_tester.ExpectTotalCount("PaymentRequest.CheckoutFunnel.Shown", 0); + // Abort should not be logged. + histogram_tester.ExpectTotalCount("PaymentRequest.CheckoutFunnel.Aborted", 0); + + // Make sure that the metrics that required the Payment Request to be shown + // are not logged. + histogram_tester.ExpectTotalCount("PaymentRequest.SelectedPaymentMethod", 0); + histogram_tester.ExpectTotalCount("PaymentRequest.RequestedInformation", 0); + histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionAdds", 0); + histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionChanges", + 0); + histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSelectionEdits", 0); + histogram_tester.ExpectTotalCount("PaymentRequest.NumberOfSuggestionsShown", + 0); + histogram_tester.ExpectTotalCount( + "PaymentRequest.UserHadSuggestionsForEverything", 0); + histogram_tester.ExpectTotalCount( + "PaymentRequest.UserDidNotHaveSuggestionsForEverything", 0); +} + } // namespace payments
diff --git a/chrome/browser/ui/views/session_crashed_bubble_view.cc b/chrome/browser/ui/views/session_crashed_bubble_view.cc index da87ad7..876d5ba 100644 --- a/chrome/browser/ui/views/session_crashed_bubble_view.cc +++ b/chrome/browser/ui/views/session_crashed_bubble_view.cc
@@ -13,6 +13,7 @@ #include "base/bind_helpers.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" +#include "base/task_runner_util.h" #include "build/build_config.h" #include "chrome/browser/metrics/metrics_reporting_state.h" #include "chrome/browser/prefs/session_startup_pref.h" @@ -118,11 +119,8 @@ new SessionCrashedBubbleView::BrowserRemovalObserver(browser)); if (DoesSupportConsentCheck()) { - // Schedule a task to run GoogleUpdateSettings::GetCollectStatsConsent() on - // FILE thread, since it does IO. Then, call - // SessionCrashedBubbleView::ShowForReal with the result. - content::BrowserThread::PostTaskAndReplyWithResult( - content::BrowserThread::FILE, FROM_HERE, + base::PostTaskAndReplyWithResult( + GoogleUpdateSettings::CollectStatsConsentTaskRunner(), FROM_HERE, base::Bind(&GoogleUpdateSettings::GetCollectStatsConsent), base::Bind(&SessionCrashedBubbleView::ShowForReal, base::Passed(&browser_observer)));
diff --git a/chrome/browser/ui/webui/app_list/OWNERS b/chrome/browser/ui/webui/app_list/OWNERS index 2aebc091..ed54f09 100644 --- a/chrome/browser/ui/webui/app_list/OWNERS +++ b/chrome/browser/ui/webui/app_list/OWNERS
@@ -1,3 +1,2 @@ calamity@chromium.org -mgiuca@chromium.org -tapted@chromium.org +khmel@chromium.org
diff --git a/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc b/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc index ccdee6ab..132edd2 100644 --- a/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc +++ b/chrome/browser/ui/webui/bookmarks_ui_browsertest.cc
@@ -45,7 +45,7 @@ if (MdBookmarksUI::IsEnabled()) { ASSERT_TRUE(content::ExecuteScriptAndExtractString( tab, "domAutomationController.send(location.href)", &out)); - ASSERT_EQ("chrome://bookmarks/?id=1", out); + ASSERT_EQ("chrome://bookmarks/", out); return; }
diff --git a/chrome/browser/ui/webui/chromeos/login/voice_interaction_value_prop_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/voice_interaction_value_prop_screen_handler.cc index 6b683716..c2bd182 100644 --- a/chrome/browser/ui/webui/chromeos/login/voice_interaction_value_prop_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/voice_interaction_value_prop_screen_handler.cc
@@ -33,6 +33,16 @@ void VoiceInteractionValuePropScreenHandler::DeclareLocalizedValues( ::login::LocalizedValuesBuilder* builder) { builder->Add("locale", g_browser_process->GetApplicationLocale()); + builder->Add("voiceInteractionValuePropLoading", + IDS_VOICE_INTERACTION_VALUE_PROP_LOADING); + builder->Add("voiceInteractionValuePropLoadErrorTitle", + IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_TITLE); + builder->Add("voiceInteractionValuePropLoadErrorMessage", + IDS_VOICE_INTERACTION_VALUE_PROP_LOAD_ERROR_MESSAGE); + builder->Add("voiceInteractionValuePropSkipButton", + IDS_VOICE_INTERACTION_VALUE_PROP_SKIP_BUTTON); + builder->Add("voiceInteractionValuePropRetryButton", + IDS_VOICE_INTERACTION_VALUE_PROP_RETRY_BUTTON); builder->Add("voiceInteractionValuePropNoThanksButton", IDS_VOICE_INTERACTION_VALUE_PROP_NO_THANKS_BUTTON); builder->Add("voiceInteractionValuePropContinueButton",
diff --git a/chrome/browser/ui/webui/net_export_ui.cc b/chrome/browser/ui/webui/net_export_ui.cc index c9b3adee..55d0b12 100644 --- a/chrome/browser/ui/webui/net_export_ui.cc +++ b/chrome/browser/ui/webui/net_export_ui.cc
@@ -28,8 +28,8 @@ #include "chrome/common/url_constants.h" #include "components/grit/components_resources.h" #include "components/net_log/chrome_net_log.h" +#include "components/net_log/net_export_file_writer.h" #include "components/net_log/net_export_ui_constants.h" -#include "components/net_log/net_log_file_writer.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/url_data_source.h" @@ -81,7 +81,7 @@ : public WebUIMessageHandler, public base::SupportsWeakPtr<NetExportMessageHandler>, public ui::SelectFileDialog::Listener, - public net_log::NetLogFileWriter::StateObserver { + public net_log::NetExportFileWriter::StateObserver { public: NetExportMessageHandler(); ~NetExportMessageHandler() override; @@ -102,7 +102,7 @@ void* params) override; void FileSelectionCanceled(void* params) override; - // net_log::NetLogFileWriter::StateObserver implementation. + // net_log::NetExportFileWriter::StateObserver implementation. void OnNewState(const base::DictionaryValue& state) override; private: @@ -130,7 +130,7 @@ static bool UsingMobileUI(); // Calls NetExportView.onExportNetLogInfoChanged JavaScript function in the - // renderer, passing in |file_writer_state|. + // renderer. void NotifyUIWithState(std::unique_ptr<base::DictionaryValue> state); // Opens the SelectFileDialog UI with the default path to save a @@ -141,12 +141,12 @@ // logging starts so that net log entries can be added for those events. URLRequestContextGetterList GetURLRequestContexts() const; - // Cache of g_browser_process->net_log()->net_log_file_writer(). This + // Cache of g_browser_process->net_log()->net_export_file_writer(). This // is owned by ChromeNetLog which is owned by BrowserProcessImpl. - net_log::NetLogFileWriter* file_writer_; + net_log::NetExportFileWriter* file_writer_; - ScopedObserver<net_log::NetLogFileWriter, - net_log::NetLogFileWriter::StateObserver> + ScopedObserver<net_log::NetExportFileWriter, + net_log::NetExportFileWriter::StateObserver> state_observer_manager_; // The capture mode the user chose in the UI when logging started is cached @@ -162,7 +162,7 @@ }; NetExportMessageHandler::NetExportMessageHandler() - : file_writer_(g_browser_process->net_log()->net_log_file_writer()), + : file_writer_(g_browser_process->net_log()->net_export_file_writer()), state_observer_manager_(this), weak_ptr_factory_(this) { file_writer_->Initialize( @@ -222,7 +222,7 @@ DCHECK(result); capture_mode_ = - net_log::NetLogFileWriter::CaptureModeFromString(capture_mode_string); + net_log::NetExportFileWriter::CaptureModeFromString(capture_mode_string); if (UsingMobileUI()) { StartNetLog(base::FilePath());
diff --git a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc index 53be2fd..3021045 100644 --- a/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/site_settings_handler_unittest.cc
@@ -232,22 +232,22 @@ TEST_F(SiteSettingsHandlerTest, GetAndSetDefault) { // Test the JS -> C++ -> JS callback path for getting and setting defaults. - base::ListValue getArgs; - getArgs.AppendString(kCallbackId); - getArgs.AppendString("notifications"); - handler()->HandleGetDefaultValueForContentType(&getArgs); + base::ListValue get_args; + get_args.AppendString(kCallbackId); + get_args.AppendString("notifications"); + handler()->HandleGetDefaultValueForContentType(&get_args); ValidateDefault("ask", "default", 1U); // Set the default to 'Blocked'. - base::ListValue setArgs; - setArgs.AppendString("notifications"); - setArgs.AppendString("block"); - handler()->HandleSetDefaultValueForContentType(&setArgs); + base::ListValue set_args; + set_args.AppendString("notifications"); + set_args.AppendString("block"); + handler()->HandleSetDefaultValueForContentType(&set_args); EXPECT_EQ(2U, web_ui()->call_data().size()); // Verify that the default has been set to 'Blocked'. - handler()->HandleGetDefaultValueForContentType(&getArgs); + handler()->HandleGetDefaultValueForContentType(&get_args); ValidateDefault("block", "default", 3U); } @@ -272,13 +272,27 @@ histograms.ExpectTotalCount(kUmaBase + ".Reset", 0); } - // Verify the change was successful. - base::ListValue listArgs; - listArgs.AppendString(kCallbackId); - listArgs.AppendString("notifications"); - handler()->HandleGetExceptionList(&listArgs); + // If the change was successful, it should show up in the response from + // getExceptionList() as well as getOriginPermissions(). + // Check getOriginPermissions(). + base::ListValue get_origin_permissions_args; + get_origin_permissions_args.AppendString(kCallbackId); + get_origin_permissions_args.AppendString(google); + { + auto category_list = base::MakeUnique<base::ListValue>(); + category_list->AppendString("notifications"); + get_origin_permissions_args.Append(std::move(category_list)); + } + handler()->HandleGetOriginPermissions(&get_origin_permissions_args); ValidateOrigin(google, google, google, "block", "preference", 2U); + // Check getExceptionList(). + base::ListValue get_exception_list_args; + get_exception_list_args.AppendString(kCallbackId); + get_exception_list_args.AppendString("notifications"); + handler()->HandleGetExceptionList(&get_exception_list_args); + ValidateOrigin(google, google, google, "block", "preference", 3U); + { // Reset things back to how they were. base::ListValue reset_args; @@ -288,7 +302,7 @@ reset_args.AppendBoolean(false); // Incognito. base::HistogramTester histograms; handler()->HandleResetCategoryPermissionForOrigin(&reset_args); - EXPECT_EQ(3U, web_ui()->call_data().size()); + EXPECT_EQ(4U, web_ui()->call_data().size()); histograms.ExpectTotalCount(kUmaBase, 1); histograms.ExpectTotalCount(kUmaBase + ".Allowed", 0); histograms.ExpectTotalCount(kUmaBase + ".Blocked", 0); @@ -296,8 +310,12 @@ } // Verify the reset was successful. - handler()->HandleGetExceptionList(&listArgs); - ValidateNoOrigin(4U); + handler()->HandleGetExceptionList(&get_exception_list_args); + ValidateNoOrigin(5U); + + handler()->HandleGetOriginPermissions(&get_origin_permissions_args); + // "Ask" is the default value for Notifications. + ValidateOrigin(google, google, google, "ask", "preference", 6U); } TEST_F(SiteSettingsHandlerTest, ExceptionHelpers) {
diff --git a/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc b/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc index 77e3d49..48e1c14c 100644 --- a/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc +++ b/chrome/browser/ui/webui/signin/signin_dice_internals_handler.cc
@@ -6,6 +6,12 @@ #include "base/values.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_tracker_service_factory.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" +#include "chrome/browser/signin/signin_manager_factory.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/sync/one_click_signin_sync_starter.h" SigninDiceInternalsHandler::SigninDiceInternalsHandler(Profile* profile) : profile_(profile) { @@ -22,6 +28,36 @@ } void SigninDiceInternalsHandler::HandleEnableSync(const base::ListValue* args) { - // TODO(msarda): Implement start syncing. - VLOG(1) << "[Dice] Start syncing"; + if (SigninManagerFactory::GetForProfile(profile_)->IsAuthenticated()) { + VLOG(1) << "[Dice] Cannot enable sync as profile is already authenticated"; + return; + } + + AccountTrackerService* tracker = + AccountTrackerServiceFactory::GetForProfile(profile_); + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); + std::vector<std::string> account_ids = token_service->GetAccounts(); + if (account_ids.empty()) { + VLOG(1) << "[Dice] No accounts available in the token service"; + return; + } + + Browser* browser = chrome::FindLastActiveWithProfile(profile_); + DCHECK(browser); + std::string account_id = account_ids[0]; + std::string gaia_id = tracker->GetAccountInfo(account_id).gaia; + std::string email = tracker->GetAccountInfo(account_id).email; + VLOG(1) << "[Dice] Start syncing with account " << email; + + // OneClickSigninSyncStarter is suicidal (it will kill itself once it finishes + // enabling sync). + OneClickSigninSyncStarter::Callback callback; + new OneClickSigninSyncStarter( + profile_, browser, gaia_id, email, "" /* password */, + "" /* refresh_token */, OneClickSigninSyncStarter::CURRENT_PROFILE, + OneClickSigninSyncStarter::CONFIRM_SYNC_SETTINGS_FIRST, + web_ui()->GetWebContents(), + OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN, + GURL("") /* current_url */, GURL("") /* continue_url */, callback); }
diff --git a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc index 8ccb608..b54fdd7 100644 --- a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc +++ b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc
@@ -89,7 +89,6 @@ const char kKeyAvatarUrl[] = "userImage"; const char kKeyNeedsSignin[] = "needsSignin"; const char kKeyHasLocalCreds[] = "hasLocalCreds"; -const char kKeyStatistics[] = "statistics"; const char kKeyIsProfileLoaded[] = "isProfileLoaded"; // JS API callback names. @@ -103,8 +102,6 @@ "logRemoveUserWarningShown"; const char kJsApiUserManagerRemoveUserWarningLoadStats[] = "removeUserWarningLoadStats"; -const char kJsApiUserManagerGetRemoveWarningDialogMessage[] = - "getRemoveWarningDialogMessage"; const char kJsApiUserManagerAreAllProfilesLocked[] = "areAllProfilesLocked"; const size_t kAvatarIconSize = 180; @@ -634,7 +631,6 @@ for (const auto& item : result) { auto stat = base::MakeUnique<base::DictionaryValue>(); stat->SetIntegerWithoutPathExpansion("count", item.count); - stat->SetBooleanWithoutPathExpansion("success", true); return_value.SetWithoutPathExpansion(item.category, std::move(stat)); } if (result.size() == profiles::kProfileStatisticsCategories.size()) { @@ -647,39 +643,6 @@ return_value); } -void UserManagerScreenHandler::HandleGetRemoveWarningDialogMessage( - const base::ListValue* args) { - const base::DictionaryValue* arg; - if (!args->GetDictionary(0, &arg)) - return; - - std::string profile_path(""); - bool is_synced_user = false; - bool has_errors = false; - - if (!arg->GetString("profilePath", &profile_path) || - !arg->GetBoolean("isSyncedUser", &is_synced_user) || - !arg->GetBoolean("hasErrors", &has_errors)) - return; - - int total_count = 0; - if (!arg->GetInteger("totalCount", &total_count)) - return; - - int message_id = is_synced_user ? - (has_errors ? IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_WITH_ERRORS : - IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC) : - (has_errors ? IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_WITH_ERRORS : - IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC); - - base::Value message = - base::Value(l10n_util::GetPluralStringFUTF16(message_id, total_count)); - - web_ui()->CallJavascriptFunctionUnsafe("updateRemoveWarningDialogSetMessage", - base::Value(profile_path), message, - base::Value(total_count)); -} - void UserManagerScreenHandler::OnGetTokenInfoResponse( std::unique_ptr<base::DictionaryValue> token_info) { // Password is unchanged so user just mistyped it. Ask again. @@ -726,10 +689,6 @@ base::Bind(&UserManagerScreenHandler::HandleRemoveUserWarningLoadStats, base::Unretained(this))); web_ui()->RegisterMessageCallback( - kJsApiUserManagerGetRemoveWarningDialogMessage, - base::Bind(&UserManagerScreenHandler::HandleGetRemoveWarningDialogMessage, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( kJsApiUserManagerAreAllProfilesLocked, base::Bind(&UserManagerScreenHandler::HandleAreAllProfilesLocked, base::Unretained(this))); @@ -790,12 +749,9 @@ // For AccountPickerScreen, the remove user warning overlay. localized_strings->SetString("removeUserWarningButtonTitle", l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON)); - localized_strings->SetString("removeUserWarningTextNonSyncNoStats", - l10n_util::GetStringUTF16( - IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_NOSTATS)); - localized_strings->SetString("removeUserWarningTextNonSyncCalculating", - l10n_util::GetStringUTF16( - IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC_CALCULATING)); + localized_strings->SetString( + "removeUserWarningTextNonSync", + l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_NONSYNC)); localized_strings->SetString("removeUserWarningTextHistory", l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_HISTORY)); localized_strings->SetString("removeUserWarningTextPasswords", @@ -807,12 +763,9 @@ l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_AUTOFILL)); localized_strings->SetString("removeUserWarningTextCalculating", l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_CALCULATING)); - localized_strings->SetString("removeUserWarningTextSyncNoStats", - l10n_util::GetStringUTF16( - IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_NOSTATS)); - localized_strings->SetString("removeUserWarningTextSyncCalculating", - l10n_util::GetStringUTF16( - IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC_CALCULATING)); + localized_strings->SetString( + "removeUserWarningTextSync", + l10n_util::GetStringUTF16(IDS_LOGIN_POD_USER_REMOVE_WARNING_SYNC)); localized_strings->SetString("removeLegacySupervisedUserWarningText", l10n_util::GetStringFUTF16( IDS_LOGIN_POD_LEGACY_SUPERVISED_USER_REMOVE_WARNING, @@ -938,17 +891,6 @@ profile_value->SetBoolean(kKeyIsDesktop, true); profile_value->SetString(kKeyAvatarUrl, GetAvatarImage(entry)); - // Add statistics dictionary (the actual statistics will be populated - // once they are retrieved from the profile). - auto stats_dict = base::MakeUnique<base::DictionaryValue>(); - for (const char* category : profiles::kProfileStatisticsCategories) { - auto stat = base::MakeUnique<base::DictionaryValue>(); - stat->SetIntegerWithoutPathExpansion("count", 0); - stat->SetBooleanWithoutPathExpansion("success", false); - stats_dict->SetWithoutPathExpansion(category, std::move(stat)); - } - profile_value->SetWithoutPathExpansion(kKeyStatistics, - std::move(stats_dict)); // GetProfileByPath returns a pointer if the profile is fully loaded, NULL // otherwise. Profile* profile =
diff --git a/chrome/browser/web_applications/web_app.cc b/chrome/browser/web_applications/web_app.cc index 298dcb9..4dc5f53 100644 --- a/chrome/browser/web_applications/web_app.cc +++ b/chrome/browser/web_applications/web_app.cc
@@ -15,7 +15,9 @@ #include "base/macros.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/task_scheduler/post_task.h" #include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_ui_util.h" @@ -90,14 +92,10 @@ const base::Closure& callback, std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - BrowserThread::PostTaskAndReply( - BrowserThread::FILE, FROM_HERE, - base::Bind(&web_app::internals::UpdatePlatformShortcuts, - shortcut_data_dir, old_app_title, - base::ConstRef(shortcut_info_ref)), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), callback)); + web_app::ShortcutInfo::PostIOTaskAndReply( + base::BindOnce(&web_app::internals::UpdatePlatformShortcuts, + shortcut_data_dir, old_app_title), + std::move(shortcut_info), callback); } void OnImageLoaded(std::unique_ptr<web_app::ShortcutInfo> shortcut_info, @@ -129,16 +127,19 @@ const web_app::ShortcutLocations& locations, std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); - - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - BrowserThread::PostTaskAndReply( - BrowserThread::FILE, FROM_HERE, - base::Bind( + web_app::ShortcutInfo::PostIOTask( + base::BindOnce( base::IgnoreResult(&web_app::internals::CreatePlatformShortcuts), - shortcut_data_dir, base::ConstRef(shortcut_info_ref), locations, - reason), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + shortcut_data_dir, locations, reason), + std::move(shortcut_info)); +} + +void DeleteShortcutInfoOnUIThread( + std::unique_ptr<web_app::ShortcutInfo> shortcut_info, + base::OnceClosure callback) { + shortcut_info.reset(); + if (callback) + std::move(callback).Run(); } } // namespace @@ -165,14 +166,6 @@ return base::FilePath(file_name); } -void DeleteShortcutInfoOnUIThread( - std::unique_ptr<web_app::ShortcutInfo> shortcut_info, - const base::Closure& callback) { - shortcut_info.reset(); - if (callback) - callback.Run(); -} - } // namespace internals ShortcutInfo::ShortcutInfo() {} @@ -181,6 +174,45 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); } +// static +void ShortcutInfo::PostIOTask( + base::OnceCallback<void(const ShortcutInfo&)> task, + std::unique_ptr<ShortcutInfo> shortcut_info) { + PostIOTaskAndReply(std::move(task), std::move(shortcut_info), + base::Closure()); +} + +// static +void ShortcutInfo::PostIOTaskAndReply( + base::OnceCallback<void(const ShortcutInfo&)> task, + std::unique_ptr<ShortcutInfo> shortcut_info, + const base::Closure& reply) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // Ownership of |shortcut_info| moves to the Reply, which is guaranteed to + // outlive the const reference. + const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; + GetTaskRunner()->PostTaskAndReply( + FROM_HERE, + base::BindOnce(std::move(task), base::ConstRef(shortcut_info_ref)), + base::BindOnce(&DeleteShortcutInfoOnUIThread, std::move(shortcut_info), + reply)); +} + +// static +scoped_refptr<base::TaskRunner> ShortcutInfo::GetTaskRunner() { + constexpr base::TaskTraits traits = { + base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}; + +#if defined(OS_WIN) + return base::TaskScheduler::GetInstance()->CreateCOMSTATaskRunnerWithTraits( + traits, base::SingleThreadTaskRunnerThreadMode::SHARED); +#else + return base::TaskScheduler::GetInstance()->CreateTaskRunnerWithTraits(traits); +#endif +} + ShortcutLocations::ShortcutLocations() : on_desktop(false), applications_menu_location(APP_MENU_LOCATION_NONE), @@ -445,14 +477,9 @@ std::unique_ptr<ShortcutInfo> shortcut_info( ShortcutInfoForExtensionAndProfile(app, profile)); base::FilePath shortcut_data_dir = GetShortcutDataDir(*shortcut_info); - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - - BrowserThread::PostTaskAndReply( - BrowserThread::FILE, FROM_HERE, - base::Bind(&web_app::internals::DeletePlatformShortcuts, - shortcut_data_dir, base::ConstRef(shortcut_info_ref)), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + ShortcutInfo::PostIOTask( + base::BindOnce(&internals::DeletePlatformShortcuts, shortcut_data_dir), + std::move(shortcut_info)); } void UpdateAllShortcuts(const base::string16& old_app_title,
diff --git a/chrome/browser/web_applications/web_app.h b/chrome/browser/web_applications/web_app.h index 2c8d2cf5..695af275 100644 --- a/chrome/browser/web_applications/web_app.h +++ b/chrome/browser/web_applications/web_app.h
@@ -19,6 +19,10 @@ class Profile; +namespace base { +class TaskRunner; +} + namespace content { class WebContents; } @@ -41,6 +45,24 @@ ShortcutInfo(); ~ShortcutInfo(); + // Run an IO task on a worker thread. Ownership of |shortcut_info| transfers + // to a closure that deletes it on the UI thread when the task is complete. + // Tasks posted here run with BACKGROUND priority and block shutdown. + // TODO(tapted): |reply| should be a OnceClosure, but first + // extensions::ImageLoaderImageCallback must be converted. + static void PostIOTask(base::OnceCallback<void(const ShortcutInfo&)> task, + std::unique_ptr<ShortcutInfo> shortcut_info); + static void PostIOTaskAndReply( + base::OnceCallback<void(const ShortcutInfo&)> task, + std::unique_ptr<ShortcutInfo> shortcut_info, + const base::Closure& reply); + + // The task runner for running shortcut tasks. On Windows this will be a task + // runner that permits access to COM libraries. Shortcut tasks typically deal + // with ensuring Profile changes are reflected on disk, so shutdown is always + // blocked so that an inconsistent shortcut state is not left on disk. + static scoped_refptr<base::TaskRunner> GetTaskRunner(); + GURL url; // If |extension_id| is non-empty, this is short cut is to an extension-app // and the launch url will be detected at start-up. In this case, |url| @@ -229,9 +251,9 @@ // |shortcut_info| contains info about the shortcut to create, and // |creation_locations| contains information about where to create them. bool CreatePlatformShortcuts(const base::FilePath& shortcut_data_path, - const ShortcutInfo& shortcut_info, const ShortcutLocations& creation_locations, - ShortcutCreationReason creation_reason); + ShortcutCreationReason creation_reason, + const ShortcutInfo& shortcut_info); // Delete all the shortcuts we have added for this extension. This is the // platform specific implementation of the DeleteAllShortcuts function, and @@ -254,10 +276,6 @@ // on-disk file name . base::FilePath GetSanitizedFileName(const base::string16& name); -// Clears |shortcut_info| and invokes |callback| unless it's null. -void DeleteShortcutInfoOnUIThread(std::unique_ptr<ShortcutInfo> shortcut_info, - const base::Closure& callback); - } // namespace internals } // namespace web_app
diff --git a/chrome/browser/web_applications/web_app_chromeos.cc b/chrome/browser/web_applications/web_app_chromeos.cc index f90fc9f..6e1ea6f 100644 --- a/chrome/browser/web_applications/web_app_chromeos.cc +++ b/chrome/browser/web_applications/web_app_chromeos.cc
@@ -14,9 +14,9 @@ namespace internals { bool CreatePlatformShortcuts(const base::FilePath& web_app_path, - const ShortcutInfo& shortcut_info, const ShortcutLocations& creation_locations, - ShortcutCreationReason creation_reason) { + ShortcutCreationReason creation_reason, + const ShortcutInfo& shortcut_info) { return true; }
diff --git a/chrome/browser/web_applications/web_app_linux.cc b/chrome/browser/web_applications/web_app_linux.cc index b9b929f..c5e7b41 100644 --- a/chrome/browser/web_applications/web_app_linux.cc +++ b/chrome/browser/web_applications/web_app_linux.cc
@@ -8,9 +8,9 @@ #include "base/environment.h" #include "base/logging.h" +#include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/shell_integration_linux.h" -#include "content/public/browser/browser_thread.h" namespace web_app { @@ -22,11 +22,11 @@ namespace internals { bool CreatePlatformShortcuts(const base::FilePath& web_app_path, - const ShortcutInfo& shortcut_info, const ShortcutLocations& creation_locations, - ShortcutCreationReason /*creation_reason*/) { + ShortcutCreationReason /*creation_reason*/, + const ShortcutInfo& shortcut_info) { #if !defined(OS_CHROMEOS) - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); return shell_integration_linux::CreateDesktopShortcut(shortcut_info, creation_locations); #else @@ -45,7 +45,7 @@ void UpdatePlatformShortcuts(const base::FilePath& web_app_path, const base::string16& /*old_app_title*/, const ShortcutInfo& shortcut_info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); std::unique_ptr<base::Environment> env(base::Environment::Create()); @@ -60,8 +60,8 @@ if (creation_locations.applications_menu_location == APP_MENU_LOCATION_NONE) creation_locations.applications_menu_location = APP_MENU_LOCATION_HIDDEN; - CreatePlatformShortcuts(web_app_path, shortcut_info, creation_locations, - SHORTCUT_CREATION_AUTOMATED); + CreatePlatformShortcuts(web_app_path, creation_locations, + SHORTCUT_CREATION_AUTOMATED, shortcut_info); } void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
diff --git a/chrome/browser/web_applications/web_app_mac.mm b/chrome/browser/web_applications/web_app_mac.mm index b51db20..5837821 100644 --- a/chrome/browser/web_applications/web_app_mac.mm +++ b/chrome/browser/web_applications/web_app_mac.mm
@@ -32,6 +32,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/post_task.h" +#include "base/threading/thread_restrictions.h" #include "base/version.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_ui_util.h" @@ -215,9 +216,9 @@ user_data_dir.value(), base::CompareCase::SENSITIVE); } -void LaunchShimOnFileThread(const web_app::ShortcutInfo& shortcut_info, - bool launched_after_rebuild) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); +void LaunchShimOnFileThread(bool launched_after_rebuild, + const web_app::ShortcutInfo& shortcut_info) { + base::ThreadRestrictions::AssertIOAllowed(); base::FilePath shim_path = web_app::GetAppInstallPath(shortcut_info); if (shim_path.empty() || @@ -254,7 +255,7 @@ const base::FilePath& app_data_path, const base::string16& old_app_title, const web_app::ShortcutInfo& shortcut_info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); if (AppShimsDisabledForTest() && !g_app_shims_allow_update_and_launch_in_tests) { return; @@ -267,21 +268,18 @@ void UpdateAndLaunchShimOnFileThread( const web_app::ShortcutInfo& shortcut_info) { + base::ThreadRestrictions::AssertIOAllowed(); base::FilePath shortcut_data_dir = web_app::GetWebAppDataDirectory( shortcut_info.profile_path, shortcut_info.extension_id, GURL()); UpdatePlatformShortcutsInternal(shortcut_data_dir, base::string16(), shortcut_info); - LaunchShimOnFileThread(shortcut_info, true); + LaunchShimOnFileThread(true, shortcut_info); } void UpdateAndLaunchShim(std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - content::BrowserThread::PostTaskAndReply( - content::BrowserThread::FILE, FROM_HERE, - base::Bind(&UpdateAndLaunchShimOnFileThread, - base::ConstRef(shortcut_info_ref)), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + web_app::ShortcutInfo::PostIOTask( + base::BindOnce(&UpdateAndLaunchShimOnFileThread), + std::move(shortcut_info)); } void RebuildAppAndLaunch(std::unique_ptr<web_app::ShortcutInfo> shortcut_info) { @@ -382,10 +380,11 @@ using ResourceIDToImage = std::map<int, gfx::Image>; -// Returns a map of gfx::Image used by SetWorkspaceIconOnFILEThread. -// Since ui::ResourceBundle can be call only on UI thread, this function also -// needs to run on UI thread. -std::unique_ptr<ResourceIDToImage> GetImageResourcesOnUIThread() { +// Generates a map of gfx::Image used by SetWorkspaceIconOnFILEThread and +// passes it to |io_task|. Since ui::ResourceBundle can be call only on UI +// thread, this function also needs to run on UI thread. +void GetImageResourcesOnUIThread( + base::OnceCallback<void(std::unique_ptr<ResourceIDToImage>)> io_task) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ui::ResourceBundle& resource_bundle = ui::ResourceBundle::GetSharedInstance(); @@ -397,12 +396,17 @@ for (int id : {IDR_APPS_FOLDER_16, IDR_APPS_FOLDER_32, IDR_APPS_FOLDER_OVERLAY_128, IDR_APPS_FOLDER_OVERLAY_512}) (*result)[id] = resource_bundle.GetNativeImageNamed(id); - return result; + + base::PostTaskWithTraits( + FROM_HERE, + {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(std::move(io_task), std::move(result))); } void SetWorkspaceIconOnFILEThread(const base::FilePath& apps_directory, std::unique_ptr<ResourceIDToImage> images) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); base::scoped_nsobject<NSImage> folder_icon_image([[NSImage alloc] init]); // Use complete assets for the small icon sizes. -[NSWorkspace setIcon:] has a @@ -467,10 +471,11 @@ [strings_dict writeToFile:strings_path atomically:YES]; - content::BrowserThread::PostTaskAndReplyWithResult( + content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, - base::BindOnce(&GetImageResourcesOnUIThread), - base::BindOnce(&SetWorkspaceIconOnFILEThread, apps_directory)); + base::BindOnce( + &GetImageResourcesOnUIThread, + base::BindOnce(&SetWorkspaceIconOnFILEThread, apps_directory))); } void DeletePathAndParentIfEmpty(const base::FilePath& app_path) { @@ -562,8 +567,8 @@ } void RevealAppShimInFinderForAppOnFileThread( - const web_app::ShortcutInfo& shortcut_info, - const base::FilePath& app_path) { + const base::FilePath& app_path, + const web_app::ShortcutInfo& shortcut_info) { web_app::WebAppShortcutCreator shortcut_creator(app_path, &shortcut_info); shortcut_creator.RevealAppShimInFinder(); } @@ -1012,13 +1017,8 @@ return; } - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - content::BrowserThread::PostTaskAndReply( - content::BrowserThread::FILE, FROM_HERE, - base::Bind(&LaunchShimOnFileThread, base::ConstRef(shortcut_info_ref), - false), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + web_app::ShortcutInfo::PostIOTask( + base::BindOnce(&LaunchShimOnFileThread, false), std::move(shortcut_info)); } bool MaybeRebuildShortcut(const base::CommandLine& command_line) { @@ -1027,9 +1027,9 @@ base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, - base::Bind(&RecordAppShimErrorAndBuildShortcutInfo, - command_line.GetSwitchValuePath(app_mode::kAppShimError)), - base::Bind(&RebuildAppAndLaunch)); + base::BindOnce(&RecordAppShimErrorAndBuildShortcutInfo, + command_line.GetSwitchValuePath(app_mode::kAppShimError)), + base::BindOnce(&RebuildAppAndLaunch)); return true; } @@ -1058,24 +1058,18 @@ void RevealAppShimInFinderForApp(Profile* profile, const extensions::Extension* app) { - std::unique_ptr<web_app::ShortcutInfo> shortcut_info = - ShortcutInfoForExtensionAndProfile(app, profile); - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - content::BrowserThread::PostTaskAndReply( - content::BrowserThread::FILE, FROM_HERE, - base::Bind(&RevealAppShimInFinderForAppOnFileThread, - base::ConstRef(shortcut_info_ref), app->path()), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + web_app::ShortcutInfo::PostIOTask( + base::BindOnce(&RevealAppShimInFinderForAppOnFileThread, app->path()), + ShortcutInfoForExtensionAndProfile(app, profile)); } namespace internals { bool CreatePlatformShortcuts(const base::FilePath& app_data_path, - const ShortcutInfo& shortcut_info, const ShortcutLocations& creation_locations, - ShortcutCreationReason creation_reason) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + ShortcutCreationReason creation_reason, + const ShortcutInfo& shortcut_info) { + base::ThreadRestrictions::AssertIOAllowed(); if (AppShimsDisabledForTest()) return true; @@ -1085,7 +1079,7 @@ void DeletePlatformShortcuts(const base::FilePath& app_data_path, const ShortcutInfo& shortcut_info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); WebAppShortcutCreator shortcut_creator(app_data_path, &shortcut_info); shortcut_creator.DeleteShortcuts(); } @@ -1097,6 +1091,7 @@ } void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) { + base::ThreadRestrictions::AssertIOAllowed(); const std::string profile_base_name = profile_path.BaseName().value(); std::vector<base::FilePath> bundles = GetAllAppBundlesInPath( profile_path.Append(chrome::kWebAppDirname), profile_base_name);
diff --git a/chrome/browser/web_applications/web_app_win.cc b/chrome/browser/web_applications/web_app_win.cc index ef26f880..0b6ee7b 100644 --- a/chrome/browser/web_applications/web_app_win.cc +++ b/chrome/browser/web_applications/web_app_win.cc
@@ -20,7 +20,7 @@ #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" -#include "base/task_scheduler/post_task.h" +#include "base/threading/thread_restrictions.h" #include "base/win/shortcut.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/shell_integration_win.h" @@ -286,7 +286,7 @@ const base::string16& title, bool* was_pinned_to_taskbar, std::vector<base::FilePath>* shortcut_paths) { - DCHECK(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); // Get all possible locations for shortcuts. web_app::ShortcutLocations all_shortcut_locations; @@ -332,10 +332,11 @@ } } -void CreateIconAndSetRelaunchDetails(const base::FilePath& web_app_path, - const base::FilePath& icon_file, - const web_app::ShortcutInfo& shortcut_info, - HWND hwnd) { +void CreateIconAndSetRelaunchDetails( + const base::FilePath& web_app_path, + const base::FilePath& icon_file, + HWND hwnd, + const web_app::ShortcutInfo& shortcut_info) { base::CommandLine command_line = shell_integration::CommandLineArgsForLauncher(shortcut_info.url, shortcut_info.extension_id, @@ -369,13 +370,11 @@ shortcut_info->url); base::FilePath icon_file = web_app::internals::GetIconFilePath(web_app_path, shortcut_info->title); - const web_app::ShortcutInfo& shortcut_info_ref = *shortcut_info; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::Bind(&CreateIconAndSetRelaunchDetails, web_app_path, icon_file, - base::ConstRef(shortcut_info_ref), hwnd), - base::Bind(&web_app::internals::DeleteShortcutInfoOnUIThread, - base::Passed(&shortcut_info), base::Closure())); + + web_app::ShortcutInfo::PostIOTask( + base::BindOnce(&CreateIconAndSetRelaunchDetails, web_app_path, icon_file, + hwnd), + std::move(shortcut_info)); } } // namespace @@ -440,10 +439,10 @@ } bool CreatePlatformShortcuts(const base::FilePath& web_app_path, - const ShortcutInfo& shortcut_info, const ShortcutLocations& creation_locations, - ShortcutCreationReason creation_reason) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + ShortcutCreationReason creation_reason, + const ShortcutInfo& shortcut_info) { + base::ThreadRestrictions::AssertIOAllowed(); // Nothing to do on Windows for hidden apps. if (creation_locations.applications_menu_location == APP_MENU_LOCATION_HIDDEN) @@ -486,7 +485,7 @@ void UpdatePlatformShortcuts(const base::FilePath& web_app_path, const base::string16& old_app_title, const ShortcutInfo& shortcut_info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); + base::ThreadRestrictions::AssertIOAllowed(); // Generates file name to use with persisted ico and shortcut file. base::FilePath file_name = @@ -540,6 +539,7 @@ } void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) { + base::ThreadRestrictions::AssertIOAllowed(); GetShortcutLocationsAndDeleteShortcuts(base::FilePath(), profile_path, L"", NULL, NULL);
diff --git a/chrome/browser/win/jumplist.cc b/chrome/browser/win/jumplist.cc index 7ebb5ea..9ab614b 100644 --- a/chrome/browser/win/jumplist.cc +++ b/chrome/browser/win/jumplist.cc
@@ -275,8 +275,13 @@ // If we have a pending favicon request, cancel it here as it's out of date. CancelPendingUpdate(); - // Initialize the one-shot timer to update the JumpList in a while. - InitializeTimerForUpdate(); + // When the first tab is closed in one session, it doesn't trigger an update + // but a TopSites sync. This sync will trigger an update for both mostly + // visited and recently closed categories. We don't delay this TopSites sync. + if (has_topsites_sync) + InitializeTimerForUpdate(); + else + ProcessNotifications(); } void JumpList::TabRestoreServiceChanged(sessions::TabRestoreService* service) { @@ -309,15 +314,20 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (timer_.IsRunning()) { + // TODO(chengx): Remove the UMA histogram below after fixing crbug/733034. + UMA_HISTOGRAM_COUNTS_10000( + "WinJumplist.NotificationTimeInterval", + (timer_.desired_run_time() - base::TimeTicks::Now()).InMilliseconds()); timer_.Reset(); } else { // base::Unretained is safe since |this| is guaranteed to outlive timer_. - timer_.Start(FROM_HERE, kDelayForJumplistUpdate, - base::Bind(&JumpList::OnDelayTimer, base::Unretained(this))); + timer_.Start( + FROM_HERE, kDelayForJumplistUpdate, + base::Bind(&JumpList::ProcessNotifications, base::Unretained(this))); } } -void JumpList::OnDelayTimer() { +void JumpList::ProcessNotifications() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!update_in_progress_); @@ -330,6 +340,17 @@ if (tab_restore_has_pending_notification_) { tab_restore_has_pending_notification_ = false; ProcessTabRestoreServiceNotification(); + + // Force a TopSite history sync when closing a first tab in one session. + if (!has_tab_closed_) { + has_tab_closed_ = true; + scoped_refptr<history::TopSites> top_sites = + TopSitesFactory::GetForProfile(profile_); + if (top_sites) { + top_sites->SyncWithHistory(); + return; + } + } } // If TopSites has updates, retrieve the URLs asynchronously, and on its @@ -354,6 +375,8 @@ return; } + has_topsites_sync = true; + scoped_refptr<history::TopSites> top_sites = TopSitesFactory::GetForProfile(profile_); if (top_sites) { @@ -400,15 +423,6 @@ } recently_closed_should_update_ = true; - - // Force a TopSite history sync when closing a first tab in one session. - if (!has_tab_closed_) { - has_tab_closed_ = true; - scoped_refptr<history::TopSites> top_sites = - TopSitesFactory::GetForProfile(profile_); - if (top_sites) - top_sites->SyncWithHistory(); - } } void JumpList::OnMostVisitedURLsAvailable( @@ -753,6 +767,9 @@ return; } + base::TimeDelta most_visited_category_time = + add_custom_category_timer.Elapsed(); + // Update the "Recently Closed" category of the JumpList. if (!jumplist_updater.AddCustomCategory( l10n_util::GetStringUTF16(IDS_RECENTLY_CLOSED), recently_closed_pages, @@ -760,9 +777,25 @@ return; } + base::TimeDelta add_category_total_time = add_custom_category_timer.Elapsed(); + + if (recently_closed_pages.size() == kRecentlyClosedItems && + most_visited_pages.size() == kMostVisitedItems) { + // TODO(chengx): Remove the UMA histogram after fixing crbug/736530. + double most_visited_over_recently_closed = + most_visited_category_time.InMillisecondsF() / + (add_category_total_time - most_visited_category_time) + .InMillisecondsF(); + + // The ratio above is typically between 1 and 10. Multiply it by 10 to + // retain decimal precision. + UMA_HISTOGRAM_COUNTS_100("WinJumplist.RatioAddCategoryTime", + most_visited_over_recently_closed * 10); + } + // If AddCustomCategory takes longer than the maximum allowed time, abort the // current update and skip the next |kUpdatesToSkipUnderHeavyLoad| updates. - if (add_custom_category_timer.Elapsed() >= kTimeOutForAddCustomCategory) { + if (add_category_total_time >= kTimeOutForAddCustomCategory) { update_transaction->update_timeout = true; return; }
diff --git a/chrome/browser/win/jumplist.h b/chrome/browser/win/jumplist.h index 30df9199..fdcf6f65 100644 --- a/chrome/browser/win/jumplist.h +++ b/chrome/browser/win/jumplist.h
@@ -124,10 +124,9 @@ // quiet period, thus avoiding update storms. void InitializeTimerForUpdate(); - // Called on a timer after requests storms have subsided. Calls APIs - // ProcessTopSitesNotification and ProcessTabRestoreNotification on - // demand to do the actual work. - void OnDelayTimer(); + // Processes update notifications. Calls APIs ProcessTopSitesNotification and + // ProcessTabRestoreNotification on demand to do the actual work. + void ProcessNotifications(); // Processes notifications from TopSites service. void ProcessTopSitesNotification(); @@ -282,6 +281,9 @@ // A flag indicating if a session has at least one tab closed. bool has_tab_closed_ = false; + // A flag indicating if a session has at least one top sites sync. + bool has_topsites_sync = false; + // Number of updates to skip to alleviate the machine when a previous update // was too slow. Updates will be resumed when this reaches 0 again. int updates_to_skip_ = 0;
diff --git a/chrome/common/chrome_constants.cc b/chrome/common/chrome_constants.cc index 94cdc2a..e4ce7d5 100644 --- a/chrome/common/chrome_constants.cc +++ b/chrome/common/chrome_constants.cc
@@ -157,6 +157,8 @@ FPL("Offline Pages/archives"); const base::FilePath::CharType kOfflinePageMetadataDirname[] = FPL("Offline Pages/metadata"); +const base::FilePath::CharType kOfflinePagePrefetchStoreDirname[] = + FPL("Offline Pages/prefech_store"); const base::FilePath::CharType kOfflinePageRequestQueueDirname[] = FPL("Offline Pages/request_queue"); const base::FilePath::CharType kPreferencesFilename[] = FPL("Preferences");
diff --git a/chrome/common/chrome_constants.h b/chrome/common/chrome_constants.h index 8321b76..a170109 100644 --- a/chrome/common/chrome_constants.h +++ b/chrome/common/chrome_constants.h
@@ -59,6 +59,7 @@ extern const base::FilePath::CharType kMediaCacheDirname[]; extern const base::FilePath::CharType kOfflinePageArchivesDirname[]; extern const base::FilePath::CharType kOfflinePageMetadataDirname[]; +extern const base::FilePath::CharType kOfflinePagePrefetchStoreDirname[]; extern const base::FilePath::CharType kOfflinePageRequestQueueDirname[]; extern const base::FilePath::CharType kPreferencesFilename[]; extern const base::FilePath::CharType kPreviewsOptOutDBFilename[];
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 15ca32a..149f3e00d 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -878,6 +878,9 @@ // Specifies Android phone page loading progress bar animation. const char kProgressBarAnimation[] = "progress-bar-animation"; +// Use a static URL for the logo of the default search engine. +const char kSearchProviderLogoURL[] = "search-provider-logo-url"; + // Specifies a particular tab management experiment to enable. const char kTabManagementExperimentTypeDisabled[] = "tab-management-experiment-type-disabled"; @@ -923,6 +926,10 @@ // or KWallets. const char kPasswordStore[] = "password-store"; +// Enables the feature of allowing the user to disable the backend via a +// setting. +const char kEnableEncryptionSelection[] = "enable-encryption-selection"; + // The same as the --class argument in X applications. Overrides the WM_CLASS // window property with the given value. const char kWmClass[] = "class";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 15e5f75..bdc29d2 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -252,6 +252,7 @@ extern const char kMarketUrlForTesting[]; extern const char kNtpSwitchToExistingTab[]; extern const char kProgressBarAnimation[]; +extern const char kSearchProviderLogoURL[]; extern const char kTabManagementExperimentTypeDisabled[]; extern const char kTabManagementExperimentTypeElderberry[]; extern const char kWebApkServerUrl[]; @@ -272,6 +273,7 @@ extern const char kHelp[]; extern const char kHelpShort[]; extern const char kPasswordStore[]; +extern const char kEnableEncryptionSelection[]; extern const char kWmClass[]; #endif
diff --git a/chrome/installer/util/google_update_settings.cc b/chrome/installer/util/google_update_settings.cc index d7f4423a..42a2c0cc 100644 --- a/chrome/installer/util/google_update_settings.cc +++ b/chrome/installer/util/google_update_settings.cc
@@ -17,6 +17,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/task_scheduler/lazy_task_runner.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" #include "base/win/registry.h" @@ -57,6 +58,11 @@ namespace { +base::LazySequencedTaskRunner g_collect_stats_consent_task_runner = + LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER( + base::TaskTraits(base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN)); + bool ReadGoogleUpdateStrKey(const wchar_t* const name, base::string16* value) { BrowserDistribution* dist = BrowserDistribution::GetDistribution(); base::string16 reg_path = dist->GetStateKey(); @@ -195,6 +201,13 @@ return !InstallUtil::IsPerUserInstall(); } +base::SequencedTaskRunner* +GoogleUpdateSettings::CollectStatsConsentTaskRunner() { + // TODO(fdoray): Use LazySequencedTaskRunner::GetRaw() here instead of + // .Get().get() when it's added to the API, http://crbug.com/730170. + return g_collect_stats_consent_task_runner.Get().get(); +} + bool GoogleUpdateSettings::GetCollectStatsConsent() { return GetCollectStatsConsentAtLevel(IsSystemInstall()); }
diff --git a/chrome/installer/util/google_update_settings.h b/chrome/installer/util/google_update_settings.h index 99174f5..2fa7d57a 100644 --- a/chrome/installer/util/google_update_settings.h +++ b/chrome/installer/util/google_update_settings.h
@@ -12,6 +12,8 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner.h" #include "base/strings/string16.h" #include "base/strings/string_piece.h" #include "base/time/time.h" @@ -76,6 +78,15 @@ // Returns true if this install is system-wide, false if it is per-user. static bool IsSystemInstall(); + // Returns the SequencedTaskRunner to be used to sequence calls to + // Get/SetCollectStatsConsent(). Tasks posted through this will run with + // USER_VISIBLE priority and will block shutdown. + // Note: There is not enforcement to ensure that all such calls go through + // this SequencedTaskRunner but callers that don't are responsible to ensure + // nothing else is racing with them (e.g. those calls can be called + // synchronously on first run, startup, etc.). + static base::SequencedTaskRunner* CollectStatsConsentTaskRunner(); + // Returns whether the user has given consent to collect UMA data and send // crash dumps to Google. This information is collected by the web server // used to download the chrome installer.
diff --git a/chrome/installer/zucchini/buffer_view.h b/chrome/installer/zucchini/buffer_view.h index f2876ae..cf13fc48 100644 --- a/chrome/installer/zucchini/buffer_view.h +++ b/chrome/installer/zucchini/buffer_view.h
@@ -14,10 +14,8 @@ namespace zucchini { namespace internal { -// A class that encapsulates a contiguous sequence of raw data. -// It does not own the memory region it encapsulates. -// BufferViewBase should not be used directly; it is an implementation -// used for both BufferView and MutableBufferView. +// BufferViewBase should not be used directly; it is an implementation used for +// both BufferView and MutableBufferView. template <class T> class BufferViewBase { public: @@ -40,7 +38,10 @@ BufferViewBase() = default; BufferViewBase(iterator first, size_type size) - : first_(first), last_(first_ + size) {} + : first_(first), last_(first_ + size) { + DCHECK(last_ >= first_); + } + BufferViewBase(const BufferViewBase&) = default; BufferViewBase& operator=(const BufferViewBase&) = default; @@ -53,9 +54,10 @@ // Element access - // Returns the raw value at specified location pos. + // Returns the raw value at specified location |pos|. + // If |pos| is not within the range of the buffer, the process is terminated. reference operator[](size_type pos) const { - DCHECK(first_ + pos < last_); + CHECK(first_ + pos < last_); return first_[pos]; } @@ -78,12 +80,10 @@ } // namespace internal -// A class that encapsulates a constant contiguous sequence of raw data. -// It does not own the memory region it refers to. -using BufferView = internal::BufferViewBase<const uint8_t>; +// Classes to encapsulate a contiguous sequence of raw data, without owning the +// encapsulated memory regions. These are intended to be used as value types. -// A class that encapsulates a mutable contiguous sequence of raw data. -// It does not own the memory region it refers to. +using ConstBufferView = internal::BufferViewBase<const uint8_t>; using MutableBufferView = internal::BufferViewBase<uint8_t>; } // namespace zucchini
diff --git a/chrome/installer/zucchini/buffer_view_unittest.cc b/chrome/installer/zucchini/buffer_view_unittest.cc index dbdda345..e2424cc 100644 --- a/chrome/installer/zucchini/buffer_view_unittest.cc +++ b/chrome/installer/zucchini/buffer_view_unittest.cc
@@ -14,48 +14,46 @@ class BufferViewTest : public testing::Test { protected: - static constexpr size_t kLen = 10; + enum : size_t { kLen = 10 }; // Some tests might modify this. uint8_t bytes_[kLen] = {0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, 0x10, 0x00}; }; -constexpr size_t BufferViewTest::kLen; - TEST_F(BufferViewTest, Size) { for (size_t len = 0; len <= kLen; ++len) { - EXPECT_EQ(len, BufferView(std::begin(bytes_), len).size()); + EXPECT_EQ(len, ConstBufferView(std::begin(bytes_), len).size()); EXPECT_EQ(len, MutableBufferView(std::begin(bytes_), len).size()); } } TEST_F(BufferViewTest, Empty) { // Empty view. - EXPECT_TRUE(BufferView(std::begin(bytes_), 0).empty()); + EXPECT_TRUE(ConstBufferView(std::begin(bytes_), 0).empty()); EXPECT_TRUE(MutableBufferView(std::begin(bytes_), 0).empty()); for (size_t len = 1; len <= kLen; ++len) { - EXPECT_FALSE(BufferView(std::begin(bytes_), len).empty()); + EXPECT_FALSE(ConstBufferView(std::begin(bytes_), len).empty()); EXPECT_FALSE(MutableBufferView(std::begin(bytes_), len).empty()); } } TEST_F(BufferViewTest, FromRange) { - BufferView buffer = - BufferView::FromRange(std::begin(bytes_), std::end(bytes_)); + ConstBufferView buffer = + ConstBufferView::FromRange(std::begin(bytes_), std::end(bytes_)); EXPECT_EQ(kLen, buffer.size()); EXPECT_EQ(std::begin(bytes_), buffer.begin()); EXPECT_DCHECK_DEATH( - BufferView::FromRange(std::end(bytes_), std::begin(bytes_))); + ConstBufferView::FromRange(std::end(bytes_), std::begin(bytes_))); EXPECT_DCHECK_DEATH( - BufferView::FromRange(std::begin(bytes_) + 1, std::begin(bytes_))); + ConstBufferView::FromRange(std::begin(bytes_) + 1, std::begin(bytes_))); } TEST_F(BufferViewTest, Subscript) { - BufferView view(std::begin(bytes_), kLen); + ConstBufferView view(std::begin(bytes_), kLen); EXPECT_EQ(0x10, view[0]); static_assert(!std::is_assignable<decltype(view[0]), uint8_t>::value, @@ -69,8 +67,8 @@ } TEST_F(BufferViewTest, Shrink) { - BufferView buffer = - BufferView::FromRange(std::begin(bytes_), std::end(bytes_)); + ConstBufferView buffer = + ConstBufferView::FromRange(std::begin(bytes_), std::end(bytes_)); buffer.shrink(kLen); EXPECT_EQ(kLen, buffer.size());
diff --git a/chrome/installer/zucchini/disassembler.cc b/chrome/installer/zucchini/disassembler.cc index 93dbcf6..8427c1d 100644 --- a/chrome/installer/zucchini/disassembler.cc +++ b/chrome/installer/zucchini/disassembler.cc
@@ -12,8 +12,8 @@ offset_t lower, offset_t upper, Disassembler* disasm) const { - DCHECK(lower <= upper); - DCHECK(upper <= disasm->size()); + DCHECK_LE(lower, upper); + DCHECK_LE(upper, disasm->size()); return (disasm->*reader_factory_)(lower, upper); } @@ -25,27 +25,11 @@ std::unique_ptr<ReferenceWriter> ReferenceGroup::GetWriter( MutableBufferView image, Disassembler* disasm) const { - DCHECK(image.begin() == disasm->GetImage().begin()); - DCHECK(image.size() == disasm->size()); + DCHECK_EQ(image.begin(), disasm->GetImage().begin()); + DCHECK_EQ(image.size(), disasm->size()); return (disasm->*writer_factory_)(image); } -ReferenceTypeTraits ReferenceGroup::Traits() const { - return traits_; -} - -offset_t ReferenceGroup::Width() const { - return traits_.width; -} - -TypeTag ReferenceGroup::TypeTag() const { - return traits_.type_tag; -} - -PoolTag ReferenceGroup::PoolTag() const { - return traits_.pool_tag; -} - Disassembler::Disassembler() = default; Disassembler::~Disassembler() = default;
diff --git a/chrome/installer/zucchini/disassembler.h b/chrome/installer/zucchini/disassembler.h index 448a67a..efdb50bc 100644 --- a/chrome/installer/zucchini/disassembler.h +++ b/chrome/installer/zucchini/disassembler.h
@@ -43,7 +43,7 @@ // A ReferenceGroup is associated with a specific |type| and has convenience // methods to obtain readers and writers for that type. A ReferenceGroup does -// not store references; it is a lighweight class that communicates with the +// not store references; it is a lightweight class that communicates with the // disassembler to operate on them. class ReferenceGroup { public: @@ -87,18 +87,18 @@ Disassembler* disasm) const; // Returns traits describing the reference type. - ReferenceTypeTraits Traits() const; + const ReferenceTypeTraits& traits() const { return traits_; } - // Shorthand for Traits().width. - offset_t Width() const; + // Shorthand for traits().width. + offset_t width() const { return traits().width; } - // Shorthand for Traits().type_tag. - TypeTag TypeTag() const; + // Shorthand for traits().type_tag. + TypeTag type_tag() const { return traits().type_tag; } - // Shorthand for Traits().pool_tag. - PoolTag PoolTag() const; + // Shorthand for traits().pool_tag. + PoolTag pool_tag() const { return traits().pool_tag; } - protected: + private: ReferenceTypeTraits traits_; ReaderFactory reader_factory_ = nullptr; WriterFactory writer_factory_ = nullptr; @@ -122,7 +122,7 @@ // Groups must be aggregated by pool. virtual std::vector<ReferenceGroup> GetReferenceGroups() const = 0; - BufferView GetImage() const { return image_; } + ConstBufferView GetImage() const { return image_; } size_t size() const { return image_.size(); } protected: @@ -130,11 +130,11 @@ // Parses |image| and initializes internal states. Returns true on success. // This must be called once and before any other operation. - virtual bool Parse(BufferView image) = 0; + virtual bool Parse(ConstBufferView image) = 0; // Raw image data. After Parse(), a Disassembler should shrink this to contain // only the portion containing the executable file it recognizes. - BufferView image_; + ConstBufferView image_; }; } // namespace zucchini
diff --git a/chrome/installer/zucchini/image_utils.h b/chrome/installer/zucchini/image_utils.h index 48935b54..2786d28 100644 --- a/chrome/installer/zucchini/image_utils.h +++ b/chrome/installer/zucchini/image_utils.h
@@ -17,19 +17,19 @@ // Used to uniquely identify a reference group. // Strongly typed objects are used to avoid ambiguitees with PoolTag. -struct TypeTag : TypedValue<TypeTag, uint8_t> { +struct TypeTag : public TypedValue<TypeTag, uint8_t> { // inheriting constructor: using TypedValue<TypeTag, uint8_t>::TypedValue; }; // Used to uniquely identify a pool. -struct PoolTag : TypedValue<PoolTag, uint8_t> { +struct PoolTag : public TypedValue<PoolTag, uint8_t> { // inheriting constructor: using TypedValue<PoolTag, uint8_t>::TypedValue; }; -constexpr TypeTag kNoTypeTag = 0xFF; -constexpr PoolTag kNoPoolTag = 0xFF; +constexpr TypeTag kNoTypeTag(0xFF); +constexpr PoolTag kNoPoolTag(0xFF); // Specification of references in an image file. struct ReferenceTypeTraits { @@ -55,7 +55,7 @@ offset_t target; }; -inline bool operator==(Reference a, Reference b) { +inline bool operator==(const Reference& a, const Reference& b) { return a.location == b.location && a.target == b.target; } @@ -79,14 +79,14 @@ // Enumerations for supported executables. enum ExecutableType : uint32_t { - EXE_TYPE_UNKNOWN = UINT32_MAX, - EXE_TYPE_NO_OP = 0, - EXE_TYPE_WIN32_X86 = 1, - EXE_TYPE_WIN32_X64 = 2, - EXE_TYPE_ELF_X86 = 3, - EXE_TYPE_ELF_ARM32 = 4, - EXE_TYPE_ELF_AARCH64 = 5, - EXE_TYPE_DEX = 6, + kExeTypeUnknown = UINT32_MAX, + kExeTypeNoOp = 0, + kExeTypeWin32X86 = 1, + kExeTypeWin32X64 = 2, + kExeTypeElfX86 = 3, + kExeTypeElfArm32 = 4, + kExeTypeElfAArch64 = 5, + kExeTypeDex = 6, }; // Descibes where to find an executable embedded in an image.
diff --git a/chrome/installer/zucchini/typed_value.h b/chrome/installer/zucchini/typed_value.h index 12ddf3f..446a601 100644 --- a/chrome/installer/zucchini/typed_value.h +++ b/chrome/installer/zucchini/typed_value.h
@@ -11,7 +11,7 @@ // Strong typed values, with compare and convert functions for underlying data. // Typically one would use strongly typed enums for this. However, for Zucchini, -// the number of bytes is not fixed, and need to be represented as integer for +// the number of bytes is not fixed, and must be represented as an integer for // iteration. // |Tag| is a type tag used to uniquely identify TypedValue. // |T| is an integral type used to hold values. @@ -25,9 +25,9 @@ class TypedValue { public: constexpr TypedValue() = default; - constexpr TypedValue(const T& value) : value_(value) {} + explicit constexpr TypedValue(const T& value) : value_(value) {} - explicit operator const T() const { return value_; } + explicit operator T() const { return value_; } const T value() const { return value_; } friend bool operator==(const TypedValue& a, const TypedValue& b) { @@ -37,7 +37,7 @@ return !(a == b); } - protected: + private: T value_ = {}; };
diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index 8d4c6833..eec4b43 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn
@@ -134,8 +134,6 @@ "//components/translate/content/renderer", "//components/translate/core/common", "//components/translate/core/language_detection", - "//components/ukm/public", - "//components/ukm/public/interfaces", "//components/visitedlink/renderer", "//components/web_cache/renderer", "//content/app/resources", @@ -150,6 +148,8 @@ "//net", "//ppapi/features", "//printing/features", + "//services/metrics/public/cpp:metrics_cpp", + "//services/metrics/public/interfaces", "//services/service_manager/public/cpp", "//skia", "//storage/common",
diff --git a/chrome/renderer/content_settings_observer.cc b/chrome/renderer/content_settings_observer.cc index 4555cf7b..2c374bdc 100644 --- a/chrome/renderer/content_settings_observer.cc +++ b/chrome/renderer/content_settings_observer.cc
@@ -298,10 +298,6 @@ return result; } -bool ContentSettingsObserver::AllowPlugins(bool enabled_per_settings) { - return enabled_per_settings; -} - bool ContentSettingsObserver::AllowScript(bool enabled_per_settings) { if (!enabled_per_settings) return false;
diff --git a/chrome/renderer/content_settings_observer.h b/chrome/renderer/content_settings_observer.h index d1bd151..365900d 100644 --- a/chrome/renderer/content_settings_observer.h +++ b/chrome/renderer/content_settings_observer.h
@@ -74,7 +74,6 @@ const blink::WebURL& image_url) override; bool AllowIndexedDB(const blink::WebString& name, const blink::WebSecurityOrigin& origin) override; - bool AllowPlugins(bool enabled_per_settings) override; bool AllowScript(bool enabled_per_settings) override; bool AllowScriptFromSource(bool enabled_per_settings, const blink::WebURL& script_url) override;
diff --git a/chrome/renderer/plugins/pdf_plugin_placeholder.cc b/chrome/renderer/plugins/pdf_plugin_placeholder.cc index 3263551..6e20cfbc 100644 --- a/chrome/renderer/plugins/pdf_plugin_placeholder.cc +++ b/chrome/renderer/plugins/pdf_plugin_placeholder.cc
@@ -5,6 +5,7 @@ #include "chrome/renderer/plugins/pdf_plugin_placeholder.h" #include "chrome/grit/renderer_resources.h" +#include "gin/object_template_builder.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/webui/jstemplate_builder.h" @@ -31,3 +32,14 @@ v8::Local<v8::Value> PDFPluginPlaceholder::GetV8Handle(v8::Isolate* isolate) { return gin::CreateHandle(isolate, this).ToV8(); } + +gin::ObjectTemplateBuilder PDFPluginPlaceholder::GetObjectTemplateBuilder( + v8::Isolate* isolate) { + return gin::Wrappable<PDFPluginPlaceholder>::GetObjectTemplateBuilder(isolate) + .SetMethod<void (PDFPluginPlaceholder::*)()>( + "downloadPDF", &PDFPluginPlaceholder::DownloadPDFCallback); +} + +void PDFPluginPlaceholder::DownloadPDFCallback() { + // TODO(amberwon): Implement starting PDF download. +}
diff --git a/chrome/renderer/plugins/pdf_plugin_placeholder.h b/chrome/renderer/plugins/pdf_plugin_placeholder.h index e3975ce..39f4216 100644 --- a/chrome/renderer/plugins/pdf_plugin_placeholder.h +++ b/chrome/renderer/plugins/pdf_plugin_placeholder.h
@@ -30,6 +30,11 @@ // WebViewPlugin::Delegate methods: v8::Local<v8::Value> GetV8Handle(v8::Isolate* isolate) final; + + gin::ObjectTemplateBuilder GetObjectTemplateBuilder( + v8::Isolate* isolate) final; + + void DownloadPDFCallback(); }; #endif // CHROME_RENDERER_PLUGINS_PDF_PLUGIN_PLACEHOLDER_H_
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 42c2eb2..afc8b0a8 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3129,6 +3129,7 @@ "../browser/media/cast_remoting_connector_unittest.cc", "../browser/media/media_engagement_contents_observer_unittest.cc", "../browser/media/media_engagement_score_unittest.cc", + "../browser/media/media_engagement_service_unittest.cc", "../browser/media/midi_permission_context_unittest.cc", "../browser/media/midi_sysex_permission_context_unittest.cc", "../browser/media/router/browser_presentation_connection_proxy_unittest.cc", @@ -3306,8 +3307,8 @@ "../browser/sync/sessions/sync_sessions_web_contents_router_unittest.cc", "../browser/sync/sync_startup_tracker_unittest.cc", "../browser/task_profiler/task_profiler_data_serializer_unittest.cc", - "../browser/thumbnails/simple_thumbnail_crop_unittest.cc", "../browser/thumbnails/thumbnail_service_unittest.cc", + "../browser/thumbnails/thumbnail_utils_unittest.cc", "../browser/translate/chrome_translate_client_unittest.cc", "../browser/translate/language_model_factory_unittest.cc", "../browser/translate/translate_service_unittest.cc",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/OWNERS b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/OWNERS index 21dc744..f5f6e7ea 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/OWNERS +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/signin/OWNERS
@@ -1,2 +1 @@ gogerald@chromium.org -maxbogue@chromium.org
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/sync/OWNERS b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/sync/OWNERS index 91e7103..4171a3fc 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/sync/OWNERS +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/sync/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org zea@chromium.org
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index e66d6c76..3ca823299 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -28,6 +28,7 @@ #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h" #include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/chromeos/arc/arc_service_launcher.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/favicon/favicon_service_factory.h" @@ -433,6 +434,9 @@ scoped_cros_settings_test_helper_.reset( new chromeos::ScopedCrosSettingsTestHelper); } + arc::ArcServiceLauncher* launcher = arc::ArcServiceLauncher::Get(); + if (launcher) + launcher->MaybeSetProfile(this); #endif set_is_guest_profile(guest_session_);
diff --git a/chrome/test/data/bookmark_html_reader/empty_folder.html b/chrome/test/data/bookmark_html_reader/empty_folder.html new file mode 100644 index 0000000..a5e75bb --- /dev/null +++ b/chrome/test/data/bookmark_html_reader/empty_folder.html
@@ -0,0 +1,24 @@ +<!DOCTYPE NETSCAPE-Bookmark-file-1> +<!-- This is an automatically generated file. + It will be read and overwritten. + DO NOT EDIT! --> +<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> +<TITLE>Bookmarks</TITLE> +<H1>Bookmarks Menu</H1> + +<DL><p> + <DT><H3 ADD_DATE="1295938143" LAST_MODIFIED="1295938145">Empty's Parent</H3> + <DL><p> + <DT><H3 ADD_DATE="1295938143" LAST_MODIFIED="1295938145"></H3> + <DL><p> + </DL><p> + </DL><p> + <DT><H3 ADD_DATE="1295938000" LAST_MODIFIED="1295939000"></H3> + <DL><p> + <DT><A HREF="http://www.tamurayukari.com/" ADD_DATE="1234567890" LAST_MODIFIED="1234567891">[Tamura Yukari.com]</A> + </DL><p> + <DT><H3 ADD_DATE="1295938000" LAST_MODIFIED="1295939000">Not Empty But Default</H3> + <DL><p> + <DT><A HREF="http://www.google.com/" ADD_DATE="0000000000" LAST_MODIFIED="0000000000">Google</A> + </DL><p> +</DL><p> \ No newline at end of file
diff --git a/chrome/test/data/payments/contact_details.js b/chrome/test/data/payments/contact_details.js index e4e4df9..67eca44 100644 --- a/chrome/test/data/payments/contact_details.js +++ b/chrome/test/data/payments/contact_details.js
@@ -12,7 +12,7 @@ function buy() { // eslint-disable-line no-unused-vars try { new PaymentRequest( - [{supportedMethods: ['https://bobpay.com', 'amex']}], + [{supportedMethods: ['https://bobpay.com', 'amex', 'visa']}], {total: {label: 'Total', amount: {currency: 'USD', value: '5.00'}}}, {requestPayerName: true, requestPayerEmail: true, requestPayerPhone: true})
diff --git a/chrome/test/data/webui/md_bookmarks/command_manager_test.js b/chrome/test/data/webui/md_bookmarks/command_manager_test.js index 61ff0f8..da428c2 100644 --- a/chrome/test/data/webui/md_bookmarks/command_manager_test.js +++ b/chrome/test/data/webui/md_bookmarks/command_manager_test.js
@@ -382,4 +382,13 @@ assertOpenedTabs(['http://111/', 'http://13/']); }); + + test('meta-down triggers Open on Mac', function() { + if (!cr.isMac) + return; + + customClick(items[0]); + MockInteractions.pressAndReleaseKeyOn(items[0], 0, 'meta', 'ArrowDown'); + assertEquals('11', store.data.selectedFolder); + }); });
diff --git a/chrome/test/data/webui/md_bookmarks/item_test.js b/chrome/test/data/webui/md_bookmarks/item_test.js index 94436d1..d03968a 100644 --- a/chrome/test/data/webui/md_bookmarks/item_test.js +++ b/chrome/test/data/webui/md_bookmarks/item_test.js
@@ -53,13 +53,13 @@ store.lastAction); }); - test('context menu selects item if unselected', function() { + function testEventSelection(eventname) { item.isSelectedItem_ = true; - item.dispatchEvent(new MouseEvent('contextmenu')); + item.dispatchEvent(new MouseEvent(eventname)); assertEquals(null, store.lastAction); item.isSelectedItem_ = false; - item.dispatchEvent(new MouseEvent('contextmenu')); + item.dispatchEvent(new MouseEvent(eventname)); assertDeepEquals( bookmarks.actions.selectItem('2', store.data, { clear: true, @@ -67,5 +67,15 @@ toggle: false, }), store.lastAction); + } + + test('context menu selects item if unselected', function() { + testEventSelection('contextmenu'); + }); + + test('doubleclicking selects item if unselected', function() { + document.body.appendChild( + document.createElement('bookmarks-command-manager')); + testEventSelection('dblclick'); }); });
diff --git a/chrome/test/data/webui/md_bookmarks/reducers_test.js b/chrome/test/data/webui/md_bookmarks/reducers_test.js index 15fae4d..e8cfc37 100644 --- a/chrome/test/data/webui/md_bookmarks/reducers_test.js +++ b/chrome/test/data/webui/md_bookmarks/reducers_test.js
@@ -436,7 +436,7 @@ assertFalse(bookmarks.util.isShowingSearch(clearedState)); assertDeepEquals(['3'], bookmarks.util.getDisplayedList(clearedState)); assertEquals('', clearedState.search.term); - assertDeepEquals([], clearedState.search.results); + assertDeepEquals(null, clearedState.search.results); // Case 2: Clear search by selecting a new folder. action = bookmarks.actions.selectFolder('1'); @@ -446,7 +446,36 @@ assertFalse(bookmarks.util.isShowingSearch(selectedState)); assertDeepEquals(['2'], bookmarks.util.getDisplayedList(selectedState)); assertEquals('', selectedState.search.term); - assertDeepEquals([], selectedState.search.results); + assertDeepEquals(null, selectedState.search.results); + }); + + test('results do not clear while performing a second search', function() { + action = bookmarks.actions.setSearchTerm('te'); + state = bookmarks.reduceAction(state, action); + + assertFalse(bookmarks.util.isShowingSearch(state)); + + action = bookmarks.actions.setSearchResults(['2', '3']); + state = bookmarks.reduceAction(state, action); + + assertFalse(state.search.inProgress); + assertTrue(bookmarks.util.isShowingSearch(state)); + + // Continuing the search should not clear the previous results, which should + // continue to show until the new results arrive. + action = bookmarks.actions.setSearchTerm('test'); + state = bookmarks.reduceAction(state, action); + + assertTrue(state.search.inProgress); + assertTrue(bookmarks.util.isShowingSearch(state)); + assertDeepEquals(['2', '3'], bookmarks.util.getDisplayedList(state)); + + action = bookmarks.actions.setSearchResults(['3']); + state = bookmarks.reduceAction(state, action); + + assertFalse(state.search.inProgress); + assertTrue(bookmarks.util.isShowingSearch(state)); + assertDeepEquals(['3'], bookmarks.util.getDisplayedList(state)); }); test('removes deleted nodes', function() {
diff --git a/chrome/test/data/webui/md_bookmarks/router_test.js b/chrome/test/data/webui/md_bookmarks/router_test.js index f118c12..87ea0593 100644 --- a/chrome/test/data/webui/md_bookmarks/router_test.js +++ b/chrome/test/data/webui/md_bookmarks/router_test.js
@@ -43,6 +43,11 @@ return Promise.resolve().then(function() { assertEquals('chrome://bookmarks/?id=2', window.location.href); + store.data.selectedFolder = '1'; + store.notifyObservers(); + }).then(function() { + // Selecting Bookmarks bar clears route. + assertEquals('chrome://bookmarks/', window.location.href); }); }); @@ -62,6 +67,13 @@ assertEquals('chrome://bookmarks/?q=bloop', window.location.href); }); }); + + test('bookmarks bar selected with empty route', function() { + navigateTo('/?id=2'); + navigateTo('/'); + assertEquals('select-folder', store.lastAction.name); + assertEquals('1', store.lastAction.id); + }); }); suite('URL preload', function() { @@ -120,7 +132,7 @@ var state = bookmarks.Store.getInstance().data; assertEquals('1', state.selectedFolder); return Promise.resolve().then(function() { - assertEquals('chrome://bookmarks/?id=1', window.location.href); + assertEquals('chrome://bookmarks/', window.location.href); }); }); });
diff --git a/chrome/utility/importer/bookmark_html_reader.cc b/chrome/utility/importer/bookmark_html_reader.cc index 8e524b83..ae39a99e 100644 --- a/chrome/utility/importer/bookmark_html_reader.cc +++ b/chrome/utility/importer/bookmark_html_reader.cc
@@ -121,6 +121,7 @@ bool last_folder_on_toolbar = false; bool last_folder_is_empty = true; bool has_subfolder = false; + bool has_last_folder = false; base::Time last_folder_add_date; std::vector<base::string16> path; size_t toolbar_folder_index = 0; @@ -153,6 +154,7 @@ &last_folder, &last_folder_on_toolbar, &last_folder_add_date)) { + has_last_folder = true; continue; } @@ -207,8 +209,9 @@ entry.path.assign(path.begin() + toolbar_folder_index - 1, path.end()); } else { // Add this bookmark to the list of |bookmarks|. - if (!has_subfolder && !last_folder.empty()) { + if (!has_subfolder && has_last_folder) { path.push_back(last_folder); + has_last_folder = false; last_folder.clear(); } entry.path.assign(path.begin(), path.end()); @@ -226,8 +229,9 @@ // Bookmarks in sub-folder are encapsulated with <DL> tag. if (base::StartsWith(line, "<DL>", base::CompareCase::INSENSITIVE_ASCII)) { has_subfolder = true; - if (!last_folder.empty()) { + if (has_last_folder) { path.push_back(last_folder); + has_last_folder = false; last_folder.clear(); } if (last_folder_on_toolbar && !toolbar_folder_index)
diff --git a/chrome/utility/importer/bookmark_html_reader_unittest.cc b/chrome/utility/importer/bookmark_html_reader_unittest.cc index 67f1cc0..2b6d8db7 100644 --- a/chrome/utility/importer/bookmark_html_reader_unittest.cc +++ b/chrome/utility/importer/bookmark_html_reader_unittest.cc
@@ -188,6 +188,8 @@ const importer::SearchEngineInfo& info); void ExpectSecondFirefoxBookmarkWithKeyword( const importer::SearchEngineInfo& info); + void ExpectFirstEmptyFolderBookmark(const ImportedBookmarkEntry& entry); + void ExpectSecondEmptyFolderBookmark(const ImportedBookmarkEntry& entry); base::FilePath test_data_path_; }; @@ -286,6 +288,27 @@ EXPECT_EQ(ASCIIToUTF16("BookmarkName"), info.display_name); } +void BookmarkHTMLReaderTestWithData::ExpectFirstEmptyFolderBookmark( + const ImportedBookmarkEntry& entry) { + EXPECT_EQ(base::string16(), entry.title); + EXPECT_TRUE(entry.is_folder); + EXPECT_EQ(base::Time::FromTimeT(1295938143), entry.creation_time); + EXPECT_EQ(1U, entry.path.size()); + if (entry.path.size() == 1) + EXPECT_EQ(ASCIIToUTF16("Empty's Parent"), entry.path.front()); +} + +void BookmarkHTMLReaderTestWithData::ExpectSecondEmptyFolderBookmark( + const ImportedBookmarkEntry& entry) { + EXPECT_EQ(ASCIIToUTF16("[Tamura Yukari.com]"), entry.title); + EXPECT_FALSE(entry.is_folder); + EXPECT_EQ(base::Time::FromTimeT(1234567890), entry.creation_time); + EXPECT_EQ(1U, entry.path.size()); + if (entry.path.size() == 1) + EXPECT_EQ(base::string16(), entry.path.front()); + EXPECT_EQ("http://www.tamurayukari.com/", entry.url.spec()); +} + } // namespace TEST_F(BookmarkHTMLReaderTestWithData, Firefox2BookmarkFileImport) { @@ -343,6 +366,20 @@ ExpectSecondFirefoxBookmarkWithKeyword(search_engines[1]); } +TEST_F(BookmarkHTMLReaderTestWithData, EmptyFolderImport) { + base::FilePath path = test_data_path_.AppendASCII("empty_folder.html"); + + std::vector<ImportedBookmarkEntry> bookmarks; + ImportBookmarksFile(base::Callback<bool(void)>(), + base::Callback<bool(const GURL&)>(), path, &bookmarks, + NULL, NULL); + + ASSERT_EQ(3U, bookmarks.size()); + ExpectFirstEmptyFolderBookmark(bookmarks[0]); + ExpectSecondEmptyFolderBookmark(bookmarks[1]); + ExpectThirdFirefox2Bookmark(bookmarks[2]); +} + TEST_F(BookmarkHTMLReaderTestWithData, RedditSaverFileImport) { base::FilePath path = test_data_path_.AppendASCII("redditsaver.html");
diff --git a/chromecast/browser/BUILD.gn b/chromecast/browser/BUILD.gn index a7793ae..555611ca 100644 --- a/chromecast/browser/BUILD.gn +++ b/chromecast/browser/BUILD.gn
@@ -4,6 +4,7 @@ import("//build/config/ui.gni") import("//chromecast/chromecast.gni") +import("//media/media_options.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") import("//tools/grit/grit_rule.gni") @@ -166,6 +167,13 @@ if (use_ozone) { deps += [ "//ui/ozone" ] } + + if (enable_mojo_media) { + deps += [ + "//media/mojo/interfaces:constants", + "//media/mojo/services", + ] + } } # This target generates an "overlay" interface spec, allowing the Cast build to
diff --git a/chromecast/browser/cast_content_browser_client.cc b/chromecast/browser/cast_content_browser_client.cc index e1ca469..7846871 100644 --- a/chromecast/browser/cast_content_browser_client.cc +++ b/chromecast/browser/cast_content_browser_client.cc
@@ -67,7 +67,8 @@ #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) #include "chromecast/media/service/cast_mojo_media_client.h" -#include "media/mojo/services/media_service.h" // nogncheck +#include "media/mojo/interfaces/constants.mojom.h" // nogncheck +#include "media/mojo/services/media_service.h" // nogncheck #endif // ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS #if defined(OS_ANDROID) @@ -525,7 +526,7 @@ service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(&CreateMediaService, base::Unretained(this)); info.task_runner = GetMediaTaskRunner(); - services->insert(std::make_pair("media", info)); + services->insert(std::make_pair(::media::mojom::kMediaServiceName, info)); #endif }
diff --git a/chromecast/browser/metrics/cast_metrics_service_client.cc b/chromecast/browser/metrics/cast_metrics_service_client.cc index 1b08f7c..8cb0a48 100644 --- a/chromecast/browser/metrics/cast_metrics_service_client.cc +++ b/chromecast/browser/metrics/cast_metrics_service_client.cc
@@ -112,10 +112,9 @@ void CastMetricsServiceClient::StoreClientInfo( const ::metrics::ClientInfo& client_info) { - const std::string& client_id = client_info.client_id; - DCHECK(client_id.empty() || base::IsValidGUID(client_id)); - // backup client_id or reset to empty. - SetMetricsClientId(client_id); + // TODO(gfhuang): |force_client_id_| logic is super ugly, we should refactor + // to align load/save logic of |force_client_id_| with Load/StoreClientInfo. + // Currently it's lumped inside SetMetricsClientId(client_id). } std::unique_ptr<::metrics::ClientInfo> @@ -339,6 +338,8 @@ // report the client-id and expect that setup will handle the current opt-in // value. metrics_state_manager_->ForceClientIdCreation(); + // Populate |client_id| to other component parts. + SetMetricsClientId(metrics_state_manager_->client_id()); CastStabilityMetricsProvider* stability_provider = new CastStabilityMetricsProvider(metrics_service_.get());
diff --git a/chromeos/components/tether/BUILD.gn b/chromeos/components/tether/BUILD.gn index 1f0c4c1..fd5cc912 100644 --- a/chromeos/components/tether/BUILD.gn +++ b/chromeos/components/tether/BUILD.gn
@@ -28,6 +28,8 @@ "device_status_util.h", "disconnect_tethering_operation.cc", "disconnect_tethering_operation.h", + "host_connection_metrics_logger.cc", + "host_connection_metrics_logger.h", "host_scan_cache.cc", "host_scan_cache.h", "host_scan_device_prioritizer.h", @@ -143,6 +145,7 @@ "connect_tethering_operation_unittest.cc", "device_status_util_unittest.cc", "disconnect_tethering_operation_unittest.cc", + "host_connection_metrics_logger_unittest.cc", "host_scan_cache_unittest.cc", "host_scan_device_prioritizer_impl_unittest.cc", "host_scan_scheduler_unittest.cc",
diff --git a/chromeos/components/tether/host_connection_metrics_logger.cc b/chromeos/components/tether/host_connection_metrics_logger.cc new file mode 100644 index 0000000..4159020 --- /dev/null +++ b/chromeos/components/tether/host_connection_metrics_logger.cc
@@ -0,0 +1,116 @@ +// 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 "chromeos/components/tether/host_connection_metrics_logger.h" + +#include "base/metrics/histogram_macros.h" + +namespace chromeos { + +namespace tether { + +HostConnectionMetricsLogger::HostConnectionMetricsLogger() {} + +HostConnectionMetricsLogger::~HostConnectionMetricsLogger() {} + +void HostConnectionMetricsLogger::RecordConnectionToHostResult( + ConnectionToHostResult result) { + switch (result) { + case ConnectionToHostResult::CONNECTION_RESULT_PROVISIONING_FAILED: + RecordConnectionResultProvisioningFailure( + ConnectionToHostResult_ProvisioningFailureEventType:: + PROVISIONING_FAILED); + break; + case ConnectionToHostResult::CONNECTION_RESULT_SUCCESS: + RecordConnectionResultSuccess( + ConnectionToHostResult_SuccessEventType::SUCCESS); + break; + case ConnectionToHostResult::CONNECTION_RESULT_FAILURE_UNKNOWN_ERROR: + RecordConnectionResultFailure( + ConnectionToHostResult_FailureEventType::UNKNOWN_ERROR); + break; + case ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_TIMEOUT: + RecordConnectionResultFailureClientConnection( + ConnectionToHostResult_FailureClientConnectionEventType::TIMEOUT); + break; + case ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_CANCELED_BY_NEW_ATTEMPT: + RecordConnectionResultFailureClientConnection( + ConnectionToHostResult_FailureClientConnectionEventType:: + CANCELED_BY_NEW_ATTEMPT); + break; + case ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_REQUIRED: + RecordConnectionResultFailureTetheringTimeout( + ConnectionToHostResult_FailureTetheringTimeoutEventType:: + FIRST_TIME_SETUP_WAS_REQUIRED); + break; + case ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_NOT_REQUIRED: + RecordConnectionResultFailureTetheringTimeout( + ConnectionToHostResult_FailureTetheringTimeoutEventType:: + FIRST_TIME_SETUP_WAS_NOT_REQUIRED); + break; + default: + NOTREACHED(); + }; +} + +void HostConnectionMetricsLogger::RecordConnectionResultProvisioningFailure( + ConnectionToHostResult_ProvisioningFailureEventType event_type) { + UMA_HISTOGRAM_ENUMERATION( + "InstantTethering.ConnectionToHostResult.ProvisioningFailureRate", + event_type, + ConnectionToHostResult_ProvisioningFailureEventType:: + PROVISIONING_FAILURE_MAX); +} + +void HostConnectionMetricsLogger::RecordConnectionResultSuccess( + ConnectionToHostResult_SuccessEventType event_type) { + UMA_HISTOGRAM_ENUMERATION( + "InstantTethering.ConnectionToHostResult.SuccessRate", event_type, + ConnectionToHostResult_SuccessEventType::SUCCESS_MAX); + + RecordConnectionResultProvisioningFailure( + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +void HostConnectionMetricsLogger::RecordConnectionResultFailure( + ConnectionToHostResult_FailureEventType event_type) { + UMA_HISTOGRAM_ENUMERATION( + "InstantTethering.ConnectionToHostResult.Failure", event_type, + ConnectionToHostResult_FailureEventType::FAILURE_MAX); + + RecordConnectionResultSuccess( + ConnectionToHostResult_SuccessEventType::FAILURE); +} + +void HostConnectionMetricsLogger::RecordConnectionResultFailureClientConnection( + ConnectionToHostResult_FailureClientConnectionEventType event_type) { + UMA_HISTOGRAM_ENUMERATION( + "InstantTethering.ConnectionToHostResult.Failure.ClientConnection", + event_type, + ConnectionToHostResult_FailureClientConnectionEventType:: + FAILURE_CLIENT_CONNECTION_MAX); + + RecordConnectionResultFailure( + ConnectionToHostResult_FailureEventType::CLIENT_CONNECTION_ERROR); +} + +void HostConnectionMetricsLogger::RecordConnectionResultFailureTetheringTimeout( + ConnectionToHostResult_FailureTetheringTimeoutEventType event_type) { + UMA_HISTOGRAM_ENUMERATION( + "InstantTethering.ConnectionToHostResult.Failure.TetheringTimeout", + event_type, + ConnectionToHostResult_FailureTetheringTimeoutEventType:: + FAILURE_TETHERING_TIMEOUT_MAX); + + RecordConnectionResultFailure( + ConnectionToHostResult_FailureEventType::TETHERING_TIMED_OUT); +} + +} // namespace tether + +} // namespace chromeos
diff --git a/chromeos/components/tether/host_connection_metrics_logger.h b/chromeos/components/tether/host_connection_metrics_logger.h new file mode 100644 index 0000000..f5a22ef --- /dev/null +++ b/chromeos/components/tether/host_connection_metrics_logger.h
@@ -0,0 +1,141 @@ +// 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 CHROMEOS_COMPONENTS_TETHER_HOST_CONNECTION_METRICS_LOGGER_H_ +#define CHROMEOS_COMPONENTS_TETHER_HOST_CONNECTION_METRICS_LOGGER_H_ + +#include "base/gtest_prod_util.h" +#include "base/macros.h" + +namespace chromeos { + +namespace tether { + +// Wrapper around metrics reporting for host connection results. Clients are +// expected to report the result of a host connection attempt once it has +// concluded. +class HostConnectionMetricsLogger { + public: + enum ConnectionToHostResult { + CONNECTION_RESULT_PROVISIONING_FAILED, + CONNECTION_RESULT_SUCCESS, + CONNECTION_RESULT_FAILURE_UNKNOWN_ERROR, + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_TIMEOUT, + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_CANCELED_BY_NEW_ATTEMPT, + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_REQUIRED, + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_NOT_REQUIRED + }; + + // Record the result of an attempted host connection. + virtual void RecordConnectionToHostResult(ConnectionToHostResult result); + + HostConnectionMetricsLogger(); + virtual ~HostConnectionMetricsLogger(); + + private: + friend class HostConnectionMetricsLoggerTest; + FRIEND_TEST_ALL_PREFIXES(HostConnectionMetricsLoggerTest, + RecordConnectionResultProvisioningFailure); + FRIEND_TEST_ALL_PREFIXES(HostConnectionMetricsLoggerTest, + RecordConnectionResultSuccess); + FRIEND_TEST_ALL_PREFIXES(HostConnectionMetricsLoggerTest, + RecordConnectionResultFailure); + FRIEND_TEST_ALL_PREFIXES( + HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureClientConnection_Timeout); + FRIEND_TEST_ALL_PREFIXES( + HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureClientConnection_CanceledByNewAttempt); + FRIEND_TEST_ALL_PREFIXES( + HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureTetheringTimeout_SetupRequired); + FRIEND_TEST_ALL_PREFIXES( + HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureTetheringTimeout_SetupNotRequired); + + // An Instant Tethering connection can fail for several different reasons. + // Though traditionally success and each failure case would be logged to a + // single enum, we have chosen to start at a top-level of view of simply + // "success vs failure", and then iteratively breaking down the failure count + // into its types (and possibly sub-types). Because of this cascading nature, + // when a failure sub-type occurs, the code path in question must report that + // sub-type as well as all the super-types above it. This would be cumbersome, + // and thus HostConnectionMetricsLogger exists to provide a simple API which + // handles all the other metrics that need to be reported. + // + // The most top-level metric is + // InstantTethering.ConnectionToHostResult.ProvisioningFailureRate. Its + // breakdown, and the breakdown of its subsquent metrics, is described in + // tools/metrics/histograms/histograms.xml. + enum ConnectionToHostResult_ProvisioningFailureEventType { + PROVISIONING_FAILED = 0, + OTHER = 1, + PROVISIONING_FAILURE_MAX + }; + + enum ConnectionToHostResult_SuccessEventType { + SUCCESS = 0, + FAILURE = 1, + SUCCESS_MAX + }; + + enum ConnectionToHostResult_FailureEventType { + UNKNOWN_ERROR = 0, + TETHERING_TIMED_OUT = 1, + CLIENT_CONNECTION_ERROR = 2, + FAILURE_MAX + }; + + enum ConnectionToHostResult_FailureClientConnectionEventType { + TIMEOUT = 0, + CANCELED_BY_NEW_ATTEMPT = 1, + FAILURE_CLIENT_CONNECTION_MAX + }; + + enum ConnectionToHostResult_FailureTetheringTimeoutEventType { + FIRST_TIME_SETUP_WAS_REQUIRED = 0, + FIRST_TIME_SETUP_WAS_NOT_REQUIRED = 1, + FAILURE_TETHERING_TIMEOUT_MAX + }; + + // Record if a host connection attempt never went through due to provisioning + // failure, or otherwise continued. Should only be publicly called with + // an argument of ConnectionToHostResult_ProvisioningFailureEventType::OTHER. + void RecordConnectionResultProvisioningFailure( + ConnectionToHostResult_ProvisioningFailureEventType event_type); + + // Record if a host connection attempt succeeded or failed. Should only be + // publicly called with + // an argument of ConnectionToHostResult_SuccessEventType::SUCCESS. Failure is + // covered by the RecordConnectionResultFailure() method. + void RecordConnectionResultSuccess( + ConnectionToHostResult_SuccessEventType event_type); + + // Record how a host connection attempt failed. Should only be + // publicly called with an argument of + // ConnectionToHostResult_FailureEventType::UNKNOWN_ERROR. Failure due to + // client error or tethering + // timeout is covered + // by theRecordConnectionResultFailureClientConnection() or + // RecordConnectionResultFailureTetheringTimeout() methods, respectively. + void RecordConnectionResultFailure( + ConnectionToHostResult_FailureEventType event_type); + + // Record how a host connection attempt failed due to a client error. + void RecordConnectionResultFailureClientConnection( + ConnectionToHostResult_FailureClientConnectionEventType event_type); + + // Record the conditions of when host connection attempt failed due to + // the host timing out during tethering. + void RecordConnectionResultFailureTetheringTimeout( + ConnectionToHostResult_FailureTetheringTimeoutEventType event_type); + + DISALLOW_COPY_AND_ASSIGN(HostConnectionMetricsLogger); +}; + +} // namespace tether + +} // namespace chromeos + +#endif // CHROMEOS_COMPONENTS_TETHER_HOST_CONNECTION_METRICS_LOGGER_H_
diff --git a/chromeos/components/tether/host_connection_metrics_logger_unittest.cc b/chromeos/components/tether/host_connection_metrics_logger_unittest.cc new file mode 100644 index 0000000..296ecc8 --- /dev/null +++ b/chromeos/components/tether/host_connection_metrics_logger_unittest.cc
@@ -0,0 +1,189 @@ +// 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 "chromeos/components/tether/host_connection_metrics_logger.h" + +#include "base/memory/ptr_util.h" +#include "base/test/histogram_tester.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromeos { + +namespace tether { + +class HostConnectionMetricsLoggerTest : public testing::Test { + protected: + HostConnectionMetricsLoggerTest() {} + + void SetUp() override { + metrics_logger_ = base::MakeUnique<HostConnectionMetricsLogger>(); + } + + void VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType event_type) { + histogram_tester_.ExpectUniqueSample( + "InstantTethering.ConnectionToHostResult.ProvisioningFailureRate", + event_type, 1); + } + + void VerifySuccess( + HostConnectionMetricsLogger::ConnectionToHostResult_SuccessEventType + event_type) { + histogram_tester_.ExpectUniqueSample( + "InstantTethering.ConnectionToHostResult.SuccessRate", event_type, 1); + } + + void VerifyFailure( + HostConnectionMetricsLogger::ConnectionToHostResult_FailureEventType + event_type) { + histogram_tester_.ExpectUniqueSample( + "InstantTethering.ConnectionToHostResult.Failure", event_type, 1); + } + + void VerifyFailure_ClientConnection( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureClientConnectionEventType event_type) { + histogram_tester_.ExpectUniqueSample( + "InstantTethering.ConnectionToHostResult.Failure.ClientConnection", + event_type, 1); + } + + void VerifyFailure_TetheringTimeout( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureTetheringTimeoutEventType event_type) { + histogram_tester_.ExpectUniqueSample( + "InstantTethering.ConnectionToHostResult.Failure.TetheringTimeout", + event_type, 1); + } + + std::unique_ptr<HostConnectionMetricsLogger> metrics_logger_; + + base::HistogramTester histogram_tester_; + + private: + DISALLOW_COPY_AND_ASSIGN(HostConnectionMetricsLoggerTest); +}; + +TEST_F(HostConnectionMetricsLoggerTest, + RecordConnectionResultProvisioningFailure) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_PROVISIONING_FAILED); + + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType:: + PROVISIONING_FAILED); +} + +TEST_F(HostConnectionMetricsLoggerTest, RecordConnectionResultSuccess) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_SUCCESS); + + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::SUCCESS); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +TEST_F(HostConnectionMetricsLoggerTest, RecordConnectionResultFailure) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_UNKNOWN_ERROR); + + VerifyFailure(HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureEventType::UNKNOWN_ERROR); + + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::FAILURE); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +TEST_F(HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureClientConnection_Timeout) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_TIMEOUT); + + VerifyFailure_ClientConnection( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureClientConnectionEventType::TIMEOUT); + VerifyFailure( + HostConnectionMetricsLogger::ConnectionToHostResult_FailureEventType:: + CLIENT_CONNECTION_ERROR); + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::FAILURE); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +TEST_F(HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureClientConnection_CanceledByNewAttempt) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_CLIENT_CONNECTION_CANCELED_BY_NEW_ATTEMPT); + + VerifyFailure_ClientConnection( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureClientConnectionEventType:: + CANCELED_BY_NEW_ATTEMPT); + VerifyFailure( + HostConnectionMetricsLogger::ConnectionToHostResult_FailureEventType:: + CLIENT_CONNECTION_ERROR); + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::FAILURE); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +TEST_F(HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureTetheringTimeout_SetupRequired) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_REQUIRED); + + VerifyFailure_TetheringTimeout( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureTetheringTimeoutEventType:: + FIRST_TIME_SETUP_WAS_REQUIRED); + VerifyFailure( + HostConnectionMetricsLogger::ConnectionToHostResult_FailureEventType:: + TETHERING_TIMED_OUT); + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::FAILURE); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +TEST_F(HostConnectionMetricsLoggerTest, + RecordConnectionResultFailureTetheringTimeout_SetupNotRequired) { + metrics_logger_->RecordConnectionToHostResult( + HostConnectionMetricsLogger::ConnectionToHostResult:: + CONNECTION_RESULT_FAILURE_TETHERING_TIMED_OUT_FIRST_TIME_SETUP_WAS_NOT_REQUIRED); + + VerifyFailure_TetheringTimeout( + HostConnectionMetricsLogger:: + ConnectionToHostResult_FailureTetheringTimeoutEventType:: + FIRST_TIME_SETUP_WAS_NOT_REQUIRED); + VerifyFailure( + HostConnectionMetricsLogger::ConnectionToHostResult_FailureEventType:: + TETHERING_TIMED_OUT); + VerifySuccess(HostConnectionMetricsLogger:: + ConnectionToHostResult_SuccessEventType::FAILURE); + VerifyProvisioningFailure( + HostConnectionMetricsLogger:: + ConnectionToHostResult_ProvisioningFailureEventType::OTHER); +} + +} // namespace tether + +} // namespace chromeos
diff --git a/chromeos/cryptohome/OWNERS b/chromeos/cryptohome/OWNERS index 436c373..e1627725 100644 --- a/chromeos/cryptohome/OWNERS +++ b/chromeos/cryptohome/OWNERS
@@ -1 +1 @@ -dkrahn@chromium.org \ No newline at end of file +hashimoto@chromium.org
diff --git a/chromeos/dbus/arc_obb_mounter_client.cc b/chromeos/dbus/arc_obb_mounter_client.cc index d55f606..2a4a0bf 100644 --- a/chromeos/dbus/arc_obb_mounter_client.cc +++ b/chromeos/dbus/arc_obb_mounter_client.cc
@@ -4,7 +4,10 @@ #include "chromeos/dbus/arc_obb_mounter_client.h" +#include <utility> + #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "dbus/bus.h" #include "dbus/message.h" @@ -33,7 +36,7 @@ void MountObb(const std::string& obb_file, const std::string& mount_path, int32_t owner_gid, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(kArcObbMounterInterface, kMountObbMethod); dbus::MessageWriter writer(&method_call); writer.AppendString(obb_file); @@ -41,17 +44,19 @@ writer.AppendInt32(owner_gid); proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&ArcObbMounterClientImpl::OnVoidDBusMethod, - weak_ptr_factory_.GetWeakPtr(), callback)); + weak_ptr_factory_.GetWeakPtr(), + base::Passed(std::move(callback)))); } void UnmountObb(const std::string& mount_path, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(kArcObbMounterInterface, kUnmountObbMethod); dbus::MessageWriter writer(&method_call); writer.AppendString(mount_path); proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&ArcObbMounterClientImpl::OnVoidDBusMethod, - weak_ptr_factory_.GetWeakPtr(), callback)); + weak_ptr_factory_.GetWeakPtr(), + base::Passed(std::move(callback)))); } protected: @@ -63,10 +68,10 @@ private: // Runs the callback with the method call result. - void OnVoidDBusMethod(const VoidDBusMethodCallback& callback, + void OnVoidDBusMethod(VoidDBusMethodCallback callback, dbus::Response* response) { - callback.Run(response ? DBUS_METHOD_CALL_SUCCESS - : DBUS_METHOD_CALL_FAILURE); + std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS + : DBUS_METHOD_CALL_FAILURE); } dbus::ObjectProxy* proxy_ = nullptr;
diff --git a/chromeos/dbus/arc_obb_mounter_client.h b/chromeos/dbus/arc_obb_mounter_client.h index 8e05512..7d1280b 100644 --- a/chromeos/dbus/arc_obb_mounter_client.h +++ b/chromeos/dbus/arc_obb_mounter_client.h
@@ -35,11 +35,11 @@ virtual void MountObb(const std::string& obb_file, const std::string& mount_path, int32_t owner_gid, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Unmounts the OBB mounted at the specified path. virtual void UnmountObb(const std::string& mount_path, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; }; } // namespace chromeos
diff --git a/chromeos/dbus/biod/biod_client.cc b/chromeos/dbus/biod/biod_client.cc index 2223e8d..5733619 100644 --- a/chromeos/dbus/biod/biod_client.cc +++ b/chromeos/dbus/biod/biod_client.cc
@@ -6,7 +6,10 @@ #include <stdint.h> +#include <utility> + #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/stringprintf.h" @@ -22,9 +25,9 @@ namespace { // D-Bus response handler for methods that use void callbacks. -void OnVoidResponse(const VoidDBusMethodCallback& callback, - dbus::Response* response) { - callback.Run(response ? DBUS_METHOD_CALL_SUCCESS : DBUS_METHOD_CALL_FAILURE); +void OnVoidResponse(VoidDBusMethodCallback callback, dbus::Response* response) { + std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS + : DBUS_METHOD_CALL_FAILURE); } } // namespace @@ -87,14 +90,14 @@ weak_ptr_factory_.GetWeakPtr(), callback)); } - void DestroyAllRecords(const VoidDBusMethodCallback& callback) override { + void DestroyAllRecords(VoidDBusMethodCallback callback) override { dbus::MethodCall method_call( biod::kBiometricsManagerInterface, biod::kBiometricsManagerDestroyAllRecordsMethod); - biod_proxy_->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::Bind(&OnVoidResponse, callback)); + biod_proxy_->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::Bind(&OnVoidResponse, base::Passed(std::move(callback)))); } void StartAuthSession(const ObjectPathCallback& callback) override { @@ -129,9 +132,9 @@ weak_ptr_factory_.GetWeakPtr(), callback)); } - void CancelEnrollSession(const VoidDBusMethodCallback& callback) override { + void CancelEnrollSession(VoidDBusMethodCallback callback) override { if (!current_enroll_session_path_) { - callback.Run(DBUS_METHOD_CALL_SUCCESS); + std::move(callback).Run(DBUS_METHOD_CALL_SUCCESS); return; } dbus::MethodCall method_call(biod::kEnrollSessionInterface, @@ -139,15 +142,15 @@ dbus::ObjectProxy* enroll_session_proxy = bus_->GetObjectProxy( biod::kBiodServiceName, *current_enroll_session_path_); - enroll_session_proxy->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::Bind(&OnVoidResponse, callback)); + enroll_session_proxy->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::Bind(&OnVoidResponse, base::Passed(std::move(callback)))); current_enroll_session_path_.reset(); } - void EndAuthSession(const VoidDBusMethodCallback& callback) override { + void EndAuthSession(VoidDBusMethodCallback callback) override { if (!current_auth_session_path_) { - callback.Run(DBUS_METHOD_CALL_SUCCESS); + std::move(callback).Run(DBUS_METHOD_CALL_SUCCESS); return; } dbus::MethodCall method_call(biod::kAuthSessionInterface, @@ -155,15 +158,15 @@ dbus::ObjectProxy* auth_session_proxy = bus_->GetObjectProxy( biod::kBiodServiceName, *current_auth_session_path_); - auth_session_proxy->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::Bind(&OnVoidResponse, callback)); + auth_session_proxy->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::Bind(&OnVoidResponse, base::Passed(std::move(callback)))); current_auth_session_path_.reset(); } void SetRecordLabel(const dbus::ObjectPath& record_path, const std::string& label, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(biod::kRecordInterface, biod::kRecordSetLabelMethod); dbus::MessageWriter writer(&method_call); @@ -171,21 +174,21 @@ dbus::ObjectProxy* record_proxy = bus_->GetObjectProxy(biod::kBiodServiceName, record_path); - record_proxy->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::Bind(&OnVoidResponse, callback)); + record_proxy->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::Bind(&OnVoidResponse, base::Passed(std::move(callback)))); } void RemoveRecord(const dbus::ObjectPath& record_path, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(biod::kRecordInterface, biod::kRecordRemoveMethod); dbus::ObjectProxy* record_proxy = bus_->GetObjectProxy(biod::kBiodServiceName, record_path); - record_proxy->CallMethod(&method_call, - dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, - base::Bind(&OnVoidResponse, callback)); + record_proxy->CallMethod( + &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, + base::Bind(&OnVoidResponse, base::Passed(std::move(callback)))); } void RequestRecordLabel(const dbus::ObjectPath& record_path,
diff --git a/chromeos/dbus/biod/biod_client.h b/chromeos/dbus/biod/biod_client.h index e34c9a0..5c76c73 100644 --- a/chromeos/dbus/biod/biod_client.h +++ b/chromeos/dbus/biod/biod_client.h
@@ -101,7 +101,7 @@ // Irreversibly destroys all records registered. |callback| is called // asynchronously with the result. - virtual void DestroyAllRecords(const VoidDBusMethodCallback& callback) = 0; + virtual void DestroyAllRecords(VoidDBusMethodCallback callback) = 0; // Starts the biometric auth session. |callback| is called with the object // path of the auth session after the method succeeds. @@ -113,23 +113,23 @@ // Cancels the enroll session. // |callback| is called asynchronously with the result. - virtual void CancelEnrollSession(const VoidDBusMethodCallback& callback) = 0; + virtual void CancelEnrollSession(VoidDBusMethodCallback callback) = 0; // Ends the auth session. // |callback| is called asynchronously with the result. - virtual void EndAuthSession(const VoidDBusMethodCallback& callback) = 0; + virtual void EndAuthSession(VoidDBusMethodCallback callback) = 0; // Changes the label of the record at |record_path| to |label|. |callback| is // called asynchronously with the result. virtual void SetRecordLabel(const dbus::ObjectPath& record_path, const std::string& label, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Removes the record at |record_path|. This record will no longer be able to // used for authentication. |callback| is called asynchronously with the // result. virtual void RemoveRecord(const dbus::ObjectPath& record_path, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Requests the label of the record at |record_path|. |callback| is called // with the label of the record.
diff --git a/chromeos/dbus/biod/fake_biod_client.cc b/chromeos/dbus/biod/fake_biod_client.cc index bed86aa..5db57c05 100644 --- a/chromeos/dbus/biod/fake_biod_client.cc +++ b/chromeos/dbus/biod/fake_biod_client.cc
@@ -4,6 +4,8 @@ #include "chromeos/dbus/biod/fake_biod_client.h" +#include <utility> + #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" @@ -151,11 +153,11 @@ FROM_HERE, base::Bind(callback, records_object_paths)); } -void FakeBiodClient::DestroyAllRecords(const VoidDBusMethodCallback& callback) { +void FakeBiodClient::DestroyAllRecords(VoidDBusMethodCallback callback) { records_.clear(); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeBiodClient::StartAuthSession(const ObjectPathCallback& callback) { @@ -175,8 +177,7 @@ biod::BiometricType::BIOMETRIC_TYPE_FINGERPRINT))); } -void FakeBiodClient::CancelEnrollSession( - const VoidDBusMethodCallback& callback) { +void FakeBiodClient::CancelEnrollSession(VoidDBusMethodCallback callback) { DCHECK_EQ(current_session_, FingerprintSession::ENROLL); // Clean up the in progress enrollment. @@ -185,33 +186,33 @@ current_session_ = FingerprintSession::NONE; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } -void FakeBiodClient::EndAuthSession(const VoidDBusMethodCallback& callback) { +void FakeBiodClient::EndAuthSession(VoidDBusMethodCallback callback) { DCHECK_EQ(current_session_, FingerprintSession::AUTH); current_session_ = FingerprintSession::NONE; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeBiodClient::SetRecordLabel(const dbus::ObjectPath& record_path, const std::string& label, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { if (records_.find(record_path) != records_.end()) records_[record_path]->label = label; base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeBiodClient::RemoveRecord(const dbus::ObjectPath& record_path, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { records_.erase(record_path); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeBiodClient::RequestRecordLabel(const dbus::ObjectPath& record_path,
diff --git a/chromeos/dbus/biod/fake_biod_client.h b/chromeos/dbus/biod/fake_biod_client.h index 4de16c5..f66c6c6 100644 --- a/chromeos/dbus/biod/fake_biod_client.h +++ b/chromeos/dbus/biod/fake_biod_client.h
@@ -62,16 +62,16 @@ const ObjectPathCallback& callback) override; void GetRecordsForUser(const std::string& user_id, const UserRecordsCallback& callback) override; - void DestroyAllRecords(const VoidDBusMethodCallback& callback) override; + void DestroyAllRecords(VoidDBusMethodCallback callback) override; void StartAuthSession(const ObjectPathCallback& callback) override; void RequestType(const BiometricTypeCallback& callback) override; - void CancelEnrollSession(const VoidDBusMethodCallback& callback) override; - void EndAuthSession(const VoidDBusMethodCallback& callback) override; + void CancelEnrollSession(VoidDBusMethodCallback callback) override; + void EndAuthSession(VoidDBusMethodCallback callback) override; void SetRecordLabel(const dbus::ObjectPath& record_path, const std::string& label, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void RemoveRecord(const dbus::ObjectPath& record_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void RequestRecordLabel(const dbus::ObjectPath& record_path, const LabelCallback& callback) override;
diff --git a/chromeos/dbus/cryptohome_client.cc b/chromeos/dbus/cryptohome_client.cc index 1d469b7..c683b86 100644 --- a/chromeos/dbus/cryptohome_client.cc +++ b/chromeos/dbus/cryptohome_client.cc
@@ -7,7 +7,10 @@ #include <stddef.h> #include <stdint.h> +#include <utility> + #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/location.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -343,17 +346,17 @@ } // CryptohomeClient override. - void TpmCanAttemptOwnership(const VoidDBusMethodCallback& callback) override { + void TpmCanAttemptOwnership(VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeTpmCanAttemptOwnership); - CallVoidMethod(&method_call, callback); + CallVoidMethod(&method_call, std::move(callback)); } // CryptohomeClient overrides. - void TpmClearStoredPassword(const VoidDBusMethodCallback& callback) override { + void TpmClearStoredPassword(VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeTpmClearStoredPassword); - CallVoidMethod(&method_call, callback); + CallVoidMethod(&method_call, std::move(callback)); } // CryptohomeClient override. @@ -922,7 +925,7 @@ } void MigrateToDircrypto(const cryptohome::Identification& cryptohome_id, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeMigrateToDircrypto); @@ -936,7 +939,8 @@ // user file size and the number. Setting the time limit to infinite. proxy_->CallMethod(&method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&CryptohomeClientImpl::OnVoidMethod, - weak_ptr_factory_.GetWeakPtr(), callback)); + weak_ptr_factory_.GetWeakPtr(), + base::Passed(std::move(callback)))); } void NeedsDircryptoMigration( @@ -1030,20 +1034,16 @@ // Calls a method without result values. void CallVoidMethod(dbus::MethodCall* method_call, - const VoidDBusMethodCallback& callback) { - proxy_->CallMethod(method_call, kTpmDBusTimeoutMs , + VoidDBusMethodCallback callback) { + proxy_->CallMethod(method_call, kTpmDBusTimeoutMs, base::Bind(&CryptohomeClientImpl::OnVoidMethod, weak_ptr_factory_.GetWeakPtr(), - callback)); + base::Passed(std::move(callback)))); } - void OnVoidMethod(const VoidDBusMethodCallback& callback, - dbus::Response* response) { - if (!response) { - callback.Run(DBUS_METHOD_CALL_FAILURE); - return; - } - callback.Run(DBUS_METHOD_CALL_SUCCESS); + void OnVoidMethod(VoidDBusMethodCallback callback, dbus::Response* response) { + std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS + : DBUS_METHOD_CALL_FAILURE); } // Calls a method with a bool value reult and block.
diff --git a/chromeos/dbus/cryptohome_client.h b/chromeos/dbus/cryptohome_client.h index 58851ea..968a67b 100644 --- a/chromeos/dbus/cryptohome_client.h +++ b/chromeos/dbus/cryptohome_client.h
@@ -252,12 +252,10 @@ // Calls TpmCanAttemptOwnership method. // This method tells the service that it is OK to attempt ownership. - virtual void TpmCanAttemptOwnership( - const VoidDBusMethodCallback& callback) = 0; + virtual void TpmCanAttemptOwnership(VoidDBusMethodCallback callback) = 0; // Calls TpmClearStoredPasswordMethod. - virtual void TpmClearStoredPassword( - const VoidDBusMethodCallback& callback) = 0; + virtual void TpmClearStoredPassword(VoidDBusMethodCallback callback) = 0; // Calls TpmClearStoredPassword method and returns true when the call // succeeds. This method blocks until the call returns. @@ -577,7 +575,7 @@ // encryption. virtual void MigrateToDircrypto( const cryptohome::Identification& cryptohome_id, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Asynchronously calls RemoveFirmwareManagementParameters method. |callback| // is called after method call, and with reply protobuf.
diff --git a/chromeos/dbus/dbus_method_call_status.cc b/chromeos/dbus/dbus_method_call_status.cc index 2cd0d861..f587604d 100644 --- a/chromeos/dbus/dbus_method_call_status.cc +++ b/chromeos/dbus/dbus_method_call_status.cc
@@ -16,7 +16,7 @@ VoidDBusMethodCallback EmptyVoidDBusMethodCallback() { - return base::Bind(&EmptyVoidDBusMethodCallbackBody); + return base::BindOnce(&EmptyVoidDBusMethodCallbackBody); } } // namespace chromeos
diff --git a/chromeos/dbus/dbus_method_call_status.h b/chromeos/dbus/dbus_method_call_status.h index 7c189e2..97f4a1da 100644 --- a/chromeos/dbus/dbus_method_call_status.h +++ b/chromeos/dbus/dbus_method_call_status.h
@@ -25,8 +25,10 @@ }; // A callback to handle responses of methods without results. -typedef base::Callback<void( - DBusMethodCallStatus call_status)> VoidDBusMethodCallback; +using VoidDBusMethodCallback = + base::OnceCallback<void(DBusMethodCallStatus call_status)>; + +// TODO(crbug.com/739622): Use OnceCallback in following definition, too. // A callback to handle responses of methods returning a bool value. typedef base::Callback<void(DBusMethodCallStatus call_status,
diff --git a/chromeos/dbus/fake_arc_obb_mounter_client.cc b/chromeos/dbus/fake_arc_obb_mounter_client.cc index 7341870..e2ff8519 100644 --- a/chromeos/dbus/fake_arc_obb_mounter_client.cc +++ b/chromeos/dbus/fake_arc_obb_mounter_client.cc
@@ -4,6 +4,8 @@ #include "chromeos/dbus/fake_arc_obb_mounter_client.h" +#include <utility> + #include "base/bind.h" #include "base/callback.h" #include "base/threading/thread_task_runner_handle.h" @@ -19,16 +21,15 @@ void FakeArcObbMounterClient::MountObb(const std::string& obb_file, const std::string& mount_path, int32_t owner_gid, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_FAILURE)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_FAILURE)); } -void FakeArcObbMounterClient::UnmountObb( - const std::string& mount_path, - const VoidDBusMethodCallback& callback) { +void FakeArcObbMounterClient::UnmountObb(const std::string& mount_path, + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_FAILURE)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_FAILURE)); } } // namespace chromeos
diff --git a/chromeos/dbus/fake_arc_obb_mounter_client.h b/chromeos/dbus/fake_arc_obb_mounter_client.h index bdd11bf..2df5435 100644 --- a/chromeos/dbus/fake_arc_obb_mounter_client.h +++ b/chromeos/dbus/fake_arc_obb_mounter_client.h
@@ -22,9 +22,9 @@ void MountObb(const std::string& obb_file, const std::string& mount_path, int32_t owner_gid, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void UnmountObb(const std::string& mount_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; private: DISALLOW_COPY_AND_ASSIGN(FakeArcObbMounterClient);
diff --git a/chromeos/dbus/fake_cryptohome_client.cc b/chromeos/dbus/fake_cryptohome_client.cc index d3bae2d..6fee9df 100644 --- a/chromeos/dbus/fake_cryptohome_client.cc +++ b/chromeos/dbus/fake_cryptohome_client.cc
@@ -7,6 +7,8 @@ #include <stddef.h> #include <stdint.h> +#include <utility> + #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_util.h" @@ -234,15 +236,15 @@ } void FakeCryptohomeClient::TpmCanAttemptOwnership( - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeCryptohomeClient::TpmClearStoredPassword( - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } bool FakeCryptohomeClient::CallTpmClearStoredPasswordAndBlock() { @@ -593,9 +595,9 @@ void FakeCryptohomeClient::MigrateToDircrypto( const cryptohome::Identification& cryptohome_id, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); dircrypto_migration_progress_ = 0; dircrypto_migration_progress_timer_.Start( FROM_HERE,
diff --git a/chromeos/dbus/fake_cryptohome_client.h b/chromeos/dbus/fake_cryptohome_client.h index 87b0780..eee04a5 100644 --- a/chromeos/dbus/fake_cryptohome_client.h +++ b/chromeos/dbus/fake_cryptohome_client.h
@@ -72,8 +72,8 @@ bool CallTpmIsOwnedAndBlock(bool* owned) override; void TpmIsBeingOwned(const BoolDBusMethodCallback& callback) override; bool CallTpmIsBeingOwnedAndBlock(bool* owning) override; - void TpmCanAttemptOwnership(const VoidDBusMethodCallback& callback) override; - void TpmClearStoredPassword(const VoidDBusMethodCallback& callback) override; + void TpmCanAttemptOwnership(VoidDBusMethodCallback callback) override; + void TpmClearStoredPassword(VoidDBusMethodCallback callback) override; bool CallTpmClearStoredPasswordAndBlock() override; void Pkcs11IsTpmTokenReady(const BoolDBusMethodCallback& callback) override; void Pkcs11GetTpmTokenInfo( @@ -197,7 +197,7 @@ const cryptohome::FlushAndSignBootAttributesRequest& request, const ProtobufMethodCallback& callback) override; void MigrateToDircrypto(const cryptohome::Identification& cryptohome_id, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void SetDircryptoMigrationProgressHandler( const DircryptoMigrationProgessHandler& handler) override; void RemoveFirmwareManagementParametersFromTpm(
diff --git a/chromeos/dbus/fake_session_manager_client.cc b/chromeos/dbus/fake_session_manager_client.cc index 763d491..181776c 100644 --- a/chromeos/dbus/fake_session_manager_client.cc +++ b/chromeos/dbus/fake_session_manager_client.cc
@@ -88,10 +88,9 @@ observer.EmitLoginPromptVisibleCalled(); } -void FakeSessionManagerClient::RestartJob( - int socket_fd, - const std::vector<std::string>& argv, - const VoidDBusMethodCallback& callback) {} +void FakeSessionManagerClient::RestartJob(int socket_fd, + const std::vector<std::string>& argv, + VoidDBusMethodCallback callback) {} void FakeSessionManagerClient::StartSession( const cryptohome::Identification& cryptohome_id) {
diff --git a/chromeos/dbus/fake_session_manager_client.h b/chromeos/dbus/fake_session_manager_client.h index 8a7171f8..9d205fc 100644 --- a/chromeos/dbus/fake_session_manager_client.h +++ b/chromeos/dbus/fake_session_manager_client.h
@@ -34,7 +34,7 @@ void EmitLoginPromptVisible() override; void RestartJob(int socket_fd, const std::vector<std::string>& argv, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void StartSession(const cryptohome::Identification& cryptohome_id) override; void StopSession() override; void NotifySupervisedUserCreationStarted() override;
diff --git a/chromeos/dbus/fake_shill_device_client.cc b/chromeos/dbus/fake_shill_device_client.cc index 23867c6..0cb8164 100644 --- a/chromeos/dbus/fake_shill_device_client.cc +++ b/chromeos/dbus/fake_shill_device_client.cc
@@ -5,6 +5,7 @@ #include "chromeos/dbus/fake_shill_device_client.h" #include <algorithm> +#include <utility> #include "base/bind.h" #include "base/location.h" @@ -93,10 +94,9 @@ weak_ptr_factory_.GetWeakPtr(), device_path, callback)); } -void FakeShillDeviceClient::ProposeScan( - const dbus::ObjectPath& device_path, - const VoidDBusMethodCallback& callback) { - PostVoidCallback(callback, DBUS_METHOD_CALL_SUCCESS); +void FakeShillDeviceClient::ProposeScan(const dbus::ObjectPath& device_path, + VoidDBusMethodCallback callback) { + PostVoidCallback(std::move(callback), DBUS_METHOD_CALL_SUCCESS); } void FakeShillDeviceClient::SetProperty(const dbus::ObjectPath& device_path, @@ -130,18 +130,17 @@ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } -void FakeShillDeviceClient::ClearProperty( - const dbus::ObjectPath& device_path, - const std::string& name, - const VoidDBusMethodCallback& callback) { +void FakeShillDeviceClient::ClearProperty(const dbus::ObjectPath& device_path, + const std::string& name, + VoidDBusMethodCallback callback) { base::DictionaryValue* device_properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion(device_path.value(), &device_properties)) { - PostVoidCallback(callback, DBUS_METHOD_CALL_FAILURE); + PostVoidCallback(std::move(callback), DBUS_METHOD_CALL_FAILURE); return; } device_properties->RemoveWithoutPathExpansion(name, NULL); - PostVoidCallback(callback, DBUS_METHOD_CALL_SUCCESS); + PostVoidCallback(std::move(callback), DBUS_METHOD_CALL_SUCCESS); } void FakeShillDeviceClient::AddIPConfig( @@ -583,11 +582,10 @@ } // Posts a task to run a void callback with status code |status|. -void FakeShillDeviceClient::PostVoidCallback( - const VoidDBusMethodCallback& callback, - DBusMethodCallStatus status) { - base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, - base::Bind(callback, status)); +void FakeShillDeviceClient::PostVoidCallback(VoidDBusMethodCallback callback, + DBusMethodCallStatus status) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), status)); } void FakeShillDeviceClient::NotifyObserversPropertyChanged(
diff --git a/chromeos/dbus/fake_shill_device_client.h b/chromeos/dbus/fake_shill_device_client.h index 0d466e6..9a9933c8 100644 --- a/chromeos/dbus/fake_shill_device_client.h +++ b/chromeos/dbus/fake_shill_device_client.h
@@ -35,7 +35,7 @@ void GetProperties(const dbus::ObjectPath& device_path, const DictionaryValueCallback& callback) override; void ProposeScan(const dbus::ObjectPath& device_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void SetProperty(const dbus::ObjectPath& device_path, const std::string& name, const base::Value& value, @@ -43,7 +43,7 @@ const ErrorCallback& error_callback) override; void ClearProperty(const dbus::ObjectPath& device_path, const std::string& name, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void AddIPConfig(const dbus::ObjectPath& device_path, const std::string& method, const ObjectPathDBusMethodCallback& callback) override; @@ -133,7 +133,7 @@ const DictionaryValueCallback& callback) const; // Posts a task to run a void callback with status code |status|. - void PostVoidCallback(const VoidDBusMethodCallback& callback, + void PostVoidCallback(VoidDBusMethodCallback callback, DBusMethodCallStatus status); void SetPropertyInternal(const dbus::ObjectPath& device_path,
diff --git a/chromeos/dbus/fake_shill_ipconfig_client.cc b/chromeos/dbus/fake_shill_ipconfig_client.cc index 11deee6..14ed788 100644 --- a/chromeos/dbus/fake_shill_ipconfig_client.cc +++ b/chromeos/dbus/fake_shill_ipconfig_client.cc
@@ -4,6 +4,8 @@ #include "chromeos/dbus/fake_shill_ipconfig_client.h" +#include <utility> + #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" @@ -41,8 +43,7 @@ } void FakeShillIPConfigClient::Refresh(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) { -} + VoidDBusMethodCallback callback) {} void FakeShillIPConfigClient::GetProperties( const dbus::ObjectPath& ipconfig_path, @@ -56,11 +57,10 @@ weak_ptr_factory_.GetWeakPtr(), dict, callback)); } -void FakeShillIPConfigClient::SetProperty( - const dbus::ObjectPath& ipconfig_path, - const std::string& name, - const base::Value& value, - const VoidDBusMethodCallback& callback) { +void FakeShillIPConfigClient::SetProperty(const dbus::ObjectPath& ipconfig_path, + const std::string& name, + const base::Value& value, + VoidDBusMethodCallback callback) { base::DictionaryValue* dict = NULL; if (!ipconfigs_.GetDictionaryWithoutPathExpansion(ipconfig_path.value(), &dict)) { @@ -70,21 +70,21 @@ // Update existing ip config stub object's properties. dict->SetWithoutPathExpansion(name, base::MakeUnique<base::Value>(value)); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeShillIPConfigClient::ClearProperty( const dbus::ObjectPath& ipconfig_path, const std::string& name, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } void FakeShillIPConfigClient::Remove(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, base::BindOnce(std::move(callback), DBUS_METHOD_CALL_SUCCESS)); } ShillIPConfigClient::TestInterface*
diff --git a/chromeos/dbus/fake_shill_ipconfig_client.h b/chromeos/dbus/fake_shill_ipconfig_client.h index ba05a95..fe2a33c 100644 --- a/chromeos/dbus/fake_shill_ipconfig_client.h +++ b/chromeos/dbus/fake_shill_ipconfig_client.h
@@ -30,18 +30,18 @@ const dbus::ObjectPath& ipconfig_path, ShillPropertyChangedObserver* observer) override; void Refresh(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void GetProperties(const dbus::ObjectPath& ipconfig_path, const DictionaryValueCallback& callback) override; void SetProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, const base::Value& value, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void ClearProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void Remove(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; ShillIPConfigClient::TestInterface* GetTestInterface() override; // ShillIPConfigClient::TestInterface overrides.
diff --git a/chromeos/dbus/mock_cryptohome_client.cc b/chromeos/dbus/mock_cryptohome_client.cc index 0e860d63..d0ed940 100644 --- a/chromeos/dbus/mock_cryptohome_client.cc +++ b/chromeos/dbus/mock_cryptohome_client.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/location.h" +#include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -35,4 +36,20 @@ MockCryptohomeClient::~MockCryptohomeClient() {} +void MockCryptohomeClient::TpmCanAttemptOwnership( + VoidDBusMethodCallback callback) { + NOTREACHED() << "No mock for TmpCanAttemptOwnership."; +} + +void MockCryptohomeClient::TpmClearStoredPassword( + VoidDBusMethodCallback callback) { + NOTREACHED() << "No mock for TmpClearStoredPassword."; +} + +void MockCryptohomeClient::MigrateToDircrypto( + const cryptohome::Identification& cryptohome_id, + VoidDBusMethodCallback callback) { + NOTREACHED() << "No mock for MigrateToDircrypto."; +} + } // namespace chromeos
diff --git a/chromeos/dbus/mock_cryptohome_client.h b/chromeos/dbus/mock_cryptohome_client.h index 549e9a82..46acbe0e 100644 --- a/chromeos/dbus/mock_cryptohome_client.h +++ b/chromeos/dbus/mock_cryptohome_client.h
@@ -82,10 +82,8 @@ MOCK_METHOD1(CallTpmIsOwnedAndBlock, bool(bool* owned)); MOCK_METHOD1(TpmIsBeingOwned, void(const BoolDBusMethodCallback& callback)); MOCK_METHOD1(CallTpmIsBeingOwnedAndBlock, bool(bool* owning)); - MOCK_METHOD1(TpmCanAttemptOwnership, - void(const VoidDBusMethodCallback& callback)); - MOCK_METHOD1(TpmClearStoredPassword, - void(const VoidDBusMethodCallback& callback)); + void TpmCanAttemptOwnership(VoidDBusMethodCallback callback) override; + void TpmClearStoredPassword(VoidDBusMethodCallback callback) override; MOCK_METHOD0(CallTpmClearStoredPasswordAndBlock, bool()); MOCK_METHOD1(Pkcs11IsTpmTokenReady, void(const BoolDBusMethodCallback& callback)); @@ -222,9 +220,8 @@ FlushAndSignBootAttributes, void(const cryptohome::FlushAndSignBootAttributesRequest& request, const ProtobufMethodCallback& callback)); - MOCK_METHOD2(MigrateToDircrypto, - void(const cryptohome::Identification& cryptohome_id, - const VoidDBusMethodCallback& callback)); + void MigrateToDircrypto(const cryptohome::Identification& cryptohome_id, + VoidDBusMethodCallback callback) override; MOCK_METHOD1(SetDircryptoMigrationProgressHandler, void(const DircryptoMigrationProgessHandler& handler)); MOCK_METHOD2(
diff --git a/chromeos/dbus/mock_session_manager_client.cc b/chromeos/dbus/mock_session_manager_client.cc index a4b260a..82ce7f35 100644 --- a/chromeos/dbus/mock_session_manager_client.cc +++ b/chromeos/dbus/mock_session_manager_client.cc
@@ -4,11 +4,18 @@ #include "chromeos/dbus/mock_session_manager_client.h" +#include "base/logging.h" + namespace chromeos { MockSessionManagerClient::MockSessionManagerClient() {} MockSessionManagerClient::~MockSessionManagerClient() {} -} // namespace chromeos +void MockSessionManagerClient::RestartJob(int socket_fd, + const std::vector<std::string>& argv, + VoidDBusMethodCallback callback) { + NOTREACHED() << "No mock for RestartJob"; +} +} // namespace chromeos
diff --git a/chromeos/dbus/mock_session_manager_client.h b/chromeos/dbus/mock_session_manager_client.h index f389df4..880df89 100644 --- a/chromeos/dbus/mock_session_manager_client.h +++ b/chromeos/dbus/mock_session_manager_client.h
@@ -26,10 +26,9 @@ MOCK_CONST_METHOD1(HasObserver, bool(const Observer*)); MOCK_CONST_METHOD0(IsScreenLocked, bool(void)); MOCK_METHOD0(EmitLoginPromptVisible, void(void)); - MOCK_METHOD3(RestartJob, - void(int, - const std::vector<std::string>&, - const VoidDBusMethodCallback&)); + void RestartJob(int socket_fd, + const std::vector<std::string>& argv, + VoidDBusMethodCallback callback) override; MOCK_METHOD1(StartSession, void(const cryptohome::Identification&)); MOCK_METHOD0(StopSession, void(void)); MOCK_METHOD0(NotifySupervisedUserCreationStarted, void(void));
diff --git a/chromeos/dbus/session_manager_client.cc b/chromeos/dbus/session_manager_client.cc index ba1d38e..36ec445 100644 --- a/chromeos/dbus/session_manager_client.cc +++ b/chromeos/dbus/session_manager_client.cc
@@ -8,8 +8,10 @@ #include <stdint.h> #include <memory> +#include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/files/file_path.h" #include "base/files/file_util.h" @@ -184,7 +186,7 @@ void RestartJob(int socket_fd, const std::vector<std::string>& argv, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(login_manager::kSessionManagerInterface, login_manager::kSessionManagerRestartJob); dbus::MessageWriter writer(&method_call); @@ -193,7 +195,8 @@ session_manager_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&SessionManagerClientImpl::OnRestartJob, - weak_ptr_factory_.GetWeakPtr(), callback)); + weak_ptr_factory_.GetWeakPtr(), + base::Passed(std::move(callback)))); } void StartSession(const cryptohome::Identification& cryptohome_id) override { @@ -621,13 +624,12 @@ } // Called when kSessionManagerRestartJob method is complete. - void OnRestartJob(const VoidDBusMethodCallback& callback, - dbus::Response* response) { + void OnRestartJob(VoidDBusMethodCallback callback, dbus::Response* response) { LOG_IF(ERROR, !response) << "Failed to call " << login_manager::kSessionManagerRestartJob; - callback.Run(response ? DBUS_METHOD_CALL_SUCCESS - : DBUS_METHOD_CALL_FAILURE); + std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS + : DBUS_METHOD_CALL_FAILURE); } // Called when kSessionManagerRetrieveActiveSessions method is complete. @@ -893,7 +895,7 @@ void EmitLoginPromptVisible() override {} void RestartJob(int socket_fd, const std::vector<std::string>& argv, - const VoidDBusMethodCallback& callback) override {} + VoidDBusMethodCallback callback) override {} void StartSession(const cryptohome::Identification& cryptohome_id) override {} void StopSession() override {} void NotifySupervisedUserCreationStarted() override {}
diff --git a/chromeos/dbus/session_manager_client.h b/chromeos/dbus/session_manager_client.h index 0f52b9a..b125309 100644 --- a/chromeos/dbus/session_manager_client.h +++ b/chromeos/dbus/session_manager_client.h
@@ -116,7 +116,7 @@ // waiting for the result. virtual void RestartJob(int socket_fd, const std::vector<std::string>& argv, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Starts the session for the user. virtual void StartSession(
diff --git a/chromeos/dbus/shill_client_helper.cc b/chromeos/dbus/shill_client_helper.cc index fbff208..8564c977 100644 --- a/chromeos/dbus/shill_client_helper.cc +++ b/chromeos/dbus/shill_client_helper.cc
@@ -6,7 +6,10 @@ #include <stddef.h> +#include <utility> + #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/threading/thread_task_runner_handle.h" @@ -91,13 +94,10 @@ // Handles responses for methods without results. void OnVoidMethod(ShillClientHelper::RefHolder* ref_holder, - const VoidDBusMethodCallback& callback, + VoidDBusMethodCallback callback, dbus::Response* response) { - if (!response) { - callback.Run(DBUS_METHOD_CALL_FAILURE); - return; - } - callback.Run(DBUS_METHOD_CALL_SUCCESS); + std::move(callback).Run(response ? DBUS_METHOD_CALL_SUCCESS + : DBUS_METHOD_CALL_FAILURE); } // Handles responses for methods with ObjectPath results. @@ -276,15 +276,14 @@ weak_ptr_factory_.GetWeakPtr())); } -void ShillClientHelper::CallVoidMethod( - dbus::MethodCall* method_call, - const VoidDBusMethodCallback& callback) { +void ShillClientHelper::CallVoidMethod(dbus::MethodCall* method_call, + VoidDBusMethodCallback callback) { DCHECK(!callback.is_null()); proxy_->CallMethod( method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::Bind(&OnVoidMethod, base::Owned(new RefHolder(weak_ptr_factory_.GetWeakPtr())), - callback)); + base::Passed(std::move(callback)))); } void ShillClientHelper::CallObjectPathMethod(
diff --git a/chromeos/dbus/shill_client_helper.h b/chromeos/dbus/shill_client_helper.h index 8ab8f54..3408f00b 100644 --- a/chromeos/dbus/shill_client_helper.h +++ b/chromeos/dbus/shill_client_helper.h
@@ -90,7 +90,7 @@ // Calls a method without results. void CallVoidMethod(dbus::MethodCall* method_call, - const VoidDBusMethodCallback& callback); + VoidDBusMethodCallback callback); // Calls a method with an object path result. void CallObjectPathMethod(dbus::MethodCall* method_call,
diff --git a/chromeos/dbus/shill_device_client.cc b/chromeos/dbus/shill_device_client.cc index 12be94d..ca6ff0f 100644 --- a/chromeos/dbus/shill_device_client.cc +++ b/chromeos/dbus/shill_device_client.cc
@@ -4,6 +4,8 @@ #include "chromeos/dbus/shill_device_client.h" +#include <utility> + #include "base/bind.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" @@ -64,10 +66,10 @@ } void ProposeScan(const dbus::ObjectPath& device_path, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(shill::kFlimflamDeviceInterface, shill::kProposeScanFunction); - GetHelper(device_path)->CallVoidMethod(&method_call, callback); + GetHelper(device_path)->CallVoidMethod(&method_call, std::move(callback)); } void SetProperty(const dbus::ObjectPath& device_path, @@ -87,12 +89,12 @@ void ClearProperty(const dbus::ObjectPath& device_path, const std::string& name, - const VoidDBusMethodCallback& callback) override { + VoidDBusMethodCallback callback) override { dbus::MethodCall method_call(shill::kFlimflamDeviceInterface, shill::kClearPropertyFunction); dbus::MessageWriter writer(&method_call); writer.AppendString(name); - GetHelper(device_path)->CallVoidMethod(&method_call, callback); + GetHelper(device_path)->CallVoidMethod(&method_call, std::move(callback)); } void AddIPConfig(const dbus::ObjectPath& device_path,
diff --git a/chromeos/dbus/shill_device_client.h b/chromeos/dbus/shill_device_client.h index fccb376c8..027a318 100644 --- a/chromeos/dbus/shill_device_client.h +++ b/chromeos/dbus/shill_device_client.h
@@ -93,7 +93,7 @@ // Calls ProposeScan method. // |callback| is called after the method call finishes. virtual void ProposeScan(const dbus::ObjectPath& device_path, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Calls SetProperty method. // |callback| is called after the method call finishes. @@ -107,7 +107,7 @@ // |callback| is called after the method call finishes. virtual void ClearProperty(const dbus::ObjectPath& device_path, const std::string& name, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Calls AddIPConfig method. // |callback| is called after the method call finishes.
diff --git a/chromeos/dbus/shill_ipconfig_client.cc b/chromeos/dbus/shill_ipconfig_client.cc index c58c0c0..6c98528 100644 --- a/chromeos/dbus/shill_ipconfig_client.cc +++ b/chromeos/dbus/shill_ipconfig_client.cc
@@ -43,18 +43,18 @@ GetHelper(ipconfig_path)->RemovePropertyChangedObserver(observer); } void Refresh(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void GetProperties(const dbus::ObjectPath& ipconfig_path, const DictionaryValueCallback& callback) override; void SetProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, const base::Value& value, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void ClearProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; void Remove(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) override; + VoidDBusMethodCallback callback) override; ShillIPConfigClient::TestInterface* GetTestInterface() override; protected: @@ -97,19 +97,17 @@ GetHelper(ipconfig_path)->CallDictionaryValueMethod(&method_call, callback); } -void ShillIPConfigClientImpl::Refresh( - const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) { +void ShillIPConfigClientImpl::Refresh(const dbus::ObjectPath& ipconfig_path, + VoidDBusMethodCallback callback) { dbus::MethodCall method_call(shill::kFlimflamIPConfigInterface, shill::kRefreshFunction); - GetHelper(ipconfig_path)->CallVoidMethod(&method_call, callback); + GetHelper(ipconfig_path)->CallVoidMethod(&method_call, std::move(callback)); } -void ShillIPConfigClientImpl::SetProperty( - const dbus::ObjectPath& ipconfig_path, - const std::string& name, - const base::Value& value, - const VoidDBusMethodCallback& callback) { +void ShillIPConfigClientImpl::SetProperty(const dbus::ObjectPath& ipconfig_path, + const std::string& name, + const base::Value& value, + VoidDBusMethodCallback callback) { dbus::MethodCall method_call(shill::kFlimflamIPConfigInterface, shill::kSetPropertyFunction); dbus::MessageWriter writer(&method_call); @@ -144,26 +142,25 @@ default: DLOG(ERROR) << "Unexpected type " << value.GetType(); } - GetHelper(ipconfig_path)->CallVoidMethod(&method_call, callback); + GetHelper(ipconfig_path)->CallVoidMethod(&method_call, std::move(callback)); } void ShillIPConfigClientImpl::ClearProperty( const dbus::ObjectPath& ipconfig_path, const std::string& name, - const VoidDBusMethodCallback& callback) { + VoidDBusMethodCallback callback) { dbus::MethodCall method_call(shill::kFlimflamIPConfigInterface, shill::kClearPropertyFunction); dbus::MessageWriter writer(&method_call); writer.AppendString(name); - GetHelper(ipconfig_path)->CallVoidMethod(&method_call, callback); + GetHelper(ipconfig_path)->CallVoidMethod(&method_call, std::move(callback)); } -void ShillIPConfigClientImpl::Remove( - const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) { +void ShillIPConfigClientImpl::Remove(const dbus::ObjectPath& ipconfig_path, + VoidDBusMethodCallback callback) { dbus::MethodCall method_call(shill::kFlimflamIPConfigInterface, shill::kRemoveConfigFunction); - GetHelper(ipconfig_path)->CallVoidMethod(&method_call, callback); + GetHelper(ipconfig_path)->CallVoidMethod(&method_call, std::move(callback)); } ShillIPConfigClient::TestInterface*
diff --git a/chromeos/dbus/shill_ipconfig_client.h b/chromeos/dbus/shill_ipconfig_client.h index 374ad80..0fc94e8 100644 --- a/chromeos/dbus/shill_ipconfig_client.h +++ b/chromeos/dbus/shill_ipconfig_client.h
@@ -67,7 +67,7 @@ // Refreshes the active IP configuration after service property changes and // renews the DHCP lease, if any. virtual void Refresh(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Calls GetProperties method. // |callback| is called after the method call succeeds. @@ -79,18 +79,18 @@ virtual void SetProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, const base::Value& value, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Calls ClearProperty method. // |callback| is called after the method call succeeds. virtual void ClearProperty(const dbus::ObjectPath& ipconfig_path, const std::string& name, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Calls Remove method. // |callback| is called after the method call succeeds. virtual void Remove(const dbus::ObjectPath& ipconfig_path, - const VoidDBusMethodCallback& callback) = 0; + VoidDBusMethodCallback callback) = 0; // Returns an interface for testing (stub only), or returns NULL. virtual ShillIPConfigClient::TestInterface* GetTestInterface() = 0;
diff --git a/chromeos/printing/ppd_cache.cc b/chromeos/printing/ppd_cache.cc index 918b0e8..653c56bf 100644 --- a/chromeos/printing/ppd_cache.cc +++ b/chromeos/printing/ppd_cache.cc
@@ -116,6 +116,11 @@ } } +// Implementation of the PpdCache that uses two separate task runners for Store +// and Fetch since the two operations have different priorities. Note that the +// two operations are not sequenced so there should be no expectation that a +// call to Find will return a file that was previously Stored until the Store +// callback is run. class PpdCacheImpl : public PpdCache { public: explicit PpdCacheImpl(const base::FilePath& cache_base_dir)
diff --git a/components/BUILD.gn b/components/BUILD.gn index 91a0c0e1..8024ba4 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -203,6 +203,7 @@ "//components/offline_pages/core:unit_tests", "//components/offline_pages/core/background:unit_tests", "//components/offline_pages/core/downloads:unit_tests", + "//components/offline_pages/core/prefetch:unit_tests", "//components/offline_pages/core/request_header:unit_tests", "//components/password_manager/content/browser:unit_tests", "//components/payments/content:unit_tests",
diff --git a/components/autofill/core/browser/DEPS b/components/autofill/core/browser/DEPS index 54761f2..9bde9e8 100644 --- a/components/autofill/core/browser/DEPS +++ b/components/autofill/core/browser/DEPS
@@ -8,7 +8,6 @@ "+components/signin/core/browser", "+components/signin/core/common", "+components/sync", - "+components/ukm", "+components/variations", "+components/version_info", "+components/webdata/common", @@ -17,6 +16,7 @@ "+google_apis/gaia", "+google_apis/google_api_keys.h", "+net", + "+services/metrics/public", "+sql", "+third_party/fips181", "+third_party/libaddressinput", # For address i18n. @@ -26,3 +26,15 @@ "+ui/base", "+ui/gfx", ] + +specific_include_rules = { + "autofill_manager_unittest\.cc": [ + "+components/ukm", + ], + "autofill_metrics_unittest\.cc": [ + "+components/ukm", + ], + "test_autofill_client\.h": [ + "+components/ukm", + ], +}
diff --git a/components/autofill/core/browser/autofill_metrics.cc b/components/autofill/core/browser/autofill_metrics.cc index c076cdf..e48a4a1 100644 --- a/components/autofill/core/browser/autofill_metrics.cc +++ b/components/autofill/core/browser/autofill_metrics.cc
@@ -21,7 +21,7 @@ #include "components/autofill/core/browser/form_structure.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/form_data.h" -#include "components/ukm/public/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" namespace internal { const char kUKMCardUploadDecisionEntryName[] = "Autofill.CardUploadDecision";
diff --git a/components/autofill/core/browser/autofill_metrics.h b/components/autofill/core/browser/autofill_metrics.h index 29203efc..0faa6bd 100644 --- a/components/autofill/core/browser/autofill_metrics.h +++ b/components/autofill/core/browser/autofill_metrics.h
@@ -19,7 +19,7 @@ #include "components/autofill/core/common/autofill_pref_names.h" #include "components/autofill/core/common/form_field_data.h" #include "components/autofill/core/common/signatures_util.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace internal { // Name constants are exposed here so they can be referenced from tests.
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index 7beba16..a18ae1b 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -38,7 +38,7 @@ #include "components/autofill/core/common/signatures_util.h" #include "components/rappor/public/rappor_utils.h" #include "components/rappor/rappor_service_impl.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace autofill { namespace {
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 72c18a83..3cf073b6ce 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -37,6 +37,7 @@ #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/signin/core/browser/signin_metrics.h" +#include "components/signin/core/common/profile_management_switches.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/bind_to_task_runner.h" #include "components/sync/base/cryptographer.h" @@ -1962,6 +1963,14 @@ // Track the fact that we're still waiting for auth to complete. is_auth_in_progress_ = true; } + + if (switches::IsAccountConsistencyDiceEnabled() && + oauth2_token_service_->RefreshTokenIsAvailable(account_id)) { + // When Dice is enabled, the refresh token may be available before the user + // enables sync. Start sync if the refresh token is already available in the + // token service when the authenticated account is set. + OnRefreshTokenAvailable(account_id); + } } void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
diff --git a/components/chrome_cleaner/public/constants/constants.h b/components/chrome_cleaner/public/constants/constants.h index a66b045..4b4ed44 100644 --- a/components/chrome_cleaner/public/constants/constants.h +++ b/components/chrome_cleaner/public/constants/constants.h
@@ -33,10 +33,8 @@ // The Chrome version string. extern const char kChromeVersionSwitch[]; -// Indicates whether logs upload is enabled in the cleaner process. Should be -// set by Chrome only be set if user has opted into Safe Browsing Extended -// Reporting v2. Takes effect only if execution mode is not -// ExecutionMode::kNone. +// Indicates whether logs upload is enabled in the cleaner process. +// Takes effect only if execution mode is ExecutionMode::kCleanup. extern const char kEnableCleanerLoggingSwitch[]; // Indicates that crash reporting is enabled for the current user. @@ -54,6 +52,7 @@ extern const char kExecutionModeSwitch[]; // Indicates that the current user opted into Safe Browsing Extended Reporting. +// This should not be used by non-legacy-mode Chrome Cleanup Tool. extern const char kExtendedSafeBrowsingEnabledSwitch[]; // Specifies the suffix to the registry path where metrics data will be saved. @@ -115,12 +114,11 @@ // will show its own UI and handle logs uploading permissions. kNone = 0, // The cleaner will run in scanning mode. No UI will be shown to the user - // (UI handled by Chrome) and logs will only be uploaded if the user opted - // into Extended Safe Browsing Reporting. + // (UI handled by Chrome) and logs will not be uploaded. kScanning = 1, // The cleaner will run in cleanup mode only. No UI will be shown to the - // user (UI handled by Chrome) and logs will only be uploaded if the user - // opted into Extended Safe Browsing Reporting v2. + // user (UI handled by Chrome) and logs should only be uploaded if + // |kEnableCleanerLoggingSwitch| is set. kCleanup = 2, // Auxiliary enumerator for range checking.
diff --git a/components/content_settings/core/browser/content_settings_pref_provider.cc b/components/content_settings/core/browser/content_settings_pref_provider.cc index fc1d59bb..6eaff3f 100644 --- a/components/content_settings/core/browser/content_settings_pref_provider.cc +++ b/components/content_settings/core/browser/content_settings_pref_provider.cc
@@ -45,7 +45,6 @@ "profile.content_settings.exceptions.mouselock"; #endif // !defined(OS_ANDROID) #endif // !defined(OS_IOS) -const char kObsoleteLastUsed[] = "last_used"; } // namespace @@ -253,34 +252,6 @@ prefs_->Set(permission_autoblocker_data_pref, *old_dict); prefs_->ClearPref(prompt_no_decision_count_pref); #endif // !defined(OS_IOS) - - // TODO(timloh): See crbug.com/691893. This removal code was added in M58, - // so is probably fine to remove in M60 or later. - for (const WebsiteSettingsInfo* info : - *WebsiteSettingsRegistry::GetInstance()) { - if (!prefs_->GetDictionary(info->pref_name())) - continue; - - prefs::ScopedDictionaryPrefUpdate update(prefs_, info->pref_name()); - auto all_settings = update.Get(); - std::vector<std::string> values_to_clean; - for (base::DictionaryValue::Iterator i(*all_settings->AsConstDictionary()); - !i.IsAtEnd(); i.Advance()) { - const base::DictionaryValue* pattern_settings = nullptr; - bool is_dictionary = i.value().GetAsDictionary(&pattern_settings); - DCHECK(is_dictionary); - if (pattern_settings->GetWithoutPathExpansion(kObsoleteLastUsed, nullptr)) - values_to_clean.push_back(i.key()); - } - - for (const std::string& key : values_to_clean) { - std::unique_ptr<prefs::DictionaryValueUpdate> pattern_settings; - all_settings->GetDictionaryWithoutPathExpansion(key, &pattern_settings); - pattern_settings->RemoveWithoutPathExpansion(kObsoleteLastUsed, nullptr); - if (pattern_settings->empty()) - all_settings->RemoveWithoutPathExpansion(key, nullptr); - } - } } void PrefProvider::SetClockForTesting(std::unique_ptr<base::Clock> clock) {
diff --git a/components/cryptauth/cryptauth_api_call_flow.cc b/components/cryptauth/cryptauth_api_call_flow.cc index cfacd899..c0de9b4 100644 --- a/components/cryptauth/cryptauth_api_call_flow.cc +++ b/components/cryptauth/cryptauth_api_call_flow.cc
@@ -6,6 +6,7 @@ #include "base/strings/string_number_conversions.h" #include "components/proximity_auth/logging/logging.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" namespace cryptauth { @@ -80,4 +81,10 @@ error_callback_.Run(error_message); } +net::PartialNetworkTrafficAnnotationTag +CryptAuthApiCallFlow::GetNetworkTrafficAnnotationTag() { + DCHECK(partial_network_annotation_ != nullptr); + return *partial_network_annotation_.get(); +} + } // namespace cryptauth
diff --git a/components/cryptauth/cryptauth_api_call_flow.h b/components/cryptauth/cryptauth_api_call_flow.h index 07a487e..ce5e34d29 100644 --- a/components/cryptauth/cryptauth_api_call_flow.h +++ b/components/cryptauth/cryptauth_api_call_flow.h
@@ -40,6 +40,14 @@ const ResultCallback& result_callback, const ErrorCallback& error_callback); + void SetPartialNetworkTrafficAnnotation( + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation) { + partial_network_annotation_.reset( + new net::PartialNetworkTrafficAnnotationTag( + partial_traffic_annotation)); + } + protected: // Reduce the visibility of OAuth2ApiCallFlow::Start() to avoid exposing // overloaded methods. @@ -53,6 +61,8 @@ const std::string& body) override; void ProcessApiCallSuccess(const net::URLFetcher* source) override; void ProcessApiCallFailure(const net::URLFetcher* source) override; + net::PartialNetworkTrafficAnnotationTag GetNetworkTrafficAnnotationTag() + override; private: // The URL of the CryptAuth endpoint serving the request. @@ -68,6 +78,9 @@ // Callback invoked with an error message when the flow fails. ErrorCallback error_callback_; + std::unique_ptr<net::PartialNetworkTrafficAnnotationTag> + partial_network_annotation_; + DISALLOW_COPY_AND_ASSIGN(CryptAuthApiCallFlow); };
diff --git a/components/cryptauth/cryptauth_api_call_flow_unittest.cc b/components/cryptauth/cryptauth_api_call_flow_unittest.cc index cbc6701..2c973207 100644 --- a/components/cryptauth/cryptauth_api_call_flow_unittest.cc +++ b/components/cryptauth/cryptauth_api_call_flow_unittest.cc
@@ -30,7 +30,10 @@ protected: CryptAuthApiCallFlowTest() : url_request_context_getter_(new net::TestURLRequestContextGetter( - new base::TestSimpleTaskRunner())) {} + new base::TestSimpleTaskRunner())) { + flow_.SetPartialNetworkTrafficAnnotation( + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); + } void SetUp() override { // The TestURLFetcherFactory will override the global URLFetcherFactory for
diff --git a/components/cryptauth/cryptauth_client.h b/components/cryptauth/cryptauth_client.h index 98c83d41..6779bfb8 100644 --- a/components/cryptauth/cryptauth_client.h +++ b/components/cryptauth/cryptauth_client.h
@@ -10,6 +10,7 @@ #include "base/callback_forward.h" #include "base/macros.h" +#include "net/traffic_annotation/network_traffic_annotation.h" namespace cryptauth { class GetMyDevicesRequest; @@ -45,7 +46,9 @@ GetMyDevicesCallback; virtual void GetMyDevices(const GetMyDevicesRequest& request, const GetMyDevicesCallback& callback, - const ErrorCallback& error_callback) = 0; + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation) = 0; // FindEligibleUnlockDevices typedef base::Callback<void( @@ -62,7 +65,9 @@ virtual void SendDeviceSyncTickle( const SendDeviceSyncTickleRequest& request, const SendDeviceSyncTickleCallback& callback, - const ErrorCallback& error_callback) = 0; + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation) = 0; // ToggleEasyUnlock typedef base::Callback<void(const ToggleEasyUnlockResponse&)>
diff --git a/components/cryptauth/cryptauth_client_impl.cc b/components/cryptauth/cryptauth_client_impl.cc index 25983859..92756ea 100644 --- a/components/cryptauth/cryptauth_client_impl.cc +++ b/components/cryptauth/cryptauth_client_impl.cc
@@ -66,44 +66,148 @@ void CryptAuthClientImpl::GetMyDevices( const GetMyDevicesRequest& request, const GetMyDevicesCallback& callback, - const ErrorCallback& error_callback) { - MakeApiCall(kGetMyDevicesPath, request, callback, error_callback); + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation) { + MakeApiCall(kGetMyDevicesPath, request, callback, error_callback, + partial_traffic_annotation); } void CryptAuthClientImpl::FindEligibleUnlockDevices( const FindEligibleUnlockDevicesRequest& request, const FindEligibleUnlockDevicesCallback& callback, const ErrorCallback& error_callback) { - MakeApiCall(kFindEligibleUnlockDevicesPath, request, callback, - error_callback); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation( + "cryptauth_find_eligible_unlock_devices", "oauth2_api_call_flow", + R"( + semantics { + sender: "CryptAuth Device Manager" + description: + "Gets the list of mobile devices that can be used by Smart Lock to " + "unlock the current device." + trigger: + "This request is sent when the user starts the Smart Lock setup flow." + data: "OAuth 2.0 token and the device's public key." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled in settings, but the request will " + "only be sent if the user explicitly tries to enable Smart Lock " + "(EasyUnlock), i.e. starts the setup flow." + chrome_policy { + EasyUnlockAllowed { + EasyUnlockAllowed: false + } + } + })"); + MakeApiCall(kFindEligibleUnlockDevicesPath, request, callback, error_callback, + partial_traffic_annotation); } void CryptAuthClientImpl::SendDeviceSyncTickle( const SendDeviceSyncTickleRequest& request, const SendDeviceSyncTickleCallback& callback, - const ErrorCallback& error_callback) { - MakeApiCall(kSendDeviceSyncTicklePath, request, callback, error_callback); + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation) { + MakeApiCall(kSendDeviceSyncTicklePath, request, callback, error_callback, + partial_traffic_annotation); } void CryptAuthClientImpl::ToggleEasyUnlock( const ToggleEasyUnlockRequest& request, const ToggleEasyUnlockCallback& callback, const ErrorCallback& error_callback) { - MakeApiCall(kToggleEasyUnlockPath, request, callback, error_callback); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation("cryptauth_toggle_easyunlock", + "oauth2_api_call_flow", R"( + semantics { + sender: "CryptAuth Device Manager" + description: "Enables Smart Lock (EasyUnlock) for the current device." + trigger: + "This request is send after the user goes through the EasyUnlock " + "setup flow." + data: "OAuth 2.0 token and the device public key." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled in settings, but the request will " + "only be send if the user explicitly enables Smart Lock " + "(EasyUnlock), i.e. uccessfully complete the setup flow." + chrome_policy { + EasyUnlockAllowed { + EasyUnlockAllowed: false + } + } + })"); + MakeApiCall(kToggleEasyUnlockPath, request, callback, error_callback, + partial_traffic_annotation); } void CryptAuthClientImpl::SetupEnrollment( const SetupEnrollmentRequest& request, const SetupEnrollmentCallback& callback, const ErrorCallback& error_callback) { - MakeApiCall(kSetupEnrollmentPath, request, callback, error_callback); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation( + "cryptauth_enrollment_flow_setup", "oauth2_api_call_flow", R"( + semantics { + sender: "CryptAuth Device Manager" + description: "Starts the CryptAuth registration flow." + trigger: + "Occurs periodically, at least once a month, because if the device " + "does not re-enroll for more than a specific number of days " + "(currently 45) it will be removed from the server." + data: + "Various device information (public key, bluetooth MAC address, " + "model, OS version, screen size, manufacturer, has screen lock " + "enabled), and OAuth 2.0 token." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled by settings. However, this request " + "is made only for signed-in users." + chrome_policy { + SigninAllowed { + SigninAllowed: false + } + } + })"); + MakeApiCall(kSetupEnrollmentPath, request, callback, error_callback, + partial_traffic_annotation); } void CryptAuthClientImpl::FinishEnrollment( const FinishEnrollmentRequest& request, const FinishEnrollmentCallback& callback, const ErrorCallback& error_callback) { - MakeApiCall(kFinishEnrollmentPath, request, callback, error_callback); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation( + "cryptauth_enrollment_flow_finish", "oauth2_api_call_flow", R"( + semantics { + sender: "CryptAuth Device Manager" + description: "Finishes the CryptAuth registration flow." + trigger: + "Occurs periodically, at least once a month, because if the device " + "does not re-enroll for more than a specific number of days " + "(currently 45) it will be removed from the server." + data: "OAuth 2.0 token." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled by settings. However, this request " + "is made only for signed-in users." + chrome_policy { + SigninAllowed { + SigninAllowed: false + } + } + })"); + MakeApiCall(kFinishEnrollmentPath, request, callback, error_callback, + partial_traffic_annotation); } std::string CryptAuthClientImpl::GetAccessTokenUsed() { @@ -115,7 +219,8 @@ const std::string& request_path, const RequestProto& request_proto, const base::Callback<void(const ResponseProto&)>& response_callback, - const ErrorCallback& error_callback) { + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation) { if (has_call_started_) { error_callback.Run( "Client has been used for another request. Do not reuse."); @@ -123,6 +228,9 @@ } has_call_started_ = true; + api_call_flow_->SetPartialNetworkTrafficAnnotation( + partial_traffic_annotation); + // The |device_classifier| field must be present for all CryptAuth requests. RequestProto request_copy(request_proto); request_copy.mutable_device_classifier()->CopyFrom(device_classifier_);
diff --git a/components/cryptauth/cryptauth_client_impl.h b/components/cryptauth/cryptauth_client_impl.h index d880a11..31d7ddf0 100644 --- a/components/cryptauth/cryptauth_client_impl.h +++ b/components/cryptauth/cryptauth_client_impl.h
@@ -11,6 +11,7 @@ #include "components/cryptauth/cryptauth_api_call_flow.h" #include "components/cryptauth/cryptauth_client.h" #include "components/cryptauth/proto/cryptauth_api.pb.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context_getter.h" class OAuth2TokenService; @@ -39,15 +40,18 @@ // CryptAuthClient: void GetMyDevices(const GetMyDevicesRequest& request, const GetMyDevicesCallback& callback, - const ErrorCallback& error_callback) override; + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation) override; void FindEligibleUnlockDevices( const FindEligibleUnlockDevicesRequest& request, const FindEligibleUnlockDevicesCallback& callback, const ErrorCallback& error_callback) override; - void SendDeviceSyncTickle( - const SendDeviceSyncTickleRequest& request, - const SendDeviceSyncTickleCallback& callback, - const ErrorCallback& error_callback) override; + void SendDeviceSyncTickle(const SendDeviceSyncTickleRequest& request, + const SendDeviceSyncTickleCallback& callback, + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation) override; void ToggleEasyUnlock(const ToggleEasyUnlockRequest& request, const ToggleEasyUnlockCallback& callback, const ErrorCallback& error_callback) override; @@ -68,7 +72,9 @@ const std::string& request_path, const RequestProto& request_proto, const base::Callback<void(const ResponseProto&)>& response_callback, - const ErrorCallback& error_callback); + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation); // Called when the access token is obtained so the API request can be made. template <class ResponseProto>
diff --git a/components/cryptauth/cryptauth_client_impl_unittest.cc b/components/cryptauth/cryptauth_client_impl_unittest.cc index 20224c0..4a012ec 100644 --- a/components/cryptauth/cryptauth_client_impl_unittest.cc +++ b/components/cryptauth/cryptauth_client_impl_unittest.cc
@@ -13,6 +13,7 @@ #include "components/cryptauth/proto/cryptauth_api.pb.h" #include "components/cryptauth/switches.h" #include "google_apis/gaia/fake_oauth2_token_service.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" @@ -63,7 +64,9 @@ // Mock CryptAuthApiCallFlow, which handles the HTTP requests to CryptAuth. class MockCryptAuthApiCallFlow : public CryptAuthApiCallFlow { public: - MockCryptAuthApiCallFlow() : CryptAuthApiCallFlow() {} + MockCryptAuthApiCallFlow() : CryptAuthApiCallFlow() { + SetPartialNetworkTrafficAnnotation(PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); + } virtual ~MockCryptAuthApiCallFlow() {} MOCK_METHOD6(Start, @@ -166,7 +169,8 @@ client_->GetMyDevices( request_proto, base::Bind(&SaveResult<GetMyDevicesResponse>, &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); GetMyDevicesRequest expected_request; EXPECT_TRUE(expected_request.ParseFromString(serialized_request_)); @@ -203,7 +207,8 @@ std::string error_message; client_->GetMyDevices(GetMyDevicesRequest(), base::Bind(&NotCalled<GetMyDevicesResponse>), - base::Bind(&SaveResult<std::string>, &error_message)); + base::Bind(&SaveResult<std::string>, &error_message), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); std::string kStatus500Error("HTTP status: 500"); FailApiCallFlow(kStatus500Error); @@ -279,9 +284,9 @@ SendDeviceSyncTickleResponse result_proto; client_->SendDeviceSyncTickle( SendDeviceSyncTickleRequest(), - base::Bind(&SaveResult<SendDeviceSyncTickleResponse>, - &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&SaveResult<SendDeviceSyncTickleResponse>, &result_proto), + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); SendDeviceSyncTickleRequest expected_request; EXPECT_TRUE(expected_request.ParseFromString(serialized_request_)); @@ -401,7 +406,8 @@ std::string error_message; client_->GetMyDevices(GetMyDevicesRequest(), base::Bind(&NotCalled<GetMyDevicesResponse>), - base::Bind(&SaveResult<std::string>, &error_message)); + base::Bind(&SaveResult<std::string>, &error_message), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ("Failed to get a valid access token.", error_message); } @@ -414,7 +420,8 @@ std::string error_message; client_->GetMyDevices(GetMyDevicesRequest(), base::Bind(&NotCalled<GetMyDevicesResponse>), - base::Bind(&SaveResult<std::string>, &error_message)); + base::Bind(&SaveResult<std::string>, &error_message), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); flow_result_callback_.Run("Not a valid serialized response message."); EXPECT_EQ("Failed to parse response proto.", error_message); @@ -431,7 +438,8 @@ client_->GetMyDevices( GetMyDevicesRequest(), base::Bind(&SaveResult<GetMyDevicesResponse>, &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); // With request pending, make second request. { @@ -466,7 +474,8 @@ std::string error_message; client_->GetMyDevices(GetMyDevicesRequest(), base::Bind(&NotCalled<GetMyDevicesResponse>), - base::Bind(&SaveResult<std::string>, &error_message)); + base::Bind(&SaveResult<std::string>, &error_message), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); // With request pending, make second request. { @@ -496,7 +505,8 @@ client_->GetMyDevices( GetMyDevicesRequest(), base::Bind(&SaveResult<GetMyDevicesResponse>, &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); GetMyDevicesResponse response_proto; response_proto.add_devices(); @@ -529,7 +539,8 @@ client_->GetMyDevices( request_proto, base::Bind(&SaveResult<GetMyDevicesResponse>, &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); GetMyDevicesRequest expected_request; EXPECT_TRUE(expected_request.ParseFromString(serialized_request_)); @@ -555,7 +566,8 @@ client_->GetMyDevices( request_proto, base::Bind(&SaveResult<GetMyDevicesResponse>, &result_proto), - base::Bind(&NotCalled<std::string>)); + base::Bind(&NotCalled<std::string>), + PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS); EXPECT_EQ(kAccessToken, client_->GetAccessTokenUsed()); }
diff --git a/components/cryptauth/cryptauth_device_manager.cc b/components/cryptauth/cryptauth_device_manager.cc index a12def4..4cea3fb 100644 --- a/components/cryptauth/cryptauth_device_manager.cc +++ b/components/cryptauth/cryptauth_device_manager.cc
@@ -18,6 +18,7 @@ #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/proximity_auth/logging/logging.h" +#include "net/traffic_annotation/network_traffic_annotation.h" namespace cryptauth { @@ -542,11 +543,38 @@ GetMyDevicesRequest request; request.set_invocation_reason(invocation_reason); request.set_allow_stale_read(is_sync_speculative); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation("cryptauth_get_my_devices", + "oauth2_api_call_flow", R"( + semantics { + sender: "CryptAuth Device Manager" + description: + "Gets a list of the devices registered (for the same user) on " + "CryptAuth." + trigger: + "Once every day, or by API request. Periodic calls happen because " + "devides that do not re-enrolled for more than X days (currently 45) " + "are automatically removed from the server." + data: "OAuth 2.0 token." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled in settings. However, this request " + "is made only for signed-in users." + chrome_policy { + SigninAllowed { + SigninAllowed: false + } + } + })"); cryptauth_client_->GetMyDevices( - request, base::Bind(&CryptAuthDeviceManager::OnGetMyDevicesSuccess, - weak_ptr_factory_.GetWeakPtr()), + request, + base::Bind(&CryptAuthDeviceManager::OnGetMyDevicesSuccess, + weak_ptr_factory_.GetWeakPtr()), base::Bind(&CryptAuthDeviceManager::OnGetMyDevicesFailure, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetWeakPtr()), + partial_traffic_annotation); } } // namespace cryptauth
diff --git a/components/cryptauth/cryptauth_device_manager_unittest.cc b/components/cryptauth/cryptauth_device_manager_unittest.cc index 0c6ae094..276e050 100644 --- a/components/cryptauth/cryptauth_device_manager_unittest.cc +++ b/components/cryptauth/cryptauth_device_manager_unittest.cc
@@ -21,6 +21,7 @@ #include "components/cryptauth/pref_names.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/prefs/testing_pref_service.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -469,7 +470,7 @@ // MockCryptAuthClientFactory::Observer: void OnCryptAuthClientCreated(MockCryptAuthClient* client) override { - EXPECT_CALL(*client, GetMyDevices(_, _, _)) + EXPECT_CALL(*client, GetMyDevices(_, _, _, _)) .WillOnce(DoAll(SaveArg<0>(&get_my_devices_request_), SaveArg<1>(&success_callback_), SaveArg<2>(&error_callback_)));
diff --git a/components/cryptauth/mock_cryptauth_client.h b/components/cryptauth/mock_cryptauth_client.h index ddc40e9..d5d3b24 100644 --- a/components/cryptauth/mock_cryptauth_client.h +++ b/components/cryptauth/mock_cryptauth_client.h
@@ -19,18 +19,22 @@ ~MockCryptAuthClient() override; // CryptAuthClient: - MOCK_METHOD3(GetMyDevices, + MOCK_METHOD4(GetMyDevices, void(const GetMyDevicesRequest& request, const GetMyDevicesCallback& callback, - const ErrorCallback& error_callback)); + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation)); MOCK_METHOD3(FindEligibleUnlockDevices, void(const FindEligibleUnlockDevicesRequest& request, const FindEligibleUnlockDevicesCallback& callback, const ErrorCallback& error_callback)); - MOCK_METHOD3(SendDeviceSyncTickle, + MOCK_METHOD4(SendDeviceSyncTickle, void(const SendDeviceSyncTickleRequest& request, const SendDeviceSyncTickleCallback& callback, - const ErrorCallback& error_callback)); + const ErrorCallback& error_callback, + const net::PartialNetworkTrafficAnnotationTag& + partial_traffic_annotation)); MOCK_METHOD3(ToggleEasyUnlock, void(const ToggleEasyUnlockRequest& request, const ToggleEasyUnlockCallback& callback,
diff --git a/components/exo/notification_surface.cc b/components/exo/notification_surface.cc index b1adf4e..79f613b 100644 --- a/components/exo/notification_surface.cc +++ b/components/exo/notification_surface.cc
@@ -88,8 +88,8 @@ root_surface()->RemoveSurfaceObserver(this); } -const gfx::Size& NotificationSurface::GetSize() const { - return host_window()->bounds().size(); +const gfx::Size& NotificationSurface::GetContentSize() const { + return root_surface()->content_size(); } void NotificationSurface::OnSurfaceCommit() {
diff --git a/components/exo/notification_surface.h b/components/exo/notification_surface.h index 5e128d2d..a202ba6 100644 --- a/components/exo/notification_surface.h +++ b/components/exo/notification_surface.h
@@ -25,7 +25,8 @@ const std::string& notification_key); ~NotificationSurface() override; - const gfx::Size& GetSize() const; + // Get the content size of the |root_surface()|. + const gfx::Size& GetContentSize() const; const std::string& notification_key() const { return notification_key_; }
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index c9be39b..3b32f0b 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -1313,7 +1313,7 @@ return widget_->GetNativeWindow(); case BoundsMode::CLIENT: - return host_window(); + return root_surface() ? root_surface()->window() : nullptr; case BoundsMode::FIXED: return nullptr;
diff --git a/components/exo/surface_tree_host.h b/components/exo/surface_tree_host.h index 046b73c9..c92a434 100644 --- a/components/exo/surface_tree_host.h +++ b/components/exo/surface_tree_host.h
@@ -50,7 +50,9 @@ aura::Window* host_window() { return host_window_.get(); } const aura::Window* host_window() const { return host_window_.get(); } + Surface* root_surface() { return root_surface_; } + const Surface* root_surface() const { return root_surface_; } // Overridden from SurfaceDelegate: void OnSurfaceCommit() override;
diff --git a/components/grpc_support/test/get_stream_engine.cc b/components/grpc_support/test/get_stream_engine.cc index a4dbae0..7a71807 100644 --- a/components/grpc_support/test/get_stream_engine.cc +++ b/components/grpc_support/test/get_stream_engine.cc
@@ -55,7 +55,7 @@ url::SchemeHostPort quic_hint_server("https", kTestServerHost, 443); server_properties_->SetQuicAlternativeService( quic_hint_server, alternative_service, base::Time::Max(), - params->quic_supported_versions); + net::QuicVersionVector()); request_context_->set_cert_verifier(mock_cert_verifier_.get()); request_context_->set_host_resolver(host_resolver_.get());
diff --git a/components/history/core/browser/top_sites_backend.cc b/components/history/core/browser/top_sites_backend.cc index 7b0437e..f343d5b3 100644 --- a/components/history/core/browser/top_sites_backend.cc +++ b/components/history/core/browser/top_sites_backend.cc
@@ -86,7 +86,7 @@ } void TopSitesBackend::InitDBOnDBThread(const base::FilePath& path) { - DCHECK(db_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); if (!db_->Init(path)) { LOG(ERROR) << "Failed to initialize database."; db_.reset(); @@ -94,13 +94,13 @@ } void TopSitesBackend::ShutdownDBOnDBThread() { - DCHECK(db_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); db_.reset(); } void TopSitesBackend::GetMostVisitedThumbnailsOnDBThread( scoped_refptr<MostVisitedThumbnails> thumbnails) { - DCHECK(db_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); if (db_) { db_->GetPageThumbnails(&(thumbnails->most_visited), @@ -142,7 +142,7 @@ } void TopSitesBackend::ResetDatabaseOnDBThread(const base::FilePath& file_path) { - DCHECK(db_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(db_task_runner_->RunsTasksInCurrentSequence()); db_.reset(NULL); sql::Connection::Delete(db_path_); db_.reset(new TopSitesDatabase());
diff --git a/components/net_log/BUILD.gn b/components/net_log/BUILD.gn index fd7d1295..133894e 100644 --- a/components/net_log/BUILD.gn +++ b/components/net_log/BUILD.gn
@@ -6,10 +6,10 @@ sources = [ "chrome_net_log.cc", "chrome_net_log.h", + "net_export_file_writer.cc", + "net_export_file_writer.h", "net_export_ui_constants.cc", "net_export_ui_constants.h", - "net_log_file_writer.cc", - "net_log_file_writer.h", ] deps = [ @@ -23,7 +23,7 @@ source_set("unit_tests") { testonly = true sources = [ - "net_log_file_writer_unittest.cc", + "net_export_file_writer_unittest.cc", ] deps = [ ":net_log",
diff --git a/components/net_log/chrome_net_log.cc b/components/net_log/chrome_net_log.cc index 304b992..509de9d1 100644 --- a/components/net_log/chrome_net_log.cc +++ b/components/net_log/chrome_net_log.cc
@@ -16,7 +16,7 @@ #include "base/values.h" #include "build/build_config.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_store.h" -#include "components/net_log/net_log_file_writer.h" +#include "components/net_log/net_export_file_writer.h" #include "components/version_info/version_info.h" #include "net/log/net_log_util.h" #include "net/log/trace_net_log_observer.h" @@ -24,47 +24,13 @@ namespace net_log { -ChromeNetLog::ChromeNetLog( - const base::FilePath& log_file, - net::NetLogCaptureMode log_file_mode, - const base::CommandLine::StringType& command_line_string, - const std::string& channel_string) - : net_log_file_writer_(new NetLogFileWriter(this)) { - if (!log_file.empty()) { - // Much like logging.h, bypass threading restrictions by using fopen - // directly. Have to write on a thread that's shutdown to handle events on - // shutdown properly, and posting events to another thread as they occur - // would result in an unbounded buffer size, so not much can be gained by - // doing this on another thread. It's only used when debugging Chrome, so - // performance is not a big concern. - base::ScopedFILE file; -#if defined(OS_WIN) - file.reset(_wfopen(log_file.value().c_str(), L"w")); -#elif defined(OS_POSIX) - file.reset(fopen(log_file.value().c_str(), "w")); -#endif - - if (!file) { - LOG(ERROR) << "Could not open file " << log_file.value() - << " for net logging"; - } else { - std::unique_ptr<base::Value> constants( - GetConstants(command_line_string, channel_string)); - write_to_file_observer_.reset(new net::WriteToFileNetLogObserver()); - - write_to_file_observer_->set_capture_mode(log_file_mode); - - write_to_file_observer_->StartObserving(this, std::move(file), - constants.get(), nullptr); - } - } - +ChromeNetLog::ChromeNetLog() { trace_net_log_observer_.reset(new net::TraceNetLogObserver()); trace_net_log_observer_->WatchForTraceStart(this); } ChromeNetLog::~ChromeNetLog() { - net_log_file_writer_.reset(); + net_export_file_writer_.reset(); // Remove the observers we own before we're destroyed. if (write_to_file_observer_) write_to_file_observer_->StopObserving(nullptr); @@ -72,10 +38,47 @@ trace_net_log_observer_->StopWatchForTraceStart(); } -NetLogFileWriter* ChromeNetLog::net_log_file_writer() { - if (!net_log_file_writer_) - net_log_file_writer_ = base::WrapUnique(new NetLogFileWriter(this)); - return net_log_file_writer_.get(); +void ChromeNetLog::StartWritingToFile( + const base::FilePath& log_file, + net::NetLogCaptureMode log_file_mode, + const base::CommandLine::StringType& command_line_string, + const std::string& channel_string) { + DCHECK(!log_file.empty()); + + // TODO(716570): Use common code to write NetLog to file. + + // Much like logging.h, bypass threading restrictions by using fopen + // directly. Have to write on a thread that's shutdown to handle events on + // shutdown properly, and posting events to another thread as they occur + // would result in an unbounded buffer size, so not much can be gained by + // doing this on another thread. It's only used when debugging Chrome, so + // performance is not a big concern. + base::ScopedFILE file; +#if defined(OS_WIN) + file.reset(_wfopen(log_file.value().c_str(), L"w")); +#elif defined(OS_POSIX) + file.reset(fopen(log_file.value().c_str(), "w")); +#endif + + if (!file) { + LOG(ERROR) << "Could not open file " << log_file.value() + << " for net logging"; + } else { + std::unique_ptr<base::Value> constants( + GetConstants(command_line_string, channel_string)); + write_to_file_observer_.reset(new net::WriteToFileNetLogObserver()); + + write_to_file_observer_->set_capture_mode(log_file_mode); + + write_to_file_observer_->StartObserving(this, std::move(file), + constants.get(), nullptr); + } +} + +NetExportFileWriter* ChromeNetLog::net_export_file_writer() { + if (!net_export_file_writer_) + net_export_file_writer_ = base::WrapUnique(new NetExportFileWriter(this)); + return net_export_file_writer_.get(); } // static
diff --git a/components/net_log/chrome_net_log.h b/components/net_log/chrome_net_log.h index 30ccb9e..42c0c2a 100644 --- a/components/net_log/chrome_net_log.h +++ b/components/net_log/chrome_net_log.h
@@ -24,31 +24,27 @@ namespace net_log { -class NetLogFileWriter; +class NetExportFileWriter; -// ChromeNetLog is an implementation of NetLog that adds file loggers -// as its observers. +// ChromeNetLog is an implementation of NetLog that manages common observers +// (for --log-net-log, chrome://net-export/, tracing), as well as acting as the +// entry point for other consumers. class ChromeNetLog : public net::NetLog { public: - // The parameters to the constructor are only used for command-line based - // NetLog writing (which starts immediately after construction). - // - // TODO(eroman): This would be clearer as a separate method to configure and - // start this logging mode. - // - // The log is saved to |log_file|. - // |log_file_mode| is the mode used to log in |log_file|. - // If |log_file| is empty, only a temporary log is created, and - // |log_file_mode| is not used. - ChromeNetLog(const base::FilePath& log_file, - net::NetLogCaptureMode log_file_mode, - const base::CommandLine::StringType& command_line_string, - const std::string& channel_string); + ChromeNetLog(); ~ChromeNetLog() override; - // TODO(eroman): Rename this to something clearer. Perhaps - // |net_export_file_writer()|. - NetLogFileWriter* net_log_file_writer(); + // Starts streaming the NetLog events to a file on disk. This will continue + // until the application shuts down. + // * |log_file| - path to write the file. + // * |log_file_mode| - capture mode for event granularity. + void StartWritingToFile( + const base::FilePath& log_file, + net::NetLogCaptureMode log_file_mode, + const base::CommandLine::StringType& command_line_string, + const std::string& channel_string); + + NetExportFileWriter* net_export_file_writer(); // Returns a Value containing constants needed to load a log file. // Safe to call on any thread. @@ -58,7 +54,7 @@ private: std::unique_ptr<net::WriteToFileNetLogObserver> write_to_file_observer_; - std::unique_ptr<NetLogFileWriter> net_log_file_writer_; + std::unique_ptr<NetExportFileWriter> net_export_file_writer_; std::unique_ptr<net::TraceNetLogObserver> trace_net_log_observer_; DISALLOW_COPY_AND_ASSIGN(ChromeNetLog);
diff --git a/components/net_log/net_log_file_writer.cc b/components/net_log/net_export_file_writer.cc similarity index 85% rename from components/net_log/net_log_file_writer.cc rename to components/net_log/net_export_file_writer.cc index a1907ea..07765ee 100644 --- a/components/net_log/net_log_file_writer.cc +++ b/components/net_log/net_export_file_writer.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 "components/net_log/net_log_file_writer.h" +#include "components/net_log/net_export_file_writer.h" #include <set> #include <utility> @@ -43,10 +43,10 @@ const base::FilePath::CharType kOldLogRelativePath[] = FILE_PATH_LITERAL("chrome-net-export-log.json"); -// Contains file-related initialization tasks for NetLogFileWriter. -NetLogFileWriter::DefaultLogPathResults SetUpDefaultLogPath( - const NetLogFileWriter::DirectoryGetter& default_log_base_dir_getter) { - NetLogFileWriter::DefaultLogPathResults results; +// Contains file-related initialization tasks for NetExportFileWriter. +NetExportFileWriter::DefaultLogPathResults SetUpDefaultLogPath( + const NetExportFileWriter::DirectoryGetter& default_log_base_dir_getter) { + NetExportFileWriter::DefaultLogPathResults results; results.default_log_path_success = false; results.log_exists = false; @@ -70,7 +70,7 @@ // Generates net log entries for ongoing events from |context_getters| and // adds them to |observer|. void CreateNetLogEntriesForActiveObjects( - const NetLogFileWriter::URLRequestContextGetterList& context_getters, + const NetExportFileWriter::URLRequestContextGetterList& context_getters, net::NetLog::ThreadSafeObserver* observer) { std::set<net::URLRequestContext*> contexts; for (const auto& getter : context_getters) { @@ -109,7 +109,7 @@ } // namespace -NetLogFileWriter::NetLogFileWriter(ChromeNetLog* chrome_net_log) +NetExportFileWriter::NetExportFileWriter(ChromeNetLog* chrome_net_log) : state_(STATE_UNINITIALIZED), log_exists_(false), log_capture_mode_known_(false), @@ -118,22 +118,22 @@ default_log_base_dir_getter_(base::Bind(&base::GetTempDir)), weak_ptr_factory_(this) {} -NetLogFileWriter::~NetLogFileWriter() { +NetExportFileWriter::~NetExportFileWriter() { if (file_net_log_observer_) file_net_log_observer_->StopObserving(nullptr, base::Bind([] {})); } -void NetLogFileWriter::AddObserver(StateObserver* observer) { +void NetExportFileWriter::AddObserver(StateObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); state_observer_list_.AddObserver(observer); } -void NetLogFileWriter::RemoveObserver(StateObserver* observer) { +void NetExportFileWriter::RemoveObserver(StateObserver* observer) { DCHECK(thread_checker_.CalledOnValidThread()); state_observer_list_.RemoveObserver(observer); } -void NetLogFileWriter::Initialize( +void NetExportFileWriter::Initialize( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> net_task_runner) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -157,11 +157,11 @@ base::PostTaskAndReplyWithResult( file_task_runner_.get(), FROM_HERE, base::Bind(&SetUpDefaultLogPath, default_log_base_dir_getter_), - base::Bind(&NetLogFileWriter::SetStateAfterSetUpDefaultLogPath, + base::Bind(&NetExportFileWriter::SetStateAfterSetUpDefaultLogPath, weak_ptr_factory_.GetWeakPtr())); } -void NetLogFileWriter::StartNetLog( +void NetExportFileWriter::StartNetLog( const base::FilePath& log_path, net::NetLogCaptureMode capture_mode, const base::CommandLine::StringType& command_line_string, @@ -193,11 +193,11 @@ base::Bind(&CreateNetLogEntriesForActiveObjects, context_getters, base::Unretained(file_net_log_observer_.get())), base::Bind( - &NetLogFileWriter::StartNetLogAfterCreateEntriesForActiveObjects, + &NetExportFileWriter::StartNetLogAfterCreateEntriesForActiveObjects, weak_ptr_factory_.GetWeakPtr(), capture_mode)); } -void NetLogFileWriter::StartNetLogAfterCreateEntriesForActiveObjects( +void NetExportFileWriter::StartNetLogAfterCreateEntriesForActiveObjects( net::NetLogCaptureMode capture_mode) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(STATE_STARTING_LOG, state_); @@ -212,7 +212,7 @@ file_net_log_observer_->StartObserving(chrome_net_log_, capture_mode); } -void NetLogFileWriter::StopNetLog( +void NetExportFileWriter::StopNetLog( std::unique_ptr<base::DictionaryValue> polled_data, scoped_refptr<net::URLRequestContextGetter> context_getter) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -229,14 +229,14 @@ base::PostTaskAndReplyWithResult( net_task_runner_.get(), FROM_HERE, base::Bind(&AddNetInfo, context_getter, base::Passed(&polled_data)), - base::Bind(&NetLogFileWriter::StopNetLogAfterAddNetInfo, + base::Bind(&NetExportFileWriter::StopNetLogAfterAddNetInfo, weak_ptr_factory_.GetWeakPtr())); } else { StopNetLogAfterAddNetInfo(std::move(polled_data)); } } -std::unique_ptr<base::DictionaryValue> NetLogFileWriter::GetState() const { +std::unique_ptr<base::DictionaryValue> NetExportFileWriter::GetState() const { DCHECK(thread_checker_.CalledOnValidThread()); auto dict = base::MakeUnique<base::DictionaryValue>(); @@ -273,7 +273,7 @@ return dict; } -void NetLogFileWriter::GetFilePathToCompletedLog( +void NetExportFileWriter::GetFilePathToCompletedLog( const FilePathCallback& path_callback) const { DCHECK(thread_checker_.CalledOnValidThread()); if (!(log_exists_ && state_ == STATE_NOT_LOGGING)) { @@ -290,7 +290,7 @@ base::Bind(&GetPathWithAllPermissions, log_path_), path_callback); } -std::string NetLogFileWriter::CaptureModeToString( +std::string NetExportFileWriter::CaptureModeToString( net::NetLogCaptureMode capture_mode) { if (capture_mode == net::NetLogCaptureMode::Default()) { return "STRIP_PRIVATE_DATA"; @@ -305,7 +305,7 @@ } } -net::NetLogCaptureMode NetLogFileWriter::CaptureModeFromString( +net::NetLogCaptureMode NetExportFileWriter::CaptureModeFromString( const std::string& capture_mode_string) { if (capture_mode_string == "STRIP_PRIVATE_DATA") { return net::NetLogCaptureMode::Default(); @@ -319,12 +319,12 @@ } } -void NetLogFileWriter::SetDefaultLogBaseDirectoryGetterForTest( +void NetExportFileWriter::SetDefaultLogBaseDirectoryGetterForTest( const DirectoryGetter& getter) { default_log_base_dir_getter_ = getter; } -void NetLogFileWriter::NotifyStateObservers() { +void NetExportFileWriter::NotifyStateObservers() { DCHECK(thread_checker_.CalledOnValidThread()); std::unique_ptr<base::DictionaryValue> state = GetState(); for (StateObserver& observer : state_observer_list_) { @@ -332,14 +332,14 @@ } } -void NetLogFileWriter::NotifyStateObserversAsync() { +void NetExportFileWriter::NotifyStateObserversAsync() { DCHECK(thread_checker_.CalledOnValidThread()); base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&NetLogFileWriter::NotifyStateObservers, + FROM_HERE, base::Bind(&NetExportFileWriter::NotifyStateObservers, weak_ptr_factory_.GetWeakPtr())); } -void NetLogFileWriter::SetStateAfterSetUpDefaultLogPath( +void NetExportFileWriter::SetStateAfterSetUpDefaultLogPath( const DefaultLogPathResults& set_up_default_log_path_results) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(STATE_INITIALIZING, state_); @@ -355,18 +355,18 @@ NotifyStateObservers(); } -void NetLogFileWriter::StopNetLogAfterAddNetInfo( +void NetExportFileWriter::StopNetLogAfterAddNetInfo( std::unique_ptr<base::DictionaryValue> polled_data) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_EQ(STATE_STOPPING_LOG, state_); file_net_log_observer_->StopObserving( std::move(polled_data), - base::Bind(&NetLogFileWriter::ResetObserverThenSetStateNotLogging, + base::Bind(&NetExportFileWriter::ResetObserverThenSetStateNotLogging, weak_ptr_factory_.GetWeakPtr())); } -void NetLogFileWriter::ResetObserverThenSetStateNotLogging() { +void NetExportFileWriter::ResetObserverThenSetStateNotLogging() { DCHECK(thread_checker_.CalledOnValidThread()); file_net_log_observer_.reset(); state_ = STATE_NOT_LOGGING;
diff --git a/components/net_log/net_log_file_writer.h b/components/net_log/net_export_file_writer.h similarity index 80% rename from components/net_log/net_log_file_writer.h rename to components/net_log/net_export_file_writer.h index 49899c3..73074826 100644 --- a/components/net_log/net_log_file_writer.h +++ b/components/net_log/net_export_file_writer.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 COMPONENTS_NET_LOG_NET_LOG_FILE_WRITER_H_ -#define COMPONENTS_NET_LOG_NET_LOG_FILE_WRITER_H_ +#ifndef COMPONENTS_NET_LOG_NET_EXPORT_FILE_WRITER_H_ +#define COMPONENTS_NET_LOG_NET_EXPORT_FILE_WRITER_H_ #include <memory> #include <string> @@ -22,18 +22,18 @@ namespace base { class DictionaryValue; class SingleThreadTaskRunner; -} +} // namespace base namespace net { class FileNetLogObserver; class URLRequestContextGetter; -} +} // namespace net namespace net_log { class ChromeNetLog; -// NetLogFileWriter is used exclusively as a support class for net-export. +// NetExportFileWriter is used exclusively as a support class for net-export. // It's a singleton that acts as the interface to all NetExportMessageHandlers // which can tell it to start or stop logging in response to user actions from // net-export UIs. Because it's a singleton, the logging state can be shared @@ -42,21 +42,21 @@ // to the ChromeNetLog. This class is used by the iOS and non-iOS // implementations of net-export. // -// NetLogFileWriter maintains the current logging state using the members +// NetExportFileWriter maintains the current logging state using the members // |state_|, |log_exists_|, |log_capture_mode_known_|, |log_capture_mode_|. // Its three main commands are Initialize(), StartNetLog(), and StopNetLog(). -// These are the only functions that may cause NetLogFileWriter to change state. -// Initialize() must be called before NetLogFileWriter can process any other -// commands. A portion of the initialization needs to run on the +// These are the only functions that may cause NetExportFileWriter to change +// state. Initialize() must be called before NetExportFileWriter can process any +// other commands. A portion of the initialization needs to run on the // |file_task_runner_|. // // This class is created and destroyed on the UI thread, and all public entry // points are to be called on the UI thread. Internally, the class may run some // code on the |file_task_runner_| and |net_task_runner_|. -class NetLogFileWriter { +class NetExportFileWriter { public: // The observer interface to be implemented by code that wishes to be notified - // of NetLogFileWriter's state changes. + // of NetExportFileWriter's state changes. class StateObserver { public: virtual void OnNewState(const base::DictionaryValue& state) = 0; @@ -75,10 +75,10 @@ using URLRequestContextGetterList = std::vector<scoped_refptr<net::URLRequestContextGetter>>; - ~NetLogFileWriter(); + ~NetExportFileWriter(); // Attaches a StateObserver. |observer| will be notified of state changes to - // NetLogFileWriter. State changes may occur in response to Initiailze(), + // NetExportFileWriter. State changes may occur in response to Initiailze(), // StartNetLog(), or StopNetLog(). StateObserver::OnNewState() will be called // asynchronously relative to the command that caused the state change. // |observer| must remain alive until RemoveObserver() is called. @@ -87,16 +87,16 @@ // Detaches a StateObserver. void RemoveObserver(StateObserver* observer); - // Initializes NetLogFileWriter if not initialized. + // Initializes NetExportFileWriter if not initialized. // - // Also sets the task runners used by NetLogFileWriter for doing file I/O and - // network I/O respectively. The task runners must not be changed once set. - // However, calling this function again with the same parameters is OK. + // Also sets the task runners used by NetExportFileWriter for doing file I/O + // and network I/O respectively. The task runners must not be changed once + // set. However, calling this function again with the same parameters is OK. void Initialize(scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, scoped_refptr<base::SingleThreadTaskRunner> net_task_runner); // Starts collecting NetLog data into the file at |log_path|. If |log_path| is - // empty, the default log path is used. If NetLogFileWriter is already + // empty, the default log path is used. If NetExportFileWriter is already // logging, this is a no-op and |capture_mode| is ignored. // // |context_getters| is an optional list of URLRequestContextGetters used only @@ -110,7 +110,7 @@ const URLRequestContextGetterList& context_getters); // Stops collecting NetLog data into the file. It is a no-op if - // NetLogFileWriter is currently not logging. + // NetExportFileWriter is currently not logging. // // |polled_data| is a JSON dictionary that will be appended to the end of the // log; it's for adding additional info to the log that aren't events. @@ -123,15 +123,15 @@ void StopNetLog(std::unique_ptr<base::DictionaryValue> polled_data, scoped_refptr<net::URLRequestContextGetter> context_getter); - // Creates a DictionaryValue summary of the state of the NetLogFileWriter + // Creates a DictionaryValue summary of the state of the NetExportFileWriter std::unique_ptr<base::DictionaryValue> GetState() const; // Gets the log filepath. |path_callback| will be used to notify the caller // when the filepath is retrieved. |path_callback| will be executed with an // empty filepath if any of the following occurs: - // (1) The NetLogFileWriter is not initialized. + // (1) The NetExportFileWriter is not initialized. // (2) The log file does not exist. - // (3) The NetLogFileWriter is currently logging. + // (3) The NetExportFileWriter is currently logging. // (4) The log file's permissions could not be set to all. // // |path_callback| will be executed at the end of GetFilePathToCompletedLog() @@ -149,15 +149,15 @@ void SetDefaultLogBaseDirectoryGetterForTest(const DirectoryGetter& getter); protected: - // Constructs a NetLogFileWriter. Only one instance is created in browser + // Constructs a NetExportFileWriter. Only one instance is created in browser // process. - explicit NetLogFileWriter(ChromeNetLog* chrome_net_log); + explicit NetExportFileWriter(ChromeNetLog* chrome_net_log); private: friend class ChromeNetLog; - friend class NetLogFileWriterTest; + friend class NetExportFileWriterTest; - // The possible logging states of NetLogFileWriter. + // The possible logging states of NetExportFileWriter. enum State { STATE_UNINITIALIZED, // Currently in the process of initializing. @@ -177,9 +177,9 @@ // Posts NotifyStateObservers() to the current thread. void NotifyStateObserversAsync(); - // Called internally by Initialize(). Will initialize NetLogFileWriter's state - // variables after the default log directory is set up and the default log - // path is determined on the |file_task_runner_|. + // Called internally by Initialize(). Will initialize NetExportFileWriter's + // state variables after the default log directory is set up and the default + // log path is determined on the |file_task_runner_|. void SetStateAfterSetUpDefaultLogPath( const DefaultLogPathResults& set_up_default_log_path_results); @@ -209,7 +209,7 @@ scoped_refptr<base::SingleThreadTaskRunner> file_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> net_task_runner_; - State state_; // Current logging state of NetLogFileWriter. + State state_; // Current logging state of NetExportFileWriter. bool log_exists_; // Whether or not a log file exists on disk. bool log_capture_mode_known_; @@ -232,9 +232,9 @@ // during initialization. This getter is initialized to base::GetTempDir(). DirectoryGetter default_log_base_dir_getter_; - base::WeakPtrFactory<NetLogFileWriter> weak_ptr_factory_; + base::WeakPtrFactory<NetExportFileWriter> weak_ptr_factory_; - DISALLOW_COPY_AND_ASSIGN(NetLogFileWriter); + DISALLOW_COPY_AND_ASSIGN(NetExportFileWriter); }; } // namespace net_log
diff --git a/components/net_log/net_log_file_writer_unittest.cc b/components/net_log/net_export_file_writer_unittest.cc similarity index 82% rename from components/net_log/net_log_file_writer_unittest.cc rename to components/net_log/net_export_file_writer_unittest.cc index 8e42583..17f3b4b 100644 --- a/components/net_log/net_log_file_writer_unittest.cc +++ b/components/net_log/net_export_file_writer_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 "components/net_log/net_log_file_writer.h" +#include "components/net_log/net_export_file_writer.h" #include <stdint.h> @@ -36,7 +36,7 @@ const char kChannelString[] = "SomeChannel"; -// Keep this in sync with kLogRelativePath defined in net_log_file_writer.cc. +// Keep this in sync with kLogRelativePath defined in net_export_file_writer.cc. base::FilePath::CharType kLogRelativePath[] = FILE_PATH_LITERAL("net-export/chrome-net-export-log.json"); @@ -55,7 +55,7 @@ namespace net_log { // Sets |path| to |path_to_return| and always returns true. This function is -// used to override NetLogFileWriter's usual getter for the default log base +// used to override NetExportFileWriter's usual getter for the default log base // directory. bool SetPathToGivenAndReturnTrue(const base::FilePath& path_to_return, base::FilePath* path) { @@ -63,7 +63,7 @@ return true; } -// Checks the "state" string of a NetLogFileWriter state. +// Checks the "state" string of a NetExportFileWriter state. WARN_UNUSED_RESULT ::testing::AssertionResult VerifyState( std::unique_ptr<base::DictionaryValue> state, const std::string& expected_state_string) { @@ -81,7 +81,7 @@ return ::testing::AssertionSuccess(); } -// Checks all fields of a NetLogFileWriter state except possibly the +// Checks all fields of a NetExportFileWriter state except possibly the // "captureMode" string; that field is only checked if // |expected_log_capture_mode_known| is true. WARN_UNUSED_RESULT ::testing::AssertionResult VerifyState( @@ -130,14 +130,14 @@ DCHECK(!log_path.empty()); if (!base::PathExists(log_path)) { - return ::testing::AssertionFailure() << log_path.value() - << " does not exist."; + return ::testing::AssertionFailure() + << log_path.value() << " does not exist."; } // Parse log file contents into a dictionary std::string log_string; if (!base::ReadFileToString(log_path, &log_string)) { - return ::testing::AssertionFailure() << log_path.value() - << " could not be read."; + return ::testing::AssertionFailure() + << log_path.value() << " could not be read."; } *root = base::DictionaryValue::From(base::JSONReader::Read(log_string)); if (!*root) { @@ -149,15 +149,15 @@ base::DictionaryValue* constants; if (!(*root)->GetDictionary("constants", &constants)) { root->reset(); - return ::testing::AssertionFailure() << log_path.value() - << " is missing constants."; + return ::testing::AssertionFailure() + << log_path.value() << " is missing constants."; } // Make sure the "events" section exists base::ListValue* events; if (!(*root)->GetList("events", &events)) { root->reset(); - return ::testing::AssertionFailure() << log_path.value() - << " is missing events list."; + return ::testing::AssertionFailure() + << log_path.value() << " is missing events list."; } return ::testing::AssertionSuccess(); } @@ -200,11 +200,11 @@ base::ThreadTaskRunnerHandle::Get(), std::move(context)); } -// An implementation of NetLogFileWriter::StateObserver that allows waiting +// An implementation of NetExportFileWriter::StateObserver that allows waiting // until it's notified of a new state. -class TestStateObserver : public NetLogFileWriter::StateObserver { +class TestStateObserver : public NetExportFileWriter::StateObserver { public: - // NetLogFileWriter::StateObserver implementation + // NetExportFileWriter::StateObserver implementation void OnNewState(const base::DictionaryValue& state) override { test_closure_.closure().Run(); result_state_ = state.CreateDeepCopy(); @@ -249,17 +249,13 @@ base::Callback<void(const base::FilePath&)> callback_; }; -class NetLogFileWriterTest : public ::testing::Test { +class NetExportFileWriterTest : public ::testing::Test { public: using URLRequestContextGetterList = std::vector<scoped_refptr<net::URLRequestContextGetter>>; - NetLogFileWriterTest() - : net_log_(base::FilePath(), - net::NetLogCaptureMode::Default(), - base::CommandLine::StringType(), - kChannelString), - net_log_file_writer_(&net_log_), + NetExportFileWriterTest() + : file_writer_(&net_log_), file_thread_("NetLogFileWriter file thread"), net_thread_("NetLogFileWriter net thread") {} @@ -267,9 +263,9 @@ void SetUp() override { ASSERT_TRUE(log_temp_dir_.CreateUniqueTempDir()); - // Override |net_log_file_writer_|'s default-log-base-directory-getter to + // Override |file_writer_|'s default-log-base-directory-getter to // a getter that returns the temp dir created for the test. - net_log_file_writer_.SetDefaultLogBaseDirectoryGetterForTest( + file_writer_.SetDefaultLogBaseDirectoryGetterForTest( base::Bind(&SetPathToGivenAndReturnTrue, log_temp_dir_.GetPath())); default_log_path_ = log_temp_dir_.GetPath().Append(kLogRelativePath); @@ -277,29 +273,29 @@ ASSERT_TRUE(file_thread_.Start()); ASSERT_TRUE(net_thread_.Start()); - net_log_file_writer_.AddObserver(&test_state_observer_); + file_writer_.AddObserver(&test_state_observer_); - ASSERT_TRUE(VerifyState(net_log_file_writer_.GetState(), - kStateUninitializedString, false, false, "")); + ASSERT_TRUE(VerifyState(file_writer_.GetState(), kStateUninitializedString, + false, false, "")); } // ::testing::Test implementation void TearDown() override { - net_log_file_writer_.RemoveObserver(&test_state_observer_); + file_writer_.RemoveObserver(&test_state_observer_); ASSERT_TRUE(log_temp_dir_.Delete()); } base::FilePath FileWriterGetFilePathToCompletedLog() { TestFilePathCallback test_callback; - net_log_file_writer_.GetFilePathToCompletedLog(test_callback.callback()); + file_writer_.GetFilePathToCompletedLog(test_callback.callback()); return test_callback.WaitForResult(); } WARN_UNUSED_RESULT ::testing::AssertionResult InitializeThenVerifyNewState( bool expected_initialize_success, bool expected_log_exists) { - net_log_file_writer_.Initialize(file_thread_.task_runner(), - net_thread_.task_runner()); + file_writer_.Initialize(file_thread_.task_runner(), + net_thread_.task_runner()); std::unique_ptr<base::DictionaryValue> state = test_state_observer_.WaitForNewState(); ::testing::AssertionResult result = @@ -312,10 +308,11 @@ } state = test_state_observer_.WaitForNewState(); - result = VerifyState(std::move(state), expected_initialize_success - ? kStateNotLoggingString - : kStateUninitializedString, - expected_log_exists, false, ""); + result = + VerifyState(std::move(state), + expected_initialize_success ? kStateNotLoggingString + : kStateUninitializedString, + expected_log_exists, false, ""); if (!result) { return ::testing::AssertionFailure() << "Second state after Initialize() does not match expected:" @@ -326,16 +323,16 @@ return ::testing::AssertionSuccess(); } - // If |custom_log_path| is empty path, |net_log_file_writer_| will use its + // If |custom_log_path| is empty path, |file_writer_| will use its // default log path, which is cached in |default_log_path_|. WARN_UNUSED_RESULT::testing::AssertionResult StartThenVerifyNewState( const base::FilePath& custom_log_path, net::NetLogCaptureMode capture_mode, const std::string& expected_capture_mode_string, const URLRequestContextGetterList& context_getters) { - net_log_file_writer_.StartNetLog(custom_log_path, capture_mode, - base::CommandLine::StringType(), - kChannelString, context_getters); + file_writer_.StartNetLog(custom_log_path, capture_mode, + base::CommandLine::StringType(), kChannelString, + context_getters); std::unique_ptr<base::DictionaryValue> state = test_state_observer_.WaitForNewState(); ::testing::AssertionResult result = @@ -375,7 +372,7 @@ std::unique_ptr<base::DictionaryValue> polled_data, scoped_refptr<net::URLRequestContextGetter> context_getter, const std::string& expected_capture_mode_string) { - net_log_file_writer_.StopNetLog(std::move(polled_data), context_getter); + file_writer_.StopNetLog(std::move(polled_data), context_getter); std::unique_ptr<base::DictionaryValue> state = test_state_observer_.WaitForNewState(); ::testing::AssertionResult result = @@ -425,13 +422,13 @@ protected: ChromeNetLog net_log_; - // |net_log_file_writer_| is initialized after |net_log_| so that it can stop + // |file_writer_| is initialized after |net_log_| so that it can stop // obvserving on destruction. - NetLogFileWriter net_log_file_writer_; + NetExportFileWriter file_writer_; base::ScopedTempDir log_temp_dir_; - // The default log path that |net_log_file_writer_| will use is cached here. + // The default log path that |file_writer_| will use is cached here. base::FilePath default_log_path_; base::Thread file_thread_; @@ -444,28 +441,29 @@ base::MessageLoop message_loop_; }; -TEST_F(NetLogFileWriterTest, InitFail) { - // Override net_log_file_writer_'s default log base directory getter to always +TEST_F(NetExportFileWriterTest, InitFail) { + // Override file_writer_'s default log base directory getter to always // fail. - net_log_file_writer_.SetDefaultLogBaseDirectoryGetterForTest( + file_writer_.SetDefaultLogBaseDirectoryGetterForTest( base::Bind([](base::FilePath* path) -> bool { return false; })); // Initialization should fail due to the override. ASSERT_TRUE(InitializeThenVerifyNewState(false, false)); - // NetLogFileWriter::GetFilePath() should return empty path if uninitialized. + // NetExportFileWriter::GetFilePath() should return empty path if + // uninitialized. EXPECT_TRUE(FileWriterGetFilePathToCompletedLog().empty()); } -TEST_F(NetLogFileWriterTest, InitWithoutExistingLog) { +TEST_F(NetExportFileWriterTest, InitWithoutExistingLog) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); - // NetLogFileWriter::GetFilePathToCompletedLog() should return empty path when - // no log file exists. + // NetExportFileWriter::GetFilePathToCompletedLog() should return empty path + // when no log file exists. EXPECT_TRUE(FileWriterGetFilePathToCompletedLog().empty()); } -TEST_F(NetLogFileWriterTest, InitWithExistingLog) { +TEST_F(NetExportFileWriterTest, InitWithExistingLog) { // Create and close an empty log file to simulate existence of a previous log // file. ASSERT_TRUE( @@ -479,7 +477,7 @@ EXPECT_EQ(default_log_path_, FileWriterGetFilePathToCompletedLog()); } -TEST_F(NetLogFileWriterTest, StartAndStopWithAllCaptureModes) { +TEST_F(NetExportFileWriterTest, StartAndStopWithAllCaptureModes) { const net::NetLogCaptureMode capture_modes[3] = { net::NetLogCaptureMode::Default(), net::NetLogCaptureMode::IncludeCookiesAndCredentials(), @@ -491,7 +489,7 @@ ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); - // For each capture mode, start and stop |net_log_file_writer_| in that mode. + // For each capture mode, start and stop |file_writer_| in that mode. for (int i = 0; i < 3; ++i) { // StartNetLog(), should result in state change. ASSERT_TRUE(StartThenVerifyNewState(base::FilePath(), capture_modes[i], @@ -501,17 +499,15 @@ // Calling StartNetLog() again should be a no-op. Try doing StartNetLog() // with various capture modes; they should all be ignored and result in no // state change. - net_log_file_writer_.StartNetLog( - base::FilePath(), capture_modes[i], base::CommandLine::StringType(), - kChannelString, URLRequestContextGetterList()); - net_log_file_writer_.StartNetLog( - base::FilePath(), capture_modes[(i + 1) % 3], - base::CommandLine::StringType(), kChannelString, - URLRequestContextGetterList()); - net_log_file_writer_.StartNetLog( - base::FilePath(), capture_modes[(i + 2) % 3], - base::CommandLine::StringType(), kChannelString, - URLRequestContextGetterList()); + file_writer_.StartNetLog(base::FilePath(), capture_modes[i], + base::CommandLine::StringType(), kChannelString, + URLRequestContextGetterList()); + file_writer_.StartNetLog(base::FilePath(), capture_modes[(i + 1) % 3], + base::CommandLine::StringType(), kChannelString, + URLRequestContextGetterList()); + file_writer_.StartNetLog(base::FilePath(), capture_modes[(i + 2) % 3], + base::CommandLine::StringType(), kChannelString, + URLRequestContextGetterList()); // StopNetLog(), should result in state change. The capture mode should // match that of the first StartNetLog() call (called by @@ -520,11 +516,11 @@ base::FilePath(), nullptr, nullptr, capture_mode_strings[i])); // Stopping a second time should be a no-op. - net_log_file_writer_.StopNetLog(nullptr, nullptr); + file_writer_.StopNetLog(nullptr, nullptr); } // Start and stop one more time just to make sure the last StopNetLog() call - // was properly ignored and left |net_log_file_writer_| in a valid state. + // was properly ignored and left |file_writer_| in a valid state. ASSERT_TRUE(StartThenVerifyNewState(base::FilePath(), capture_modes[0], capture_mode_strings[0], URLRequestContextGetterList())); @@ -535,7 +531,7 @@ // Verify the file sizes after two consecutive starts/stops are the same (even // if some junk data is added in between). -TEST_F(NetLogFileWriterTest, StartClearsFile) { +TEST_F(NetExportFileWriterTest, StartClearsFile) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); ASSERT_TRUE(StartThenVerifyNewState( @@ -574,7 +570,7 @@ // Adds an event to the log file, then checks that the file is larger than // the file created without that event. -TEST_F(NetLogFileWriterTest, AddEvent) { +TEST_F(NetExportFileWriterTest, AddEvent) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); ASSERT_TRUE(StartThenVerifyNewState( @@ -605,7 +601,7 @@ // Using a custom path to make sure logging can still occur when the path has // changed. -TEST_F(NetLogFileWriterTest, AddEventCustomPath) { +TEST_F(NetExportFileWriterTest, AddEventCustomPath) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); base::FilePath::CharType kCustomRelativePath[] = @@ -641,7 +637,7 @@ EXPECT_GE(new_stop_file_size, stop_file_size); } -TEST_F(NetLogFileWriterTest, StopWithPolledDataAndContextGetter) { +TEST_F(NetExportFileWriterTest, StopWithPolledDataAndContextGetter) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); // Create dummy polled data @@ -656,8 +652,9 @@ const int kDummyQuicParam = 75; net::TestClosure init_done; net_thread_.task_runner()->PostTaskAndReply( - FROM_HERE, base::Bind(&SetUpTestContextGetterWithQuicTimeoutInfo, - &net_log_, kDummyQuicParam, &context_getter), + FROM_HERE, + base::Bind(&SetUpTestContextGetterWithQuicTimeoutInfo, &net_log_, + kDummyQuicParam, &context_getter), init_done.closure()); init_done.WaitForResult(); @@ -692,7 +689,7 @@ EXPECT_EQ(kDummyQuicParam, timeout); } -TEST_F(NetLogFileWriterTest, StartWithContextGetters) { +TEST_F(NetExportFileWriterTest, StartWithContextGetters) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); // Create test context getter and request on |net_thread_| and wait for it to @@ -739,20 +736,19 @@ net_thread_.task_runner()->DeleteSoon(FROM_HERE, request.release()); } -TEST_F(NetLogFileWriterTest, ReceiveStartWhileInitializing) { - // Trigger initialization of |net_log_file_writer_|. - net_log_file_writer_.Initialize(file_thread_.task_runner(), - net_thread_.task_runner()); +TEST_F(NetExportFileWriterTest, ReceiveStartWhileInitializing) { + // Trigger initialization of |file_writer_|. + file_writer_.Initialize(file_thread_.task_runner(), + net_thread_.task_runner()); - // Before running the main message loop, tell |net_log_file_writer_| to start + // Before running the main message loop, tell |file_writer_| to start // logging. Not running the main message loop prevents the initialization // process from completing, so this ensures that StartNetLog() is received - // before |net_log_file_writer_| finishes initialization, which means this + // before |file_writer_| finishes initialization, which means this // should be a no-op. - net_log_file_writer_.StartNetLog( - base::FilePath(), net::NetLogCaptureMode::Default(), - base::CommandLine::StringType(), kChannelString, - URLRequestContextGetterList()); + file_writer_.StartNetLog(base::FilePath(), net::NetLogCaptureMode::Default(), + base::CommandLine::StringType(), kChannelString, + URLRequestContextGetterList()); // Now run the main message loop. Make sure StartNetLog() was ignored by // checking that the next two states are "initializing" followed by @@ -765,26 +761,25 @@ VerifyState(std::move(state), kStateNotLoggingString, false, false, "")); } -TEST_F(NetLogFileWriterTest, ReceiveStartWhileStoppingLog) { +TEST_F(NetExportFileWriterTest, ReceiveStartWhileStoppingLog) { ASSERT_TRUE(InitializeThenVerifyNewState(true, false)); - // Call StartNetLog() on |net_log_file_writer_| and wait for the state change. + // Call StartNetLog() on |file_writer_| and wait for the state change. ASSERT_TRUE(StartThenVerifyNewState( base::FilePath(), net::NetLogCaptureMode::IncludeSocketBytes(), kCaptureModeIncludeSocketBytesString, URLRequestContextGetterList())); - // Tell |net_log_file_writer_| to stop logging. - net_log_file_writer_.StopNetLog(nullptr, nullptr); + // Tell |file_writer_| to stop logging. + file_writer_.StopNetLog(nullptr, nullptr); - // Before running the main message loop, tell |net_log_file_writer_| to start + // Before running the main message loop, tell |file_writer_| to start // logging. Not running the main message loop prevents the stopping process // from completing, so this ensures StartNetLog() is received before - // |net_log_file_writer_| finishes stopping, which means this should be a + // |file_writer_| finishes stopping, which means this should be a // no-op. - net_log_file_writer_.StartNetLog( - base::FilePath(), net::NetLogCaptureMode::Default(), - base::CommandLine::StringType(), kChannelString, - URLRequestContextGetterList()); + file_writer_.StartNetLog(base::FilePath(), net::NetLogCaptureMode::Default(), + base::CommandLine::StringType(), kChannelString, + URLRequestContextGetterList()); // Now run the main message loop. Make sure the last StartNetLog() was // ignored by checking that the next two states are "stopping-log" followed by
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index 6b0dc65..e2a2914 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -4,7 +4,9 @@ #include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h" +#include <map> #include <memory> +#include <string> #include <utility> #include <vector> @@ -20,6 +22,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" #include "base/test/histogram_tester.h" #include "base/test/simple_test_clock.h" #include "base/threading/thread_task_runner_handle.h" @@ -52,8 +55,6 @@ #include "components/signin/core/browser/fake_signin_manager.h" #include "components/variations/variations_params_manager.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/test_url_fetcher_factory.h" -#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gmock_mutant.h" #include "testing/gtest/include/gtest/gtest.h" @@ -101,20 +102,11 @@ const int kMaxExcludedDismissedIds = 100; const base::Time::Exploded kDefaultCreationTime = {2015, 11, 4, 25, 13, 46, 45}; -const char kTestContentSuggestionsServerEndpoint[] = - "https://alpha-chromecontentsuggestions-pa.sandbox.googleapis.com/v1/" - "suggestions/fetch"; -const char kAPIKey[] = "fakeAPIkey"; -const char kTestContentSuggestionsServerWithAPIKey[] = - "https://alpha-chromecontentsuggestions-pa.sandbox.googleapis.com/v1/" - "suggestions/fetch?key=fakeAPIkey"; const char kSuggestionUrl[] = "http://localhost/foobar"; const char kSuggestionTitle[] = "Title"; const char kSuggestionText[] = "Suggestion"; -const char kSuggestionSalientImage[] = "http://localhost/salient_image"; const char kSuggestionPublisherName[] = "Foo News"; -const char kSuggestionAmpUrl[] = "http://localhost/amp"; const char kSuggestionUrl2[] = "http://foo.com/bar"; @@ -137,6 +129,7 @@ return base::Time::Now() + base::TimeDelta::FromHours(1); } +// TODO(vitaliii): Remove this and use RemoteSuggestionBuilder instead. std::unique_ptr<RemoteSuggestion> CreateTestRemoteSuggestion( const std::string& url) { SnippetProto snippet_proto; @@ -154,54 +147,6 @@ return RemoteSuggestion::CreateFromProto(snippet_proto); } -std::string GetCategoryJson(const std::vector<std::string>& suggestions, - int remote_category_id, - const std::string& category_title) { - return base::StringPrintf( - " {\n" - " \"id\": %d,\n" - " \"localizedTitle\": \"%s\",\n" - " \"suggestions\": [%s]\n" - " }\n", - remote_category_id, category_title.c_str(), - base::JoinString(suggestions, ", ").c_str()); -} - -class MultiCategoryJsonBuilder { - public: - MultiCategoryJsonBuilder() {} - - MultiCategoryJsonBuilder& AddCategoryWithCustomTitle( - const std::vector<std::string>& suggestions, - int remote_category_id, - const std::string& category_title) { - category_json_.push_back( - GetCategoryJson(suggestions, remote_category_id, category_title)); - return *this; - } - - MultiCategoryJsonBuilder& AddCategory( - const std::vector<std::string>& suggestions, - int remote_category_id) { - return AddCategoryWithCustomTitle( - suggestions, remote_category_id, - "Title" + base::IntToString(remote_category_id)); - } - - std::string Build() { - return base::StringPrintf( - "{\n" - " \"categories\": [\n" - "%s\n" - " ]\n" - "}\n", - base::JoinString(category_json_, " ,\n").c_str()); - } - - private: - std::vector<std::string> category_json_; -}; - class RemoteSuggestionBuilder { public: RemoteSuggestionBuilder() = default; @@ -373,92 +318,6 @@ base::Optional<std::vector<RemoteSuggestionBuilder>> suggestion_builders_; }; -// TODO(vitaliii): Remove these convenience functions as they do not provide -// that much value and add additional redirections obscuring the code. -std::string GetTestJson(const std::vector<std::string>& suggestions, - const std::string& category_title) { - return MultiCategoryJsonBuilder() - .AddCategoryWithCustomTitle(suggestions, /*remote_category_id=*/1, - category_title) - .Build(); -} - -std::string GetTestJson(const std::vector<std::string>& suggestions) { - return GetTestJson(suggestions, kTestJsonDefaultCategoryTitle); -} - -std::string FormatTime(const base::Time& t) { - base::Time::Exploded x; - t.UTCExplode(&x); - return base::StringPrintf("%04d-%02d-%02dT%02d:%02d:%02dZ", x.year, x.month, - x.day_of_month, x.hour, x.minute, x.second); -} - -std::string GetSuggestionWithUrlAndTimesAndSource( - const std::vector<std::string>& ids, - const std::string& url, - const base::Time& creation_time, - const base::Time& expiry_time, - const std::string& publisher, - const std::string& amp_url, - double score) { - const std::string ids_string = base::JoinString(ids, "\",\n \""); - return base::StringPrintf( - "{\n" - " \"ids\": [\n" - " \"%s\"\n" - " ],\n" - " \"title\": \"%s\",\n" - " \"snippet\": \"%s\",\n" - " \"fullPageUrl\": \"%s\",\n" - " \"creationTime\": \"%s\",\n" - " \"expirationTime\": \"%s\",\n" - " \"attribution\": \"%s\",\n" - " \"imageUrl\": \"%s\",\n" - " \"ampUrl\": \"%s\",\n" - " \"score\": %f\n" - " }", - ids_string.c_str(), kSuggestionTitle, kSuggestionText, url.c_str(), - FormatTime(creation_time).c_str(), FormatTime(expiry_time).c_str(), - publisher.c_str(), kSuggestionSalientImage, amp_url.c_str(), score); -} - -std::string GetSuggestionWithSources(const std::string& source_url, - const std::string& publisher, - const std::string& amp_url) { - return GetSuggestionWithUrlAndTimesAndSource( - {source_url}, source_url, GetDefaultCreationTime(), - GetDefaultExpirationTime(), publisher, amp_url, /*score=*/1); -} - -std::string GetSuggestionWithSourcesAndScore(const std::string& source_url, - const std::string& publisher, - const std::string& amp_url, - double score) { - return GetSuggestionWithUrlAndTimesAndSource( - {source_url}, source_url, GetDefaultCreationTime(), - GetDefaultExpirationTime(), publisher, amp_url, score); -} - -std::string GetSuggestionWithUrlAndTimes( - const std::string& url, - const base::Time& content_creation_time, - const base::Time& expiry_time) { - return GetSuggestionWithUrlAndTimesAndSource( - {url}, url, content_creation_time, expiry_time, kSuggestionPublisherName, - kSuggestionAmpUrl, /*score=*/1); -} - -std::string GetSuggestionWithUrl(const std::string& url) { - return GetSuggestionWithUrlAndTimes(url, GetDefaultCreationTime(), - GetDefaultExpirationTime()); -} - -std::string GetSuggestion() { - return GetSuggestionWithUrlAndTimes(kSuggestionUrl, GetDefaultCreationTime(), - GetDefaultExpirationTime()); -} - using ServeImageCallback = base::Callback<void( const std::string&, base::Callback<void(const std::string&, @@ -493,33 +352,6 @@ return result; } -void ParseJson(const std::string& json, - const SuccessCallback& success_callback, - const ErrorCallback& error_callback) { - base::JSONReader json_reader; - std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); - if (value) { - success_callback.Run(std::move(value)); - } else { - error_callback.Run(json_reader.GetErrorMessage()); - } -} - -// Factory for FakeURLFetcher objects that always generate errors. -class FailingFakeURLFetcherFactory : public net::URLFetcherFactory { - public: - std::unique_ptr<net::URLFetcher> CreateURLFetcher( - int id, - const GURL& url, - net::URLFetcher::RequestType request_type, - net::URLFetcherDelegate* d, - net::NetworkTrafficAnnotationTag traffic_annotation) override { - return base::MakeUnique<net::FakeURLFetcher>( - url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND, - net::URLRequestStatus::FAILED); - } -}; - class MockImageFetcher : public ImageFetcher { public: MOCK_METHOD1(SetImageFetcherDelegate, void(ImageFetcherDelegate*)); @@ -606,17 +438,10 @@ class RemoteSuggestionsProviderImplTest : public ::testing::Test { public: RemoteSuggestionsProviderImplTest() - : params_manager_(ntp_snippets::kArticleSuggestionsFeature.name, - {{"content_suggestions_backend", - kTestContentSuggestionsServerEndpoint}}, - {ntp_snippets::kArticleSuggestionsFeature.name}), - fake_url_fetcher_factory_( - /*default_factory=*/&failing_url_fetcher_factory_), - test_url_(kTestContentSuggestionsServerWithAPIKey), - category_ranker_(base::MakeUnique<ConstantCategoryRanker>()), + : category_ranker_(base::MakeUnique<ConstantCategoryRanker>()), user_classifier_(/*pref_service=*/nullptr, base::MakeUnique<base::DefaultClock>()), - suggestions_fetcher_(nullptr), + mock_suggestions_fetcher_(nullptr), image_fetcher_(nullptr), scheduler_(base::MakeUnique<NiceMock<MockScheduler>>()), database_(nullptr) { @@ -636,41 +461,23 @@ // TODO(vitaliii): Rewrite this function to initialize a test class member // instead of creating a new provider. - std::unique_ptr<RemoteSuggestionsProviderImpl> MakeSuggestionsProvider( - bool use_mock_suggestions_fetcher, - bool set_empty_response) { + std::unique_ptr<RemoteSuggestionsProviderImpl> MakeSuggestionsProvider() { auto provider = MakeSuggestionsProviderWithoutInitialization( - use_mock_suggestions_fetcher, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - set_empty_response); + WaitForSuggestionsProviderInitialization(provider.get()); return provider; } - // TODO(vitaliii): Rewrite tests and always use mock suggestions fetcher. std::unique_ptr<RemoteSuggestionsProviderImpl> MakeSuggestionsProviderWithoutInitialization( - bool use_mock_suggestions_fetcher, bool use_mock_prefetched_pages_tracker) { scoped_refptr<base::SingleThreadTaskRunner> task_runner( base::ThreadTaskRunnerHandle::Get()); - scoped_refptr<net::TestURLRequestContextGetter> request_context_getter = - new net::TestURLRequestContextGetter(task_runner.get()); utils_.ResetSigninManager(); - std::unique_ptr<RemoteSuggestionsFetcher> suggestions_fetcher; - if (use_mock_suggestions_fetcher) { - suggestions_fetcher = - base::MakeUnique<StrictMock<MockRemoteSuggestionsFetcher>>(); - } else { - suggestions_fetcher = base::MakeUnique<RemoteSuggestionsFetcherImpl>( - utils_.fake_signin_manager(), /*token_service=*/nullptr, - std::move(request_context_getter), utils_.pref_service(), nullptr, - base::Bind(&ParseJson), - GetFetchEndpoint(version_info::Channel::STABLE), kAPIKey, - &user_classifier_); - } - suggestions_fetcher_ = suggestions_fetcher.get(); + auto mock_suggestions_fetcher = + base::MakeUnique<StrictMock<MockRemoteSuggestionsFetcher>>(); + mock_suggestions_fetcher_ = mock_suggestions_fetcher.get(); std::unique_ptr<PrefetchedPagesTracker> prefetched_pages_tracker; if (use_mock_prefetched_pages_tracker) { @@ -692,7 +499,7 @@ database_ = database.get(); return base::MakeUnique<RemoteSuggestionsProviderImpl>( observer_.get(), utils_.pref_service(), "fr", category_ranker_.get(), - scheduler_.get(), std::move(suggestions_fetcher), + scheduler_.get(), std::move(mock_suggestions_fetcher), std::move(image_fetcher), std::move(database), base::MakeUnique<RemoteSuggestionsStatusService>( utils_.fake_signin_manager(), utils_.pref_service(), std::string()), @@ -703,22 +510,14 @@ MakeSuggestionsProviderWithoutInitializationWithStrictScheduler() { scheduler_ = base::MakeUnique<StrictMock<MockScheduler>>(); return MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/false); } void WaitForSuggestionsProviderInitialization( - RemoteSuggestionsProviderImpl* provider, - bool set_empty_response) { + RemoteSuggestionsProviderImpl* provider) { EXPECT_EQ(RemoteSuggestionsProviderImpl::State::NOT_INITED, provider->state_); - // Add an initial fetch response, as the provider tries to fetch when there - // is nothing in the DB. - if (set_empty_response) { - SetUpFetchResponse(GetTestJson(std::vector<std::string>())); - } - // TODO(treib): Find a better way to wait for initialization to finish. base::RunLoop().RunUntilIdle(); EXPECT_NE(RemoteSuggestionsProviderImpl::State::NOT_INITED, @@ -726,13 +525,10 @@ } void ResetSuggestionsProvider( - std::unique_ptr<RemoteSuggestionsProviderImpl>* provider, - bool use_mock_suggestions_fetcher, - bool set_empty_response) { + std::unique_ptr<RemoteSuggestionsProviderImpl>* provider) { provider->reset(); observer_.reset(); - *provider = MakeSuggestionsProvider(use_mock_suggestions_fetcher, - set_empty_response); + *provider = MakeSuggestionsProvider(); } void SetCategoryRanker(std::unique_ptr<CategoryRanker> category_ranker) { @@ -760,10 +556,9 @@ } protected: - const GURL& test_url() { return test_url_; } FakeContentSuggestionsProviderObserver& observer() { return *observer_; } - RemoteSuggestionsFetcher* suggestions_fetcher() { - return suggestions_fetcher_; + StrictMock<MockRemoteSuggestionsFetcher>* mock_suggestions_fetcher() { + return mock_suggestions_fetcher_; } PrefetchedPagesTracker* prefetched_pages_tracker() { return prefetched_pages_tracker_; @@ -776,28 +571,13 @@ RemoteSuggestionsDatabase* database() { return database_; } MockScheduler* scheduler() { return scheduler_.get(); } - // Provide the json to be returned by the fake fetcher. - void SetUpFetchResponse(const std::string& json) { - fake_url_fetcher_factory_.SetFakeResponse(test_url_, json, net::HTTP_OK, - net::URLRequestStatus::SUCCESS); - } - - // Have the fake fetcher fail due to a HTTP error like a 404. - void SetUpHttpError() { - fake_url_fetcher_factory_.SetFakeResponse(test_url_, /*json=*/std::string(), - net::HTTP_NOT_FOUND, - net::URLRequestStatus::SUCCESS); - } - void FetchTheseSuggestions( RemoteSuggestionsProviderImpl* provider, bool interactive_request, Status status, base::Optional<std::vector<FetchedCategory>> fetched_categories) { - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)) + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) .RetiresOnSaturation(); provider->FetchSuggestions( @@ -814,10 +594,8 @@ FetchDoneCallback fetch_done_callback, Status status, base::Optional<std::vector<FetchedCategory>> fetched_categories) { - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)) + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) .RetiresOnSaturation(); EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) @@ -829,67 +607,37 @@ std::move(fetched_categories)); } - void LoadFromJSONString(RemoteSuggestionsProviderImpl* provider, - const std::string& json) { - SetUpFetchResponse(json); - provider->FetchSuggestions( - /*interactive_request=*/true, - RemoteSuggestionsProvider::FetchStatusCallback()); - base::RunLoop().RunUntilIdle(); - } - - void LoadMoreFromJSONString(RemoteSuggestionsProviderImpl* provider, - const Category& category, - const std::string& json, - const std::set<std::string>& known_ids, - FetchDoneCallback callback) { - SetUpFetchResponse(json); - EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) - .WillOnce(Return(true)) - .RetiresOnSaturation(); - provider->Fetch(category, known_ids, callback); - base::RunLoop().RunUntilIdle(); - } - void SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(bool value) { // params_manager supports only one // |SetVariationParamsWithFeatureAssociations| at a time, so we clear - // previous settings first and then set everything we need. + // previous settings first to make this explicit. params_manager_.ClearAllVariationParams(); params_manager_.SetVariationParamsWithFeatureAssociations( kArticleSuggestionsFeature.name, {{"order_new_remote_categories_based_on_articles_category", - value ? "true" : "false"}, - {"content_suggestions_backend", - kTestContentSuggestionsServerEndpoint}}, + value ? "true" : "false"}}, {kArticleSuggestionsFeature.name}); } void EnableKeepingPrefetchedContentSuggestions() { // params_manager supports only one // |SetVariationParamsWithFeatureAssociations| at a time, so we clear - // previous settings first and then set everything we need. + // previous settings first to make this explicit. params_manager_.ClearAllVariationParams(); params_manager_.SetVariationParamsWithFeatureAssociations( kKeepPrefetchedContentSuggestions.name, - {{"content_suggestions_backend", - kTestContentSuggestionsServerEndpoint}}, - {kArticleSuggestionsFeature.name, - kKeepPrefetchedContentSuggestions.name}); + /*param_values=*/std::map<std::string, std::string>(), + {kKeepPrefetchedContentSuggestions.name}); } private: variations::testing::VariationParamsManager params_manager_; test::RemoteSuggestionsTestUtils utils_; base::MessageLoop message_loop_; - FailingFakeURLFetcherFactory failing_url_fetcher_factory_; - // Instantiation of factory automatically sets itself as URLFetcher's factory. - net::FakeURLFetcherFactory fake_url_fetcher_factory_; - const GURL test_url_; std::unique_ptr<CategoryRanker> category_ranker_; UserClassifier user_classifier_; std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_; - RemoteSuggestionsFetcher* suggestions_fetcher_; + StrictMock<MockRemoteSuggestionsFetcher>* mock_suggestions_fetcher_; PrefetchedPagesTracker* prefetched_pages_tracker_; NiceMock<MockImageFetcher>* image_fetcher_; FakeImageDecoder image_decoder_; @@ -902,8 +650,7 @@ }; TEST_F(RemoteSuggestionsProviderImplTest, Full) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); // TODO(vitaliii): Inline the vector creation in FetchTheseSuggestions. std::vector<FetchedCategory> fetched_categories; @@ -943,8 +690,7 @@ // Don't send an initial response -- we want to test what happens without any // server status. - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); // The articles category should be there by default, and have a title. CategoryInfo info_before = provider->GetCategoryInfo(articles_category()); @@ -981,8 +727,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, MultipleCategories) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1050,8 +795,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ArticleCategoryInfo) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); CategoryInfo article_info = provider->GetCategoryInfo(articles_category()); EXPECT_THAT(article_info.additional_action(), Eq(ContentSuggestionsAdditionalAction::FETCH)); @@ -1059,8 +803,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ExperimentalCategoryInfo) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1116,8 +859,7 @@ EXPECT_CALL(*raw_mock_ranker, AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); } - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, Status(StatusCode::SUCCESS, "message"), std::move(fetched_categories)); @@ -1170,8 +912,7 @@ InsertCategoryAfterIfNecessary(Category::FromRemoteCategory(12), articles_category())); } - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, Status(StatusCode::SUCCESS, "message"), std::move(fetched_categories)); @@ -1194,16 +935,14 @@ EXPECT_CALL(*raw_mock_ranker, InsertCategoryBeforeIfNecessary(_, _)).Times(0); EXPECT_CALL(*raw_mock_ranker, AppendCategoryIfNecessary(Category::FromRemoteCategory(11))); - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, Status(StatusCode::SUCCESS, "message"), std::move(fetched_categories)); } TEST_F(RemoteSuggestionsProviderImplTest, PersistCategoryInfos) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1231,8 +970,7 @@ Category::FromRemoteCategory(kUnknownRemoteCategoryId)); // Recreate the provider to simulate a Chrome restart. - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/true, - /*set_empty_response=*/true); + ResetSuggestionsProvider(&provider); // The categories should have been restored. ASSERT_NE(observer().StatusForCategory(articles_category()), @@ -1258,8 +996,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, PersistRemoteCategoryOrder) { // We create a provider with a normal ranker to store the order. - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1286,9 +1023,7 @@ MockCategoryRanker* raw_mock_ranker = mock_ranker.get(); SetCategoryRanker(std::move(mock_ranker)); // Ensure that the order is not fetched. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)).Times(0); + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0); { // The order of categories is determined by the order in which they are // added. Thus, the latter is tested here. @@ -1304,13 +1039,11 @@ EXPECT_CALL(*raw_mock_ranker, AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); } - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/true, - /*set_empty_response=*/false); + ResetSuggestionsProvider(&provider); } TEST_F(RemoteSuggestionsProviderImplTest, PersistSuggestions) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1333,8 +1066,7 @@ ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); // Recreate the provider to simulate a Chrome restart. - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/true, - /*set_empty_response=*/true); + ResetSuggestionsProvider(&provider); // The suggestions in both categories should have been restored. EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), @@ -1344,8 +1076,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, DontNotifyIfNotAvailable) { // Get some suggestions into the database. - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( FetchedCategoryBuilder() @@ -1371,8 +1102,7 @@ pref_service()->SetBoolean(prefs::kEnableSnippets, false); // Recreate the provider to simulate a Chrome start. - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/true, - /*set_empty_response=*/true); + ResetSuggestionsProvider(&provider); ASSERT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED, Eq(provider->state_)); @@ -1384,8 +1114,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, Clear) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -1406,8 +1135,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ReplaceSuggestions) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::string first("http://first"); std::vector<FetchedCategory> fetched_categories; @@ -1439,8 +1167,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldResolveFetchedSuggestionThumbnail) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -1467,8 +1194,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ShouldFetchMore) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -1502,8 +1228,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldResolveFetchedMoreSuggestionThumbnail) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -1540,10 +1265,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldNotChangeSuggestionsInOtherSurfacesWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); // Fetch a suggestion. std::vector<FetchedCategory> fetched_categories; @@ -1557,11 +1280,9 @@ Status(StatusCode::SUCCESS, "message"), std::move(fetched_categories)); - ASSERT_THAT( - observer().SuggestionsForCategory(articles_category()), - ElementsAre(Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://old.com/")))); + ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), + ElementsAre(Property(&ContentSuggestion::id, + MakeArticleID("http://old.com/")))); // Now fetch more, but first prepare a response. fetched_categories.clear(); @@ -1586,11 +1307,9 @@ Status(StatusCode::SUCCESS, "message"), std::move(fetched_categories)); // Other surfaces should remain the same. - EXPECT_THAT( - observer().SuggestionsForCategory(articles_category()), - ElementsAre(Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://old.com/")))); + EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), + ElementsAre(Property(&ContentSuggestion::id, + MakeArticleID("http://old.com/")))); } // Imagine that we have surfaces A and B. The user fetches more in A. This @@ -1600,12 +1319,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldNotAffectFetchMoreInOtherSurfacesWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); // Fetch more on the surface A. std::vector<FetchedCategory> fetched_categories; @@ -1623,7 +1338,7 @@ Eq("http://fetched-more.com/")); }); RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)) + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) .RetiresOnSaturation(); EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) @@ -1654,7 +1369,7 @@ }); // The provider should not ask the fetcher to exclude the suggestion fetched // more on A. - EXPECT_CALL(*mock_fetcher, + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(Field(&RequestParams::excluded_ids, Not(Contains("http://fetched-more.com/"))), _)) @@ -1673,8 +1388,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ClearHistoryShouldDeleteArchivedSuggestions) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/false); + auto provider = MakeSuggestionsProvider(); // First get suggestions into the archived state which happens through // subsequent fetches. Then we verify the entries are gone from the 'archived' // state by trying to load their images (and we shouldn't even know the URLs @@ -1744,12 +1458,9 @@ TEST_F(RemoteSuggestionsProviderImplTest, ReturnFetchRequestEmptyBeforeInit) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)).Times(0); + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)).Times(0); MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; EXPECT_CALL(loaded, Call(Field(&Status::code, StatusCode::TEMPORARY_ERROR), IsEmpty())); @@ -1760,14 +1471,11 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldForwardTemporaryErrorFromFetcher) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + auto provider = MakeSuggestionsProvider(); RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; - EXPECT_CALL(*mock_fetcher, FetchSnippets(_, _)) + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)); EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) .WillOnce(Return(true)) @@ -1786,8 +1494,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldNotAddNewSuggestionsAfterFetchError) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); FetchTheseSuggestions( provider.get(), /*interactive_request=*/false, @@ -1799,8 +1506,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldNotClearOldSuggestionsAfterFetchError) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back(FetchedCategory( @@ -1828,8 +1534,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, Dismiss) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; const FetchedCategoryBuilder category_builder = @@ -1883,8 +1588,7 @@ IsEmpty()); // The suggestion should stay dismissed even after re-creating the provider. - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/true, - /*set_empty_response=*/true); + ResetSuggestionsProvider(&provider); fetched_categories.clear(); fetched_categories.push_back(category_builder.Build()); FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, @@ -1907,8 +1611,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, GetDismissed) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -1953,8 +1656,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, RemoveExpiredDismissedContent) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2004,8 +1706,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ExpiredContentNotRemoved) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2023,8 +1724,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSource) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2051,8 +1751,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMissingData) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2070,8 +1769,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, LogNumArticlesHistogram) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); base::HistogramTester tester; @@ -2160,8 +1858,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, DismissShouldRespectAllKnownUrls) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); const std::vector<std::string> source_urls = { "http://mashable.com/2016/05/11/stolen", @@ -2213,8 +1910,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ImageReturnedWithTheSameId) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2248,8 +1944,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, EmptyImageReturnedForNonExistentId) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); // Create a non-empty image so that we can test the image gets updated. gfx::Image image = gfx::test::CreateImage(1, 1); @@ -2270,8 +1965,7 @@ // Testing that the provider is not accessing the database is tricky. // Therefore, we simply put in some data making sure that if the provider asks // the database, it will get a wrong answer. - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); ContentSuggestion::ID unknown_id = MakeArticleID(kSuggestionUrl2); database()->SaveImage(unknown_id.id_within_category(), "some image blob"); @@ -2293,8 +1987,7 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ClearHistoryRemovesAllSuggestions) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/true, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2333,8 +2026,7 @@ ShouldKeepArticlesCategoryAvailableAfterClearHistory) { // If the provider marks that category as NOT_PROVIDED, then it won't be shown // at all in the UI and the user cannot load new data :-/. - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/false, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); ASSERT_THAT(observer().StatusForCategory(articles_category()), Eq(CategoryStatus::AVAILABLE)); @@ -2346,10 +2038,18 @@ } TEST_F(RemoteSuggestionsProviderImplTest, ShouldClearOrphanedImagesOnRestart) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/false, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); - LoadFromJSONString(provider.get(), GetTestJson({GetSuggestion()})); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder().AddId(kSuggestionUrl)) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ServeImageCallback cb = base::Bind(&ServeOneByOneImage, &provider->GetImageFetcherForTesting()); @@ -2363,14 +2063,20 @@ // Send new suggestion which don't include the suggestion referencing the // image. - LoadFromJSONString(provider.get(), - GetTestJson({GetSuggestionWithUrl( - "http://something.com/pletely/unrelated")})); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId( + "http://something.com/pletely/unrelated")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); // The image should still be available until a restart happens. EXPECT_FALSE( FetchImage(provider.get(), MakeArticleID(kSuggestionUrl)).IsEmpty()); - ResetSuggestionsProvider(&provider, /*use_mock_suggestions_fetcher=*/false, - /*set_empty_response=*/true); + ResetSuggestionsProvider(&provider); // After the restart, the image should be garbage collected. EXPECT_TRUE( FetchImage(provider.get(), MakeArticleID(kSuggestionUrl)).IsEmpty()); @@ -2378,15 +2084,19 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldHandleMoreThanMaxSuggestionsInResponse) { - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/false, /*set_empty_response=*/true); + auto provider = MakeSuggestionsProvider(); - std::vector<std::string> suggestions; + std::vector<FetchedCategory> fetched_categories; + FetchedCategoryBuilder category_builder; + category_builder.SetCategory(articles_category()); for (int i = 0; i < provider->GetMaxSuggestionCountForTesting() + 1; ++i) { - suggestions.push_back(GetSuggestionWithUrl( + category_builder.AddSuggestionViaBuilder(RemoteSuggestionBuilder().AddId( base::StringPrintf("http://localhost/suggestion-id-%d", i))); } - LoadFromJSONString(provider.get(), GetTestJson(suggestions)); + fetched_categories.push_back(category_builder.Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); // TODO(tschumann): We should probably trim out any additional results and // only serve the MaxSuggestionCount items. EXPECT_THAT(provider->GetSuggestionsForTesting(articles_category()), @@ -2399,7 +2109,6 @@ // is triggered since the suggestions DB is empty. Therefore the provider must // not be initialized until the test clock is set. auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/false); auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>(); @@ -2410,19 +2119,24 @@ EXPECT_EQ( 0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); EXPECT_EQ( simple_test_clock_ptr->Now().ToInternalValue(), pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); // Advance the time and check whether the time was updated correctly after the // background fetch. - simple_test_clock_ptr->Advance(TimeDelta::FromHours(1)); + simple_test_clock_ptr->Advance(base::TimeDelta::FromHours(1)); + RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback; + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _)) + .WillOnce(MoveSecondArgumentPointeeTo(&snippets_callback)) + .RetiresOnSaturation(); provider->RefetchInTheBackground( RemoteSuggestionsProvider::FetchStatusCallback()); base::RunLoop().RunUntilIdle(); + std::move(snippets_callback) + .Run(Status(StatusCode::SUCCESS, "message"), base::nullopt); // TODO(jkrcal): Move together with the pref storage into the scheduler. EXPECT_EQ( simple_test_clock_ptr->Now().ToInternalValue(), @@ -2437,8 +2151,7 @@ // Should be called when becoming ready. EXPECT_CALL(*scheduler(), OnProviderActivated()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); } TEST_F(RemoteSuggestionsProviderImplTest, CallsSchedulerOnError) { @@ -2470,8 +2183,7 @@ MakeSuggestionsProviderWithoutInitializationWithStrictScheduler(); // Initiate the provider so that it is already READY. EXPECT_CALL(*scheduler(), OnProviderActivated()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); // The scheduler should be notified of clearing the history. EXPECT_CALL(*scheduler(), OnHistoryCleared()); @@ -2484,8 +2196,7 @@ MakeSuggestionsProviderWithoutInitializationWithStrictScheduler(); // Initiate the provider so that it is already READY. EXPECT_CALL(*scheduler(), OnProviderActivated()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); // The scheduler should be notified of clearing the history. EXPECT_CALL(*scheduler(), OnSuggestionsCleared()); @@ -2498,8 +2209,7 @@ MakeSuggestionsProviderWithoutInitializationWithStrictScheduler(); // Initiate the provider so that it is already READY. EXPECT_CALL(*scheduler(), OnProviderActivated()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); + WaitForSuggestionsProviderInitialization(provider.get()); // The scheduler should be notified of clearing the history. EXPECT_CALL(*scheduler(), OnSuggestionsCleared()); @@ -2510,12 +2220,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldExcludeKnownSuggestionsWithoutTruncatingWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); std::set<std::string> known_ids; for (int i = 0; i < 200; ++i) { @@ -2525,7 +2231,7 @@ EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) .WillOnce(Return(true)) .RetiresOnSaturation(); - EXPECT_CALL(*mock_fetcher, + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(Field(&RequestParams::excluded_ids, known_ids), _)); provider->Fetch( articles_category(), known_ids, @@ -2536,14 +2242,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldExcludeDismissedSuggestionsWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - - // Initialize fetcher to return a given suggestion. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); std::vector<FetchedCategory> fetched_categories; fetched_categories.push_back( @@ -2563,9 +2263,10 @@ EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) .WillOnce(Return(true)) .RetiresOnSaturation(); - EXPECT_CALL(*mock_fetcher, FetchSnippets(Field(&RequestParams::excluded_ids, - expected_excluded_ids), - _)); + EXPECT_CALL( + *mock_suggestions_fetcher(), + FetchSnippets(Field(&RequestParams::excluded_ids, expected_excluded_ids), + _)); provider->Fetch( articles_category(), std::set<std::string>(), base::Bind([](Status status_code, @@ -2575,14 +2276,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldTruncateExcludedDismissedSuggestionsWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - - // Initialize fetcher to return given suggestions. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); std::vector<FetchedCategory> fetched_categories; FetchedCategoryBuilder category_builder; @@ -2606,7 +2301,7 @@ EXPECT_CALL(*scheduler(), AcquireQuotaForInteractiveFetch()) .WillOnce(Return(true)) .RetiresOnSaturation(); - EXPECT_CALL(*mock_fetcher, + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(Field(&RequestParams::excluded_ids, SizeIs(kMaxExcludedDismissedIds)), _)); @@ -2619,14 +2314,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldPreferLatestExcludedDismissedSuggestionsWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - - // Initialize fetcher to return given suggestions. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); std::vector<FetchedCategory> fetched_categories; FetchedCategoryBuilder category_builder; @@ -2657,7 +2346,7 @@ .RetiresOnSaturation(); // The oldest dismissed suggestion should be absent, because there are // |kMaxExcludedDismissedIds| newer dismissed suggestions. - EXPECT_CALL(*mock_fetcher, + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(Field(&RequestParams::excluded_ids, Not(Contains(first_dismissed_suggestion_id))), _)); @@ -2670,14 +2359,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldExcludeDismissedSuggestionsFromAllCategoriesWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - - // Initialize fetcher to return given suggestions. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); // Add article suggestions. std::vector<FetchedCategory> fetched_categories; @@ -2720,9 +2403,10 @@ .RetiresOnSaturation(); // Dismissed suggestions from all categories must be excluded (but not only // target category). - EXPECT_CALL(*mock_fetcher, FetchSnippets(Field(&RequestParams::excluded_ids, - expected_excluded_ids), - _)); + EXPECT_CALL( + *mock_suggestions_fetcher(), + FetchSnippets(Field(&RequestParams::excluded_ids, expected_excluded_ids), + _)); provider->Fetch( articles_category(), std::set<std::string>(), base::Bind([](Status status_code, @@ -2732,14 +2416,8 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldPreferTargetCategoryExcludedDismissedSuggestionsWhenFetchingMore) { auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/true, /*use_mock_prefetched_pages_tracker=*/false); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/true); - - // Initialize fetcher to return given suggestions. - auto* mock_fetcher = static_cast<StrictMock<MockRemoteSuggestionsFetcher>*>( - suggestions_fetcher()); + WaitForSuggestionsProviderInitialization(provider.get()); // Add article suggestions. std::vector<FetchedCategory> fetched_categories; @@ -2779,7 +2457,7 @@ // The other category dismissed suggestion should be absent, because the fetch // is for articles and there are |kMaxExcludedDismissedIds| dismissed // suggestions there. - EXPECT_CALL(*mock_fetcher, + EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(Field(&RequestParams::excluded_ids, Not(Contains("http://other.com/"))), _)); @@ -2792,9 +2470,16 @@ TEST_F(RemoteSuggestionsProviderImplTest, ShouldFetchNormallyWithoutPrefetchedPagesTracker) { EnableKeepingPrefetchedContentSuggestions(); - auto provider = MakeSuggestionsProvider( - /*use_mock_suggestions_fetcher=*/false, /*set_empty_response=*/true); - LoadFromJSONString(provider.get(), GetTestJson({GetSuggestion()})); + auto provider = MakeSuggestionsProvider(); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder()) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); } @@ -2803,17 +2488,23 @@ ShouldKeepPrefetchedSuggestionsAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://prefeched.com", "publisher", - "http://amp.prefetched.com")})); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://prefetched.com") + .SetUrl("http://prefetched.com") + .SetAmpUrl("http://amp.prefetched.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); @@ -2822,36 +2513,49 @@ EXPECT_CALL(*mock_tracker, PrefetchedOfflinePageExists(GURL("http://amp.prefetched.com"))) .WillOnce(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://other.com", "publisher", - "http://amp.other.com")})); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://other.com") + .SetUrl("http://other.com") + .SetAmpUrl("http://amp.other.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); - EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), - UnorderedElementsAre( - Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://prefeched.com")), - Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://other.com")))); + EXPECT_THAT( + observer().SuggestionsForCategory(articles_category()), + UnorderedElementsAre( + Property(&ContentSuggestion::id, + MakeArticleID("http://prefetched.com")), + Property(&ContentSuggestion::id, MakeArticleID("http://other.com")))); } TEST_F(RemoteSuggestionsProviderImplTest, ShouldIgnoreNotPrefetchedSuggestionsAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString(provider.get(), - GetTestJson({GetSuggestionWithSources( - "http://not_prefeched.com", "publisher", - "http://amp.not_prefetched.com")})); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder() + .AddId("http://not_prefetched.com") + .SetUrl("http://not_prefetched.com") + .SetAmpUrl("http://amp.not_prefetched.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); @@ -2860,40 +2564,50 @@ EXPECT_CALL(*mock_tracker, PrefetchedOfflinePageExists( GURL("http://amp.not_prefetched.com"))) .WillOnce(Return(false)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://other.com", "publisher", - "http://amp.other.com")})); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://other.com") + .SetUrl("http://other.com") + .SetAmpUrl("http://amp.other.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), - UnorderedElementsAre( - Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://other.com")))); + UnorderedElementsAre(Property( + &ContentSuggestion::id, MakeArticleID("http://other.com")))); } TEST_F(RemoteSuggestionsProviderImplTest, ShouldLimitKeptPrefetchedSuggestionsAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); const int prefetched_suggestions_count = 2 * kMaxAdditionalPrefetchedSuggestions + 1; - std::vector<std::string> prefetched_suggestions; + std::vector<FetchedCategory> fetched_categories; + FetchedCategoryBuilder category_builder; + category_builder.SetCategory(articles_category()); for (int i = 0; i < prefetched_suggestions_count; ++i) { - prefetched_suggestions.push_back(GetSuggestionWithSources( - base::StringPrintf("http://prefetched.com/%d", i), "publisher", - base::StringPrintf("http://amp.prefetched.com/%d", i))); + const std::string url = base::StringPrintf("http://prefetched.com/%d", i); + category_builder.AddSuggestionViaBuilder( + RemoteSuggestionBuilder().AddId(url).SetUrl(url).SetAmpUrl( + base::StringPrintf("http://amp.prefetched.com/%d", i))); } + fetched_categories.push_back(category_builder.Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString(provider.get(), GetTestJson(prefetched_suggestions)); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(prefetched_suggestions_count)); @@ -2904,10 +2618,19 @@ base::StringPrintf("http://amp.prefetched.com/%d", i)))) .WillOnce(Return(true)); } - LoadFromJSONString(provider.get(), - GetTestJson({GetSuggestionWithSources( - "http://not_prefeched.com", "publisher", - "http://amp.not_prefetched.com")})); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder() + .AddId("http://not_prefetched.com") + .SetUrl("http://not_prefetched.com") + .SetAmpUrl("http://amp.not_prefetched.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(kMaxAdditionalPrefetchedSuggestions + 1)); @@ -2917,25 +2640,49 @@ ShouldMixInPrefetchedSuggestionsByScoreAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://prefetched.com/1") + .SetUrl("http://prefetched.com/1") + .SetAmpUrl("http://amp.prefetched.com/1") + .SetScore(1)) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://prefetched.com/3") + .SetUrl("http://prefetched.com/3") + .SetAmpUrl("http://amp.prefetched.com/3") + .SetScore(3)) + .Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSourcesAndScore( - "http://prefeched.com/1", "publisher", - "http://amp.prefetched.com/1", /*score=*/1), - GetSuggestionWithSourcesAndScore( - "http://prefeched.com/3", "publisher", - "http://amp.prefetched.com/3", /*score=*/3)})); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(2)); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://new.com/2") + .SetUrl("http://new.com/2") + .SetAmpUrl("http://amp.new.com/2") + .SetScore(2)) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://new.com/4") + .SetUrl("http://new.com/4") + .SetAmpUrl("http://amp.new.com/4") + .SetScore(4)) + .Build()); + EXPECT_CALL(*mock_tracker, PrefetchedOfflinePageExists(GURL("http://amp.prefetched.com/1"))) .WillOnce(Return(true)); @@ -2943,27 +2690,19 @@ PrefetchedOfflinePageExists(GURL("http://amp.prefetched.com/3"))) .WillOnce(Return(true)); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString(provider.get(), - GetTestJson({GetSuggestionWithSourcesAndScore( - "http://new.com/2", "publisher", - "http://amp.new.com/2", /*score=*/2), - GetSuggestionWithSourcesAndScore( - "http://new.com/4", "publisher", - "http://amp.new.com/4", /*score=*/4)})); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); EXPECT_THAT( observer().SuggestionsForCategory(articles_category()), ElementsAre( Property(&ContentSuggestion::id, MakeArticleID("http://new.com/4")), Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://prefeched.com/3")), + MakeArticleID("http://prefetched.com/3")), + Property(&ContentSuggestion::id, MakeArticleID("http://new.com/2")), Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://new.com/2")), - Property(&ContentSuggestion::id, - Property(&ContentSuggestion::ID::id_within_category, - "http://prefeched.com/1")))); + MakeArticleID("http://prefetched.com/1")))); } TEST_F( @@ -2971,17 +2710,23 @@ ShouldKeepMostRecentlyFetchedPrefetchedSuggestionsFirstAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); + std::vector<FetchedCategory> fetched_categories; const int prefetched_suggestions_count = 2 * kMaxAdditionalPrefetchedSuggestions + 1; - for (int i = 0; i < prefetched_suggestions_count; ++i) { + const std::string url = base::StringPrintf("http://prefetched.com/%d", i); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder().AddId(url).SetUrl(url).SetAmpUrl( + base::StringPrintf("http://amp.prefetched.com/%d", i))) + .Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); if (i != 0) { EXPECT_CALL(*mock_tracker, @@ -2989,11 +2734,10 @@ "http://amp.prefetched.com/%d", i - 1)))) .WillRepeatedly(Return(true)); } - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources( - base::StringPrintf("http://prefetched.com/%d", i), "publisher", - base::StringPrintf("http://amp.prefetched.com/%d", i))})); + + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); } const std::vector<ContentSuggestion>& actual_suggestions = @@ -3019,62 +2763,84 @@ ShouldNotKeepStalePrefetchedSuggestionsAfterFetchWhenEnabled) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - auto* fetcher = - static_cast<RemoteSuggestionsFetcherImpl*>(suggestions_fetcher()); - auto wrapped_fetcher_clock = base::MakeUnique<base::SimpleTestClock>(); - base::SimpleTestClock* fetcher_clock = wrapped_fetcher_clock.get(); - fetcher->SetClockForTesting(std::move(wrapped_fetcher_clock)); - auto wrapped_provider_clock = base::MakeUnique<base::SimpleTestClock>(); base::SimpleTestClock* provider_clock = wrapped_provider_clock.get(); provider->SetClockForTesting(std::move(wrapped_provider_clock)); provider_clock->SetNow(GetDefaultCreationTime() + base::TimeDelta::FromHours(10)); - fetcher_clock->SetNow(provider_clock->Now()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); - + WaitForSuggestionsProviderInitialization(provider.get()); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder() + .AddId("http://prefetched.com") + .SetUrl("http://prefetched.com") + .SetAmpUrl("http://amp.prefetched.com") + .SetFetchDate(provider_clock->Now()) + .SetPublishDate(GetDefaultCreationTime())) + .Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://prefeched.com", "publisher", - "http://amp.prefetched.com")})); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(1)); provider_clock->Advance(kMaxAgeForAdditionalPrefetchedSuggestion - base::TimeDelta::FromSeconds(1)); - fetcher_clock->SetNow(provider_clock->Now()); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder() + .AddId("http://other.com") + .SetUrl("http://other.com") + .SetAmpUrl("http://amp.other.com") + .SetFetchDate(provider_clock->Now()) + .SetPublishDate(GetDefaultCreationTime())) + .Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); EXPECT_CALL(*mock_tracker, PrefetchedOfflinePageExists(GURL("http://amp.prefetched.com"))) .WillOnce(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://other.com", "publisher", - "http://amp.other.com")})); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); + ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(2)); provider_clock->Advance(base::TimeDelta::FromSeconds(2)); - fetcher_clock->SetNow(provider_clock->Now()); + fetched_categories.clear(); + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder( + RemoteSuggestionBuilder() + .AddId("http://other.com") + .SetUrl("http://other.com") + .SetAmpUrl("http://amp.other.com") + .SetFetchDate(provider_clock->Now()) + .SetPublishDate(GetDefaultCreationTime())) + .Build()); EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true)); EXPECT_CALL(*mock_tracker, PrefetchedOfflinePageExists(GURL("http://amp.prefetched.com"))) .WillOnce(Return(true)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://other.com", "publisher", - "http://amp.other.com")})); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), ElementsAre(Property(&ContentSuggestion::id, MakeArticleID("http://other.com")))); @@ -3084,21 +2850,27 @@ ShouldWaitForPrefetchedPagesTrackerInitialization) { EnableKeepingPrefetchedContentSuggestions(); auto provider = MakeSuggestionsProviderWithoutInitialization( - /*use_mock_suggestions_fetcher=*/false, /*use_mock_prefetched_pages_tracker=*/true); auto* mock_tracker = static_cast<StrictMock<MockPrefetchedPagesTracker>*>( prefetched_pages_tracker()); - WaitForSuggestionsProviderInitialization(provider.get(), - /*set_empty_response=*/false); + WaitForSuggestionsProviderInitialization(provider.get()); base::OnceCallback<void()> initialization_completed_callback; EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(false)); EXPECT_CALL(*mock_tracker, AddInitializationCompletedCallback(_)) .WillOnce(MoveFirstArgumentPointeeTo(&initialization_completed_callback)); - LoadFromJSONString( - provider.get(), - GetTestJson({GetSuggestionWithSources("http://prefeched.com", "publisher", - "http://amp.prefetched.com")})); + std::vector<FetchedCategory> fetched_categories; + fetched_categories.push_back( + FetchedCategoryBuilder() + .SetCategory(articles_category()) + .AddSuggestionViaBuilder(RemoteSuggestionBuilder() + .AddId("http://prefetched.com") + .SetUrl("http://prefetched.com") + .SetAmpUrl("http://amp.prefetched.com")) + .Build()); + FetchTheseSuggestions(provider.get(), /*interactive_request=*/true, + Status(StatusCode::SUCCESS, "message"), + std::move(fetched_categories)); EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), SizeIs(0));
diff --git a/components/offline_pages/core/offline_page_feature.cc b/components/offline_pages/core/offline_page_feature.cc index d3eeb441..146efed9 100644 --- a/components/offline_pages/core/offline_page_feature.cc +++ b/components/offline_pages/core/offline_page_feature.cc
@@ -52,6 +52,9 @@ "BackgroundLoader", base::FEATURE_DISABLED_BY_DEFAULT }; +const base::Feature kOfflinePagesCTV2Feature{"OfflinePagesCTV2", + base::FEATURE_DISABLED_BY_DEFAULT}; + bool IsOfflineBookmarksEnabled() { return base::FeatureList::IsEnabled(kOfflineBookmarksFeature); } @@ -98,4 +101,8 @@ return cl->HasSwitch(switches::kOfflinePagesUseTestingSnapshotDelay); } +bool IsOfflinePagesCTV2Enabled() { + return base::FeatureList::IsEnabled(kOfflinePagesCTV2Feature); +} + } // namespace offline_pages
diff --git a/components/offline_pages/core/offline_page_feature.h b/components/offline_pages/core/offline_page_feature.h index 11a5b68..00c4c38 100644 --- a/components/offline_pages/core/offline_page_feature.h +++ b/components/offline_pages/core/offline_page_feature.h
@@ -20,6 +20,7 @@ extern const base::Feature kPrefetchingOfflinePagesFeature; extern const base::Feature kNewBackgroundLoaderFeature; extern const base::Feature kOfflinePagesLoadSignalCollectingFeature; +extern const base::Feature kOfflinePagesCTV2Feature; // Returns true if saving bookmarked pages for offline viewing is enabled. bool IsOfflineBookmarksEnabled(); @@ -57,6 +58,9 @@ // snapshot delay. bool ShouldUseTestingSnapshotDelay(); +// Returns true if we should record request origin as part of custom tabs V2. +bool IsOfflinePagesCTV2Enabled(); + } // namespace offline_pages #endif // COMPONENTS_OFFLINE_PAGES_OFFLINE_PAGE_FEATURE_H_
diff --git a/components/offline_pages/core/prefetch/BUILD.gn b/components/offline_pages/core/prefetch/BUILD.gn index ec22924..de42722 100644 --- a/components/offline_pages/core/prefetch/BUILD.gn +++ b/components/offline_pages/core/prefetch/BUILD.gn
@@ -44,6 +44,10 @@ "prefetch_service_impl.h", "prefetch_types.cc", "prefetch_types.h", + "store/prefetch_store.cc", + "store/prefetch_store.h", + "store/prefetch_store_utils.cc", + "store/prefetch_store_utils.h", "suggested_articles_observer.cc", "suggested_articles_observer.h", ] @@ -65,6 +69,7 @@ "//components/version_info", "//google_apis", "//net:net", + "//sql:sql", "//url", ] } @@ -76,6 +81,8 @@ "prefetch_request_test_base.h", "prefetch_service_test_taco.cc", "prefetch_service_test_taco.h", + "store/prefetch_store_test_util.cc", + "store/prefetch_store_test_util.h", "task_test_base.cc", "task_test_base.h", "test_offline_metrics_collector.h", @@ -96,6 +103,8 @@ "//components/prefs:test_support", "//components/version_info:channel", "//net:test_support", + "//sql:sql", + "//url", ] } @@ -111,6 +120,7 @@ source_set("unit_tests") { testonly = true sources = [ + "add_unique_urls_task_unittest.cc", "generate_page_bundle_request_unittest.cc", "generate_page_bundle_task_unittest.cc", "get_operation_request_unittest.cc", @@ -123,12 +133,14 @@ "prefetch_request_fetcher_unittest.cc", "prefetch_request_operation_response_unittest.cc", "prefetch_server_urls_unittest.cc", + "store/prefetch_store_unittest.cc", "suggested_articles_observer_unittest.cc", ] deps = [ ":prefetch", ":test_support", + "//base", "//components/download/public", "//components/gcm_driver/instance_id", "//components/offline_pages/core", @@ -137,6 +149,7 @@ "//components/variations:test_support", "//components/version_info:channel", "//net:test_support", + "//sql:sql", "//testing/gmock", "//testing/gtest", "//url",
diff --git a/components/offline_pages/core/prefetch/DEPS b/components/offline_pages/core/prefetch/DEPS index 2bebfd7..98d9dd2 100644 --- a/components/offline_pages/core/prefetch/DEPS +++ b/components/offline_pages/core/prefetch/DEPS
@@ -6,4 +6,5 @@ "+components/ntp_snippets", "+components/version_info", "+net", + "+sql", ]
diff --git a/components/offline_pages/core/prefetch/add_unique_urls_task.cc b/components/offline_pages/core/prefetch/add_unique_urls_task.cc index e25cc54..9307342 100644 --- a/components/offline_pages/core/prefetch/add_unique_urls_task.cc +++ b/components/offline_pages/core/prefetch/add_unique_urls_task.cc
@@ -4,53 +4,135 @@ #include "components/offline_pages/core/prefetch/add_unique_urls_task.h" +#include <map> #include <memory> +#include <set> #include <utility> #include "base/bind.h" #include "base/callback.h" +#include "base/time/time.h" +#include "components/offline_pages/core/prefetch/prefetch_types.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_utils.h" +#include "sql/connection.h" +#include "sql/statement.h" +#include "sql/transaction.h" #include "url/gurl.h" namespace offline_pages { namespace { -// Adds new prefetch item entries to the store using the URLs and client IDs -// from |prefetch_urls| and the client's |name_space|. Also cleans up entries in -// the Zombie state from the client's |name_space| except for the ones -// whose URL is contained in |prefetch_urls|. -// Returns the number of added prefecth items. -static int AddUrlsAndCleanupZombies( - const std::string& name_space, - const std::vector<PrefetchURL>& prefetch_urls) { - NOTIMPLEMENTED(); - return 1; +std::map<std::string, std::pair<int64_t, PrefetchItemState>> +FindExistingPrefetchItemsInNamespaceSync(sql::Connection* db, + const std::string& name_space) { + static const char kSql[] = + "SELECT offline_id, state, requested_url FROM prefetch_items" + " WHERE client_namespace = ?"; + sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindString(0, name_space); + + std::map<std::string, std::pair<int64_t, PrefetchItemState>> result; + while (statement.Step()) { + result.insert(std::make_pair( + statement.ColumnString(2), + std::make_pair(statement.ColumnInt64(0), static_cast<PrefetchItemState>( + statement.ColumnInt(1))))); + } + + return result; } -// TODO(fgorski): replace this with the SQL executor. -static void Execute(base::RepeatingCallback<int()> command_callback, - base::OnceCallback<void(int)> result_callback) { - std::move(result_callback).Run(command_callback.Run()); +bool CreatePrefetchItemSync(sql::Connection* db, + const std::string& name_space, + const PrefetchURL& prefetch_url) { + static const char kSql[] = + "INSERT INTO prefetch_items" + " (offline_id, requested_url, client_namespace, client_id, creation_time," + " freshness_time)" + " VALUES" + " (?, ?, ?, ?, ?, ?)"; + + int64_t now_internal = base::Time::Now().ToInternalValue(); + sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt64(0, GenerateOfflineId()); + statement.BindString(1, prefetch_url.url.spec()); + statement.BindString(2, name_space); + statement.BindString(3, prefetch_url.id); + statement.BindInt64(4, now_internal); + statement.BindInt64(5, now_internal); + + return statement.Run(); +} + +// Adds new prefetch item entries to the store using the URLs and client IDs +// from |candidate_prefetch_urls| and the client's |name_space|. Also cleans up +// entries in the Zombie state from the client's |name_space| except for the +// ones whose URL is contained in |candidate_prefetch_urls|. +// Returns the number of added prefecth items. +AddUniqueUrlsTask::Result AddUrlsAndCleanupZombiesSync( + const std::string& name_space, + const std::vector<PrefetchURL>& candidate_prefetch_urls, + sql::Connection* db) { + if (!db) + return AddUniqueUrlsTask::Result::STORE_ERROR; + + sql::Transaction transaction(db); + if (!transaction.Begin()) + return AddUniqueUrlsTask::Result::STORE_ERROR; + + std::map<std::string, std::pair<int64_t, PrefetchItemState>> existing_items = + FindExistingPrefetchItemsInNamespaceSync(db, name_space); + + AddUniqueUrlsTask::Result result(AddUniqueUrlsTask::Result::NOTHING_ADDED); + for (const auto& prefetch_url : candidate_prefetch_urls) { + auto iter = existing_items.find(prefetch_url.url.spec()); + if (iter == existing_items.end()) { + if (!CreatePrefetchItemSync(db, name_space, prefetch_url)) + return AddUniqueUrlsTask::Result::STORE_ERROR; // Transaction rollback. + result = AddUniqueUrlsTask::Result::URLS_ADDED; + } else { + // Removing from the list of existing items if it was requested again, to + // prevent it from being removed in the next step. + existing_items.erase(iter); + } + } + + // Purge remaining zombie IDs. + for (const auto& existing_item : existing_items) { + if (existing_item.second.second != PrefetchItemState::ZOMBIE) + continue; + if (!DeletePrefetchItemByOfflineIdSync(db, existing_item.second.first)) + return AddUniqueUrlsTask::Result::STORE_ERROR; // Transaction rollback. + } + + if (!transaction.Commit()) + return AddUniqueUrlsTask::Result::STORE_ERROR; // Transaction rollback. + + return result; } } AddUniqueUrlsTask::AddUniqueUrlsTask( + PrefetchStore* prefetch_store, const std::string& name_space, const std::vector<PrefetchURL>& prefetch_urls) - : name_space_(name_space), + : prefetch_store_(prefetch_store), + name_space_(name_space), prefetch_urls_(prefetch_urls), weak_ptr_factory_(this) {} AddUniqueUrlsTask::~AddUniqueUrlsTask() {} void AddUniqueUrlsTask::Run() { - Execute(base::BindRepeating(&AddUrlsAndCleanupZombies, name_space_, - prefetch_urls_), - base::BindOnce(&AddUniqueUrlsTask::OnUrlsAdded, - weak_ptr_factory_.GetWeakPtr())); + prefetch_store_->Execute(base::BindOnce(&AddUrlsAndCleanupZombiesSync, + name_space_, prefetch_urls_), + base::BindOnce(&AddUniqueUrlsTask::OnUrlsAdded, + weak_ptr_factory_.GetWeakPtr())); } -void AddUniqueUrlsTask::OnUrlsAdded(int added_entry_count) { +void AddUniqueUrlsTask::OnUrlsAdded(Result result) { // TODO(carlosk): schedule NWake here if at least one new entry was added to // the store. TaskComplete();
diff --git a/components/offline_pages/core/prefetch/add_unique_urls_task.h b/components/offline_pages/core/prefetch/add_unique_urls_task.h index c265cd3b..b400915 100644 --- a/components/offline_pages/core/prefetch/add_unique_urls_task.h +++ b/components/offline_pages/core/prefetch/add_unique_urls_task.h
@@ -8,11 +8,13 @@ #include <string> #include <vector> +#include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "components/offline_pages/core/prefetch/prefetch_types.h" #include "components/offline_pages/core/task.h" namespace offline_pages { +class PrefetchStore; +struct PrefetchURL; // Task that adds new URL suggestions to the pipeline. URLs are matched against // existing ones from any stage of the process so that only new, unique ones are @@ -25,15 +27,25 @@ // from the store. class AddUniqueUrlsTask : public Task { public: - AddUniqueUrlsTask(const std::string& name_space, + // Result of executing the command in the store. + enum class Result { + NOTHING_ADDED, + URLS_ADDED, + STORE_ERROR, + }; + + AddUniqueUrlsTask(PrefetchStore* prefetch_store, + const std::string& name_space, const std::vector<PrefetchURL>& prefetch_urls); ~AddUniqueUrlsTask() override; void Run() override; private: - void OnUrlsAdded(int added_entry_count); + void OnUrlsAdded(Result result); + // Prefetch store to execute against. Not owned. + PrefetchStore* prefetch_store_; const std::string& name_space_; std::vector<PrefetchURL> prefetch_urls_;
diff --git a/components/offline_pages/core/prefetch/add_unique_urls_task_unittest.cc b/components/offline_pages/core/prefetch/add_unique_urls_task_unittest.cc new file mode 100644 index 0000000..4a9c043 --- /dev/null +++ b/components/offline_pages/core/prefetch/add_unique_urls_task_unittest.cc
@@ -0,0 +1,129 @@ +// 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 "components/offline_pages/core/prefetch/add_unique_urls_task.h" + +#include <string> +#include <vector> + +#include "base/test/test_simple_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" +#include "components/offline_pages/core/prefetch/prefetch_types.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace offline_pages { +namespace { +void VerifyItemCount(int expected_count, int actual_count) { + EXPECT_EQ(expected_count, actual_count); +} +} // namespace + +class AddUniqueUrlsTaskTest : public testing::Test { + public: + AddUniqueUrlsTaskTest(); + ~AddUniqueUrlsTaskTest() override = default; + + void SetUp() override; + void TearDown() override; + + PrefetchStore* store() { return store_test_util_.store(); } + + PrefetchStoreTestUtil* store_util() { return &store_test_util_; } + + void PumpLoop(); + + private: + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + base::ThreadTaskRunnerHandle task_runner_handle_; + PrefetchStoreTestUtil store_test_util_; +}; + +AddUniqueUrlsTaskTest::AddUniqueUrlsTaskTest() + : task_runner_(new base::TestSimpleTaskRunner), + task_runner_handle_(task_runner_) {} + +void AddUniqueUrlsTaskTest::SetUp() { + store_test_util_.BuildStoreInMemory(); +} + +void AddUniqueUrlsTaskTest::TearDown() { + store_test_util_.DeleteStore(); + PumpLoop(); +} + +void AddUniqueUrlsTaskTest::PumpLoop() { + task_runner_->RunUntilIdle(); +} + +TEST_F(AddUniqueUrlsTaskTest, AddTaskInEmptyStore) { + std::string name_space("test"); + std::vector<PrefetchURL> urls; + urls.push_back(PrefetchURL{"ID-1", GURL("https://www.google.com/")}); + urls.push_back(PrefetchURL{"ID-2", GURL("http://www.example.com/")}); + AddUniqueUrlsTask task(store(), name_space, urls); + task.Run(); + PumpLoop(); + + store_util()->CountPrefetchItems(base::BindOnce(&VerifyItemCount, 2)); + PumpLoop(); +} + +TEST_F(AddUniqueUrlsTaskTest, DontAddURLIfItExists) { + std::string name_space("test"); + std::vector<PrefetchURL> urls; + urls.push_back(PrefetchURL{"ID-1", GURL("https://www.google.com/")}); + urls.push_back(PrefetchURL{"ID-2", GURL("http://www.example.com/")}); + AddUniqueUrlsTask task1(store(), name_space, urls); + task1.Run(); + PumpLoop(); + + urls.clear(); + urls.push_back(PrefetchURL{"ID-1", GURL("https://www.google.com/")}); + urls.push_back(PrefetchURL{"ID-3", GURL("https://news.google.com/")}); + AddUniqueUrlsTask task2(store(), name_space, urls); + task2.Run(); + PumpLoop(); + + // Do the count here. + store_util()->CountPrefetchItems(base::BindOnce(&VerifyItemCount, 3)); + PumpLoop(); +} + +TEST_F(AddUniqueUrlsTaskTest, HandleZombiePrefetchItems) { + std::string name_space("test"); + std::vector<PrefetchURL> urls; + urls.push_back(PrefetchURL{"ID-1", GURL("https://www.google.com/")}); + urls.push_back(PrefetchURL{"ID-2", GURL("http://www.example.com/")}); + urls.push_back(PrefetchURL{"ID-3", GURL("https://news.google.com/")}); + AddUniqueUrlsTask task1(store(), name_space, urls); + task1.Run(); + PumpLoop(); + + store_util()->ZombifyPrefetchItem(name_space, urls[0].url, + base::BindOnce(&VerifyItemCount, 1)); + PumpLoop(); + store_util()->ZombifyPrefetchItem(name_space, urls[1].url, + base::BindOnce(&VerifyItemCount, 1)); + PumpLoop(); + + urls.clear(); + urls.push_back(PrefetchURL{"ID-1", GURL("https://www.google.com/")}); + urls.push_back(PrefetchURL{"ID-3", GURL("https://news.google.com/")}); + urls.push_back(PrefetchURL{"ID-4", GURL("https://chrome.google.com/")}); + // ID-1 is expected to stay in zombie state. + // ID-2 is expected to be removed, because it is in zombie state. + // ID-3 is still requested, so it is ignored. + // ID-4 is added. + AddUniqueUrlsTask task2(store(), name_space, urls); + task2.Run(); + PumpLoop(); + + // Do the count here. + store_util()->CountPrefetchItems(base::BindOnce(&VerifyItemCount, 3)); + PumpLoop(); +} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl.cc b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl.cc index ce4b1fd8..04b82549 100644 --- a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl.cc +++ b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl.cc
@@ -49,8 +49,9 @@ if (!IsPrefetchingOfflinePagesEnabled()) return; - std::unique_ptr<Task> add_task = - base::MakeUnique<AddUniqueUrlsTask>(name_space, prefetch_urls); + PrefetchStore* prefetch_store = service_->GetPrefetchStore(); + std::unique_ptr<Task> add_task = base::MakeUnique<AddUniqueUrlsTask>( + prefetch_store, name_space, prefetch_urls); task_queue_.AddTask(std::move(add_task)); // TODO(dewittj): Remove when we have proper scheduling.
diff --git a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc index d324c5d..7944ff1 100644 --- a/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_dispatcher_impl_unittest.cc
@@ -17,6 +17,8 @@ #include "components/offline_pages/core/prefetch/prefetch_network_request_factory.h" #include "components/offline_pages/core/prefetch/prefetch_service.h" #include "components/offline_pages/core/prefetch/prefetch_service_test_taco.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" #include "components/offline_pages/core/prefetch/suggested_articles_observer.h" #include "components/offline_pages/core/prefetch/test_prefetch_network_request_factory.h" #include "components/version_info/channel.h" @@ -25,9 +27,10 @@ #include "url/gurl.h" namespace offline_pages { - namespace { +const std::string kTestNamespace = "TestPrefetchClientNamespace"; + class TestScopedBackgroundTask : public PrefetchDispatcher::ScopedBackgroundTask { public: @@ -45,8 +48,6 @@ class PrefetchDispatcherTest : public testing::Test { public: - const std::string TEST_NAMESPACE = "TestPrefetchClientNamespace"; - PrefetchDispatcherTest(); // Test implementation. @@ -54,6 +55,7 @@ void TearDown() override; void PumpLoop(); + PrefetchDispatcher::ScopedBackgroundTask* GetBackgroundTask() { return dispatcher_->background_task_.get(); } @@ -67,29 +69,27 @@ std::vector<PrefetchURL> test_urls_; private: - scoped_refptr<base::TestSimpleTaskRunner> task_runner_ = - new base::TestSimpleTaskRunner; + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; - OfflineEventLogger logger_; + std::unique_ptr<PrefetchServiceTestTaco> taco_; + base::test::ScopedFeatureList feature_list_; - PrefetchServiceTestTaco taco_; // Owned by |taco_|. PrefetchDispatcherImpl* dispatcher_; }; PrefetchDispatcherTest::PrefetchDispatcherTest() - : task_runner_handle_(task_runner_) { + : task_runner_(new base::TestSimpleTaskRunner), + task_runner_handle_(task_runner_) { feature_list_.InitAndEnableFeature(kPrefetchingOfflinePagesFeature); - - dispatcher_ = new PrefetchDispatcherImpl(); - taco_.SetPrefetchDispatcher(base::WrapUnique(dispatcher_)); - - taco_.CreatePrefetchService(); } void PrefetchDispatcherTest::SetUp() { - ASSERT_FALSE(task_runner()->HasPendingTask()); + dispatcher_ = new PrefetchDispatcherImpl(); + taco_.reset(new PrefetchServiceTestTaco); + taco_->SetPrefetchDispatcher(base::WrapUnique(dispatcher_)); + taco_->CreatePrefetchService(); ASSERT_TRUE(test_urls_.empty()); test_urls_.push_back({"1", GURL("http://testurl.com/foo")}); @@ -97,7 +97,9 @@ } void PrefetchDispatcherTest::TearDown() { - task_runner()->ClearPendingTasks(); + // Ensures that the store is properly disposed off. + taco_.reset(); + PumpLoop(); } void PrefetchDispatcherTest::PumpLoop() { @@ -109,7 +111,7 @@ // with the state of adding tasks, and that the end state is we have tests // that verify the proper tasks were added in the proper order at each wakeup // signal of the dispatcher. - prefetch_dispatcher()->AddCandidatePrefetchURLs(TEST_NAMESPACE, test_urls_); + prefetch_dispatcher()->AddCandidatePrefetchURLs(kTestNamespace, test_urls_); prefetch_dispatcher()->RemoveAllUnprocessedPrefetchURLs( kSuggestedArticlesNamespace); prefetch_dispatcher()->RemovePrefetchURLsByClientId( @@ -117,9 +119,8 @@ } TEST_F(PrefetchDispatcherTest, AddCandidatePrefetchURLsTask) { - prefetch_dispatcher()->AddCandidatePrefetchURLs(TEST_NAMESPACE, test_urls_); + prefetch_dispatcher()->AddCandidatePrefetchURLs(kTestNamespace, test_urls_); EXPECT_TRUE(dispatcher_task_queue()->HasPendingTasks()); - EXPECT_TRUE(dispatcher_task_queue()->HasRunningTask()); PumpLoop(); EXPECT_FALSE(dispatcher_task_queue()->HasPendingTasks()); EXPECT_FALSE(dispatcher_task_queue()->HasRunningTask()); @@ -132,7 +133,7 @@ // Don't add a task for new prefetch URLs. PrefetchURL prefetch_url("id", GURL("https://www.chromium.org")); prefetch_dispatcher()->AddCandidatePrefetchURLs( - TEST_NAMESPACE, std::vector<PrefetchURL>(1, prefetch_url)); + kTestNamespace, std::vector<PrefetchURL>(1, prefetch_url)); EXPECT_FALSE(dispatcher_task_queue()->HasRunningTask()); // Do nothing with a new background task.
diff --git a/components/offline_pages/core/prefetch/prefetch_downloader_unittest.cc b/components/offline_pages/core/prefetch/prefetch_downloader_unittest.cc index 9823617..1befed2 100644 --- a/components/offline_pages/core/prefetch/prefetch_downloader_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_downloader_unittest.cc
@@ -141,16 +141,23 @@ task_runner_handle_(task_runner_) {} void SetUp() override { + prefetch_service_taco_.reset(new PrefetchServiceTestTaco); + auto downloader = base::MakeUnique<PrefetchDownloader>(&download_service_, kTestChannel); download_service_.set_prefetch_downloader(downloader.get()); - prefetch_service_taco_.SetPrefetchDownloader(std::move(downloader)); + prefetch_service_taco_->SetPrefetchDownloader(std::move(downloader)); - prefetch_service_taco_.CreatePrefetchService(); + prefetch_service_taco_->CreatePrefetchService(); GetPrefetchDownloader()->SetCompletedCallback(base::Bind( &PrefetchDownloaderTest::OnDownloadCompleted, base::Unretained(this))); } + void TearDown() override { + prefetch_service_taco_.reset(); + PumpLoop(); + } + void SetDownloadServiceReady(bool ready) { download_service_.set_ready(ready); if (ready) @@ -184,13 +191,13 @@ } PrefetchDownloader* GetPrefetchDownloader() const { - return prefetch_service_taco_.prefetch_service()->GetPrefetchDownloader(); + return prefetch_service_taco_->prefetch_service()->GetPrefetchDownloader(); } scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; download::TestDownloadService download_service_; - PrefetchServiceTestTaco prefetch_service_taco_; + std::unique_ptr<PrefetchServiceTestTaco> prefetch_service_taco_; std::vector<PrefetchDownloadResult> completed_downloads_; }; @@ -209,6 +216,7 @@ std::string alt_value; EXPECT_TRUE(net::GetValueForKeyInQuery(download_url, "alt", &alt_value)); EXPECT_EQ("media", alt_value); + PumpLoop(); } TEST_F(PrefetchDownloaderTest, StartDownloadBeforeServiceReady) {
diff --git a/components/offline_pages/core/prefetch/prefetch_gcm_app_handler_unittest.cc b/components/offline_pages/core/prefetch/prefetch_gcm_app_handler_unittest.cc index 04f19b9a..fe969a8 100644 --- a/components/offline_pages/core/prefetch/prefetch_gcm_app_handler_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_gcm_app_handler_unittest.cc
@@ -38,21 +38,29 @@ public: PrefetchGCMAppHandlerTest() : task_runner_(new base::TestSimpleTaskRunner), - task_runner_handle_(task_runner_) { + task_runner_handle_(task_runner_) {} + + void SetUp() override { auto dispatcher = base::MakeUnique<TestPrefetchDispatcher>(); + test_dispatcher_ = dispatcher.get(); auto token_factory = base::MakeUnique<TestTokenFactory>(); token_factory_ = token_factory.get(); auto gcm_app_handler = base::MakeUnique<PrefetchGCMAppHandler>(std::move(token_factory)); - - test_dispatcher_ = dispatcher.get(); handler_ = gcm_app_handler.get(); - prefetch_service_taco_.SetPrefetchGCMHandler(std::move(gcm_app_handler)); - prefetch_service_taco_.SetPrefetchDispatcher(std::move(dispatcher)); - prefetch_service_taco_.CreatePrefetchService(); + prefetch_service_taco_.reset(new PrefetchServiceTestTaco); + prefetch_service_taco_->SetPrefetchGCMHandler(std::move(gcm_app_handler)); + prefetch_service_taco_->SetPrefetchDispatcher(std::move(dispatcher)); + prefetch_service_taco_->CreatePrefetchService(); + } + + void TearDown() override { + // Ensures that the store is properly disposed off. + prefetch_service_taco_.reset(); + task_runner_->RunUntilIdle(); } TestPrefetchDispatcher* dispatcher() { return test_dispatcher_; } @@ -62,7 +70,8 @@ private: scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; - PrefetchServiceTestTaco prefetch_service_taco_; + std::unique_ptr<PrefetchServiceTestTaco> prefetch_service_taco_; + // Owned by the taco. TestPrefetchDispatcher* test_dispatcher_; // Owned by the taco.
diff --git a/components/offline_pages/core/prefetch/prefetch_item.cc b/components/offline_pages/core/prefetch/prefetch_item.cc index 3c435bb2..375bf09 100644 --- a/components/offline_pages/core/prefetch/prefetch_item.cc +++ b/components/offline_pages/core/prefetch/prefetch_item.cc
@@ -13,9 +13,9 @@ PrefetchItem::~PrefetchItem(){}; bool PrefetchItem::operator==(const PrefetchItem& other) const { - return guid == other.guid && client_id == other.client_id && - state == other.state && url == other.url && - final_archived_url == other.final_archived_url && + return offline_id == other.offline_id && guid == other.guid && + client_id == other.client_id && state == other.state && + url == other.url && final_archived_url == other.final_archived_url && request_archive_attempt_count == other.request_archive_attempt_count && operation_name == other.operation_name && archive_body_name == other.archive_body_name &&
diff --git a/components/offline_pages/core/prefetch/prefetch_item.h b/components/offline_pages/core/prefetch/prefetch_item.h index b6b001a..ad22a92 100644 --- a/components/offline_pages/core/prefetch/prefetch_item.h +++ b/components/offline_pages/core/prefetch/prefetch_item.h
@@ -28,6 +28,10 @@ bool operator==(const PrefetchItem& other) const; bool operator!=(const PrefetchItem& other) const; + // Primary key that stays consistent between prefetch item, request and + // offline page. + int64_t offline_id = 0; + // Primary key/ID for this prefetch item (See |base::GenerateGUID()|). This // value will be reused when communicating with other systems accepting GUID // identifiers for operations linked to this item.
diff --git a/components/offline_pages/core/prefetch/prefetch_item_unittest.cc b/components/offline_pages/core/prefetch/prefetch_item_unittest.cc index e5710ea..3778281 100644 --- a/components/offline_pages/core/prefetch/prefetch_item_unittest.cc +++ b/components/offline_pages/core/prefetch/prefetch_item_unittest.cc
@@ -16,6 +16,11 @@ EXPECT_EQ(item1, PrefetchItem()); EXPECT_EQ(item1, PrefetchItem(item1)); + item1.offline_id = 77L; + EXPECT_NE(item1, PrefetchItem()); + EXPECT_EQ(item1, PrefetchItem(item1)); + item1 = PrefetchItem(); + item1.guid = "A"; EXPECT_NE(item1, PrefetchItem()); EXPECT_EQ(item1, PrefetchItem(item1));
diff --git a/components/offline_pages/core/prefetch/prefetch_service.h b/components/offline_pages/core/prefetch/prefetch_service.h index 10e7105..eb196b4 100644 --- a/components/offline_pages/core/prefetch/prefetch_service.h +++ b/components/offline_pages/core/prefetch/prefetch_service.h
@@ -14,6 +14,7 @@ class PrefetchDownloader; class PrefetchGCMHandler; class PrefetchNetworkRequestFactory; +class PrefetchStore; class SuggestedArticlesObserver; // Main class and entry point for the Offline Pages Prefetching feature, that @@ -33,6 +34,7 @@ virtual PrefetchGCMHandler* GetPrefetchGCMHandler() = 0; virtual PrefetchNetworkRequestFactory* GetPrefetchNetworkRequestFactory() = 0; virtual PrefetchDownloader* GetPrefetchDownloader() = 0; + virtual PrefetchStore* GetPrefetchStore() = 0; // May be |nullptr| in tests. The PrefetchService does not depend on the // SuggestedArticlesObserver, it merely owns it for lifetime purposes.
diff --git a/components/offline_pages/core/prefetch/prefetch_service_impl.cc b/components/offline_pages/core/prefetch/prefetch_service_impl.cc index 478d4109..b255451 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_impl.cc +++ b/components/offline_pages/core/prefetch/prefetch_service_impl.cc
@@ -13,6 +13,7 @@ #include "components/offline_pages/core/prefetch/prefetch_downloader.h" #include "components/offline_pages/core/prefetch/prefetch_gcm_handler.h" #include "components/offline_pages/core/prefetch/prefetch_network_request_factory.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" #include "components/offline_pages/core/prefetch/suggested_articles_observer.h" namespace offline_pages { @@ -22,12 +23,14 @@ std::unique_ptr<PrefetchDispatcher> dispatcher, std::unique_ptr<PrefetchGCMHandler> gcm_handler, std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory, + std::unique_ptr<PrefetchStore> prefetch_store, std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer, std::unique_ptr<PrefetchDownloader> prefetch_downloader) : offline_metrics_collector_(std::move(offline_metrics_collector)), prefetch_dispatcher_(std::move(dispatcher)), prefetch_gcm_handler_(std::move(gcm_handler)), network_request_factory_(std::move(network_request_factory)), + prefetch_store_(std::move(prefetch_store)), suggested_articles_observer_(std::move(suggested_articles_observer)), prefetch_downloader_(std::move(prefetch_downloader)) { prefetch_dispatcher_->SetService(this); @@ -56,6 +59,10 @@ return network_request_factory_.get(); } +PrefetchStore* PrefetchServiceImpl::GetPrefetchStore() { + return prefetch_store_.get(); +} + SuggestedArticlesObserver* PrefetchServiceImpl::GetSuggestedArticlesObserver() { return suggested_articles_observer_.get(); }
diff --git a/components/offline_pages/core/prefetch/prefetch_service_impl.h b/components/offline_pages/core/prefetch/prefetch_service_impl.h index 98e5d61..df8a54b 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_impl.h +++ b/components/offline_pages/core/prefetch/prefetch_service_impl.h
@@ -13,12 +13,6 @@ #include "components/offline_pages/core/prefetch/prefetch_types.h" namespace offline_pages { -class OfflineMetricsCollector; -class PrefetchDispatcher; -class PrefetchDownloader; -class PrefetchGCMHandler; -class PrefetchNetworkRequestFactory; -class SuggestedArticlesObserver; class PrefetchServiceImpl : public PrefetchService { public: @@ -27,6 +21,7 @@ std::unique_ptr<PrefetchDispatcher> dispatcher, std::unique_ptr<PrefetchGCMHandler> gcm_handler, std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory, + std::unique_ptr<PrefetchStore> prefetch_store, std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer, std::unique_ptr<PrefetchDownloader> prefetch_downloader); ~PrefetchServiceImpl() override; @@ -36,6 +31,7 @@ PrefetchDispatcher* GetPrefetchDispatcher() override; PrefetchGCMHandler* GetPrefetchGCMHandler() override; PrefetchNetworkRequestFactory* GetPrefetchNetworkRequestFactory() override; + PrefetchStore* GetPrefetchStore() override; SuggestedArticlesObserver* GetSuggestedArticlesObserver() override; OfflineEventLogger* GetLogger() override; PrefetchDownloader* GetPrefetchDownloader() override; @@ -53,6 +49,7 @@ std::unique_ptr<PrefetchDispatcher> prefetch_dispatcher_; std::unique_ptr<PrefetchGCMHandler> prefetch_gcm_handler_; std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory_; + std::unique_ptr<PrefetchStore> prefetch_store_; std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer_; std::unique_ptr<PrefetchDownloader> prefetch_downloader_;
diff --git a/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc index e74c98a..6296a2e 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc +++ b/components/offline_pages/core/prefetch/prefetch_service_test_taco.cc
@@ -13,6 +13,8 @@ #include "components/offline_pages/core/prefetch/prefetch_downloader.h" #include "components/offline_pages/core/prefetch/prefetch_gcm_handler.h" #include "components/offline_pages/core/prefetch/prefetch_service_impl.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" #include "components/offline_pages/core/prefetch/suggested_articles_observer.h" #include "components/offline_pages/core/prefetch/test_offline_metrics_collector.h" #include "components/offline_pages/core/prefetch/test_prefetch_dispatcher.h" @@ -32,6 +34,10 @@ network_request_factory_ = base::MakeUnique<TestPrefetchNetworkRequestFactory>(); + PrefetchStoreTestUtil store_test_util; + store_test_util.BuildStoreInMemory(); + prefetch_store_sql_ = store_test_util.ReleaseStore(); + suggested_articles_observer_ = base::MakeUnique<SuggestedArticlesObserver>(); prefetch_downloader_ = base::WrapUnique(new PrefetchDownloader(kTestChannel)); // This sets up the testing articles as an empty vector, we can ignore the @@ -65,6 +71,12 @@ network_request_factory_ = std::move(network_request_factory); } +void PrefetchServiceTestTaco::SetPrefetchStoreSql( + std::unique_ptr<PrefetchStore> prefetch_store_sql) { + CHECK(!prefetch_service_); + prefetch_store_sql_ = std::move(prefetch_store_sql); +} + void PrefetchServiceTestTaco::SetSuggestedArticlesObserver( std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer) { CHECK(!prefetch_service_); @@ -79,12 +91,14 @@ void PrefetchServiceTestTaco::CreatePrefetchService() { CHECK(metrics_collector_ && dispatcher_ && gcm_handler_ && - suggested_articles_observer_ && network_request_factory_ && - prefetch_downloader_); + network_request_factory_ && prefetch_store_sql_ && + suggested_articles_observer_ && prefetch_downloader_); + prefetch_service_ = base::MakeUnique<PrefetchServiceImpl>( std::move(metrics_collector_), std::move(dispatcher_), std::move(gcm_handler_), std::move(network_request_factory_), - std::move(suggested_articles_observer_), std::move(prefetch_downloader_)); + std::move(prefetch_store_sql_), std::move(suggested_articles_observer_), + std::move(prefetch_downloader_)); } std::unique_ptr<PrefetchService>
diff --git a/components/offline_pages/core/prefetch/prefetch_service_test_taco.h b/components/offline_pages/core/prefetch/prefetch_service_test_taco.h index aa56544..d4db9a1 100644 --- a/components/offline_pages/core/prefetch/prefetch_service_test_taco.h +++ b/components/offline_pages/core/prefetch/prefetch_service_test_taco.h
@@ -18,6 +18,7 @@ class PrefetchGCMHandler; class PrefetchService; class PrefetchNetworkRequestFactory; +class PrefetchStore; class SuggestedArticlesObserver; // The taco class acts as a wrapper around the prefetch service making @@ -43,6 +44,7 @@ // Default type: TestNetworkRequestFactory. void SetPrefetchNetworkRequestFactory( std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory); + void SetPrefetchStoreSql(std::unique_ptr<PrefetchStore> prefetch_store_sql); // Defaults to SuggestedArticlesObserver. Initializes the testing suggestions // by default, so no ContentSuggestionsService is required.. void SetSuggestedArticlesObserver( @@ -70,6 +72,7 @@ std::unique_ptr<PrefetchDispatcher> dispatcher_; std::unique_ptr<PrefetchGCMHandler> gcm_handler_; std::unique_ptr<PrefetchNetworkRequestFactory> network_request_factory_; + std::unique_ptr<PrefetchStore> prefetch_store_sql_; std::unique_ptr<SuggestedArticlesObserver> suggested_articles_observer_; std::unique_ptr<PrefetchDownloader> prefetch_downloader_;
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store.cc b/components/offline_pages/core/prefetch/store/prefetch_store.cc new file mode 100644 index 0000000..f6cecd57 --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store.cc
@@ -0,0 +1,173 @@ +// 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 "components/offline_pages/core/prefetch/store/prefetch_store.h" + +#include "base/bind.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/metrics/histogram_macros.h" +#include "base/sequenced_task_runner.h" +#include "base/task_runner_util.h" +#include "base/threading/thread_task_runner_handle.h" +#include "components/offline_pages/core/offline_store_types.h" +#include "components/offline_pages/core/prefetch/prefetch_item.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_utils.h" +#include "sql/connection.h" +#include "sql/meta_table.h" +#include "sql/statement.h" +#include "sql/transaction.h" + +namespace offline_pages { +namespace { + +// Name of the table with prefetch items. +const char kPrefetchItemsTableName[] = "prefetch_items"; +const char kPrefetchStoreFileName[] = "PrefetchStore.db"; + +const int kCurrentVersion = 1; +const int kCompatibleVersion = 1; + +using InitializeCallback = + base::Callback<void(InitializationStatus, + std::unique_ptr<sql::Connection>)>; + +bool CreatePrefetchItemsTable(sql::Connection* db) { + static const char kSql[] = + "CREATE TABLE prefetch_items" + "(offline_id INTEGER PRIMARY KEY NOT NULL," + " state INTEGER NOT NULL DEFAULT 0," + " request_archive_attempt_count INTEGER NOT NULL DEFAULT 0," + " archive_body_length INTEGER_NOT_NULL DEFAULT -1," + " creation_time INTEGER NOT NULL," + " freshness_time INTEGER NOT NULL," + " error_code INTEGER NOT NULL DEFAULT 0," + " guid VARCHAR NOT NULL DEFAULT ''," + " client_namespace VARCHAR NOT NULL DEFAULT ''," + " client_id VARCHAR NOT NULL DEFAULT ''," + " requested_url VARCHAR NOT NULL DEFAULT ''," + " final_archived_url VARCHAR NOT NULL DEFAULT ''," + " operation_name VARCHAR NOT NULL DEFAULT ''," + " archive_body_name VARCHAR NOT NULL DEFAULT ''" + ")"; + return db->Execute(kSql); +} + +bool CreateSchema(sql::Connection* db) { + // If you create a transaction but don't Commit() it is automatically + // rolled back by its destructor when it falls out of scope. + sql::Transaction transaction(db); + if (!transaction.Begin()) + return false; + + if (!db->DoesTableExist(kPrefetchItemsTableName)) { + if (!CreatePrefetchItemsTable(db)) + return false; + } + + sql::MetaTable meta_table; + meta_table.Init(db, kCurrentVersion, kCompatibleVersion); + + // This would be a great place to add indices when we need them. + return transaction.Commit(); +} + +bool PrepareDirectory(const base::FilePath& path) { + base::File::Error error = base::File::FILE_OK; + if (!base::DirectoryExists(path.DirName())) { + if (!base::CreateDirectoryAndGetError(path.DirName(), &error)) { + LOG(ERROR) << "Failed to create prefetch db directory: " + << base::File::ErrorToString(error); + return false; + } + } + return true; +} + +// TODO(fgorski): This function and this part of the system in general could +// benefit from a better status code reportable through UMA to better capture +// the reason for failure, aiding the process of repeated attempts to +// open/initialize the database. +bool InitializeSync(sql::Connection* db, + const base::FilePath& path, + bool in_memory) { + // These values are default. + db->set_page_size(4096); + db->set_cache_size(500); + db->set_histogram_tag("PrefetchStore"); + db->set_exclusive_locking(); + + if (!in_memory && !PrepareDirectory(path)) + return false; + + bool open_db_result = false; + if (in_memory) + open_db_result = db->OpenInMemory(); + else + open_db_result = db->Open(path); + + if (!open_db_result) { + LOG(ERROR) << "Failed to open database, in memory: " << in_memory; + return false; + } + db->Preload(); + + return CreateSchema(db); +} + +} // namespace + +PrefetchStore::PrefetchStore( + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner) + : blocking_task_runner_(std::move(blocking_task_runner)), + in_memory_(true), + db_(new sql::Connection, + base::OnTaskRunnerDeleter(blocking_task_runner_)), + initialization_status_(InitializationStatus::NOT_INITIALIZED), + weak_ptr_factory_(this) {} + +PrefetchStore::PrefetchStore( + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner, + const base::FilePath& path) + : blocking_task_runner_(std::move(blocking_task_runner)), + db_file_path_(path.AppendASCII(kPrefetchStoreFileName)), + in_memory_(false), + db_(new sql::Connection, + base::OnTaskRunnerDeleter(blocking_task_runner_)), + initialization_status_(InitializationStatus::NOT_INITIALIZED), + weak_ptr_factory_(this) {} + +PrefetchStore::~PrefetchStore() {} + +void PrefetchStore::Initialize(base::OnceClosure pending_command) { + DCHECK_EQ(initialization_status_, InitializationStatus::NOT_INITIALIZED); + + initialization_status_ = InitializationStatus::INITIALIZING; + base::PostTaskAndReplyWithResult( + blocking_task_runner_.get(), FROM_HERE, + base::BindOnce(&InitializeSync, db_.get(), db_file_path_, in_memory_), + base::BindOnce(&PrefetchStore::OnInitializeDone, + weak_ptr_factory_.GetWeakPtr(), + std::move(pending_command))); +} + +void PrefetchStore::OnInitializeDone(base::OnceClosure pending_command, + bool success) { + DCHECK_EQ(initialization_status_, InitializationStatus::INITIALIZING); + initialization_status_ = + success ? InitializationStatus::SUCCESS : InitializationStatus::FAILURE; + + CHECK(!pending_command.is_null()); + std::move(pending_command).Run(); + + // Once pending commands are empty, we get back to NOT_INITIALIZED state, to + // make it possible to retry initialization next time a DB operation is + // attempted. + if (initialization_status_ == InitializationStatus::FAILURE) + initialization_status_ = InitializationStatus::NOT_INITIALIZED; +} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store.h b/components/offline_pages/core/prefetch/store/prefetch_store.h new file mode 100644 index 0000000..15929a6 --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store.h
@@ -0,0 +1,122 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_H_ + +#include <memory> + +#include "base/bind.h" +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/location.h" +#include "base/memory/weak_ptr.h" +#include "base/sequenced_task_runner.h" +#include "base/task_runner_util.h" + +namespace sql { +class Connection; +} + +namespace offline_pages { + +enum class InitializationStatus { + NOT_INITIALIZED, + INITIALIZING, + SUCCESS, + FAILURE, +}; + +// PrefetchStore is a front end to SQLite store hosting prefetch related +// items. +// +// The store controls the pointer to the SQLite database and only makes it +// available to the |RunCallback| of the |Execute| method on the blocking +// thread. +// +// Store has a set of auxiliary functions meant to be used on the blocking +// thread. They can be found in prefetch_store_sql_utils file. +class PrefetchStore { + public: + // Definition of the callback that is going to run the core of the command in + // the |Execute| method. + template <typename T> + using RunCallback = base::OnceCallback<T(sql::Connection*)>; + + // Definition of the callback used to pass the result back to the caller of + // |Execute| method. + template <typename T> + using ResultCallback = base::OnceCallback<void(T)>; + + explicit PrefetchStore( + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner); + PrefetchStore(scoped_refptr<base::SequencedTaskRunner> blocking_task_runner, + const base::FilePath& database_dir); + ~PrefetchStore(); + + // Executes a |run_callback| on SQL store on the blocking thread, and posts + // its result back to calling thread through |result_callback|. The work will + // be postponed if the store is in NOT_INITIALIZED or INITIALIZING, in which + // case the work will have to wait until initialization is completed. Calling + // |Execute| when store is NOT_INITIALIZED will cause the store initialization + // to start. + // Store initialization status needs to be SUCCESS for test task to run, or + // FAILURE, in which case the |db| pointer passed to |run_callback| will be + // null and such case should be gracefully handled. + template <typename T> + void Execute(RunCallback<T> run_callback, ResultCallback<T> result_callback) { + CHECK_NE(initialization_status_, InitializationStatus::INITIALIZING); + + if (initialization_status_ == InitializationStatus::NOT_INITIALIZED) { + Initialize(base::BindOnce( + &PrefetchStore::Execute<T>, weak_ptr_factory_.GetWeakPtr(), + std::move(run_callback), std::move(result_callback))); + return; + } + + sql::Connection* db = + initialization_status_ == InitializationStatus::SUCCESS ? db_.get() + : nullptr; + base::PostTaskAndReplyWithResult( + blocking_task_runner_.get(), FROM_HERE, + base::BindOnce(std::move(run_callback), db), + std::move(result_callback)); + } + + // Gets the initialization status of the store. + InitializationStatus initialization_status() const { + return initialization_status_; + } + + private: + // Used internally to initialize connection. + void Initialize(base::OnceClosure pending_command); + + // Used to conclude opening/resetting DB connection. + void OnInitializeDone(base::OnceClosure pending_command, bool success); + + // Background thread where all SQL access should be run. + scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; + + // Path to the database on disk. + base::FilePath db_file_path_; + + // Only open the store in memory. Used for testing. + bool in_memory_; + + // Database connection. + std::unique_ptr<sql::Connection, base::OnTaskRunnerDeleter> db_; + + // Initialization status of the store. + InitializationStatus initialization_status_; + + // Weak pointer to control the callback. + base::WeakPtrFactory<PrefetchStore> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(PrefetchStore); +}; + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_H_
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store_test_util.cc b/components/offline_pages/core/prefetch/store/prefetch_store_test_util.cc new file mode 100644 index 0000000..b3fb7a4 --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store_test_util.cc
@@ -0,0 +1,90 @@ +// 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 "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" + +#include "base/bind.h" +#include "base/threading/thread_task_runner_handle.h" +#include "components/offline_pages/core/prefetch/prefetch_types.h" +#include "sql/connection.h" +#include "sql/statement.h" +#include "url/gurl.h" + +namespace offline_pages { +namespace { + +int CountPrefetchItemsSync(sql::Connection* db) { + // Not starting transaction as this is a single read. + static const char kSql[] = "SELECT COUNT(offline_id) FROM prefetch_items"; + sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + if (statement.Step()) + return statement.ColumnInt(0); + + return kStoreCommandFailed; +} + +int UpdateItemsStateSync(const std::string& name_space, + const std::string& url, + PrefetchItemState state, + sql::Connection* db) { + static const char kSql[] = + "UPDATE prefetch_items" + " SET state = ?" + " WHERE client_namespace = ? AND requested_url = ?"; + + sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt(0, static_cast<int>(state)); + statement.BindString(1, name_space); + statement.BindString(2, url); + if (statement.Run()) + return db->GetLastChangeCount(); + + return kStoreCommandFailed; +} + +} // namespace + +PrefetchStoreTestUtil::PrefetchStoreTestUtil() {} + +PrefetchStoreTestUtil::~PrefetchStoreTestUtil() = default; + +void PrefetchStoreTestUtil::BuildStore() { + if (!temp_directory_.CreateUniqueTempDir()) + DVLOG(1) << "temp_directory_ not created"; + + store_.reset(new PrefetchStore(base::ThreadTaskRunnerHandle::Get(), + temp_directory_.GetPath())); +} + +void PrefetchStoreTestUtil::BuildStoreInMemory() { + store_.reset(new PrefetchStore(base::ThreadTaskRunnerHandle::Get())); +} + +std::unique_ptr<PrefetchStore> PrefetchStoreTestUtil::ReleaseStore() { + return std::move(store_); +} + +void PrefetchStoreTestUtil::DeleteStore() { + store_.reset(); + if (temp_directory_.IsValid()) { + if (!temp_directory_.Delete()) + DVLOG(1) << "temp_directory_ not created"; + } +} + +void PrefetchStoreTestUtil::CountPrefetchItems( + PrefetchStore::ResultCallback<int> result_callback) { + store_->Execute(base::BindOnce(&CountPrefetchItemsSync), + std::move(result_callback)); +} + +void PrefetchStoreTestUtil::ZombifyPrefetchItem( + const std::string& name_space, + const GURL& url, + PrefetchStore::ResultCallback<int> result_callback) { + store_->Execute(base::BindOnce(&UpdateItemsStateSync, name_space, url.spec(), + PrefetchItemState::ZOMBIE), + std::move(result_callback)); +} +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store_test_util.h b/components/offline_pages/core/prefetch/store/prefetch_store_test_util.h new file mode 100644 index 0000000..c330308a --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store_test_util.h
@@ -0,0 +1,54 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_TEST_UTIL_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_TEST_UTIL_H_ + +#include <memory> + +#include "base/callback_forward.h" +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store.h" + +class GURL; + +namespace base { +class ScopedTempDir; +} // namespace base + +namespace offline_pages { +const int kStoreCommandFailed = -1; + +class PrefetchStoreTestUtil { + public: + PrefetchStoreTestUtil(); + ~PrefetchStoreTestUtil(); + + void BuildStore(); + void BuildStoreInMemory(); + + void CountPrefetchItems(PrefetchStore::ResultCallback<int> result_callback); + + void ZombifyPrefetchItem(const std::string& name_space, + const GURL& url, + PrefetchStore::ResultCallback<int> reuslt_callback); + + // Releases the ownership of currently controlled store. + std::unique_ptr<PrefetchStore> ReleaseStore(); + + void DeleteStore(); + + PrefetchStore* store() { return store_.get(); } + + private: + base::ScopedTempDir temp_directory_; + std::unique_ptr<PrefetchStore> store_; + + DISALLOW_COPY_AND_ASSIGN(PrefetchStoreTestUtil); +}; + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_TEST_UTIL_H_
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store_unittest.cc b/components/offline_pages/core/prefetch/store/prefetch_store_unittest.cc new file mode 100644 index 0000000..a463fce --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store_unittest.cc
@@ -0,0 +1,66 @@ +// 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 "components/offline_pages/core/prefetch/store/prefetch_store.h" + +#include "base/test/test_simple_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" +#include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" +#include "sql/connection.h" +#include "sql/statement.h" +#include "sql/transaction.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace offline_pages { +namespace { + +int CountPrefetchItems(sql::Connection* db) { + // Not starting transaction as this is a single read. + static const char kSql[] = "SELECT COUNT(offline_id) FROM prefetch_items"; + sql::Statement statement(db->GetUniqueStatement(kSql)); + if (statement.Step()) + return statement.ColumnInt(0); + + return -1; +} + +void CountPrefetchItemsResult(int expected_count, int actual_count) { + EXPECT_EQ(expected_count, actual_count); +} + +} // namespace + +class PrefetchStoreTest : public testing::Test { + public: + PrefetchStoreTest(); + ~PrefetchStoreTest() override = default; + + void SetUp() override { store_test_util_.BuildStoreInMemory(); } + + void TearDown() override { + store_test_util_.DeleteStore(); + PumpLoop(); + } + + PrefetchStore* store() { return store_test_util_.store(); } + + void PumpLoop() { task_runner_->RunUntilIdle(); } + + private: + PrefetchStoreTestUtil store_test_util_; + scoped_refptr<base::TestSimpleTaskRunner> task_runner_; + base::ThreadTaskRunnerHandle task_runner_handle_; +}; + +PrefetchStoreTest::PrefetchStoreTest() + : task_runner_(new base::TestSimpleTaskRunner), + task_runner_handle_(task_runner_) {} + +TEST_F(PrefetchStoreTest, InitializeStore) { + store()->Execute<int>(base::BindOnce(&CountPrefetchItems), + base::BindOnce(&CountPrefetchItemsResult, 0)); + PumpLoop(); +} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store_utils.cc b/components/offline_pages/core/prefetch/store/prefetch_store_utils.cc new file mode 100644 index 0000000..e5c28d90 --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store_utils.cc
@@ -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. + +#include "components/offline_pages/core/prefetch/store/prefetch_store_utils.h" + +#include <limits> + +#include "base/rand_util.h" +#include "components/offline_pages/core/prefetch/prefetch_item.h" +#include "sql/connection.h" +#include "sql/statement.h" + +namespace offline_pages { + +int64_t GenerateOfflineId() { + return base::RandGenerator(std::numeric_limits<int64_t>::max()) + 1; +} + +bool DeletePrefetchItemByOfflineIdSync(sql::Connection* db, + int64_t offline_id) { + DCHECK(db); + static const char kSql[] = "DELETE FROM prefetch_items WHERE offline_id=?"; + sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); + statement.BindInt64(0, offline_id); + return statement.Run(); +} + +} // namespace offline_pages
diff --git a/components/offline_pages/core/prefetch/store/prefetch_store_utils.h b/components/offline_pages/core/prefetch/store/prefetch_store_utils.h new file mode 100644 index 0000000..d47696b --- /dev/null +++ b/components/offline_pages/core/prefetch/store/prefetch_store_utils.h
@@ -0,0 +1,25 @@ +// 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 COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_UTILS_H_ +#define COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_UTILS_H_ + +#include <stdint.h> + +namespace sql { +class Connection; +} // namespace sql + +namespace offline_pages { + +// Creates an offline ID for the prefetch item. +int64_t GenerateOfflineId(); + +// Deletes a prefetch item by its offline ID. Returns whether it was the item +// was successfully deleted. +bool DeletePrefetchItemByOfflineIdSync(sql::Connection* db, int64_t offline_id); + +} // namespace offline_pages + +#endif // COMPONENTS_OFFLINE_PAGES_CORE_PREFETCH_STORE_PREFETCH_STORE_UTILS_H_
diff --git a/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc b/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc index 5abea6c..a243c2e 100644 --- a/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc +++ b/components/offline_pages/core/prefetch/suggested_articles_observer_unittest.cc
@@ -36,17 +36,26 @@ public: OfflinePageSuggestedArticlesObserverTest() : task_runner_(new base::TestSimpleTaskRunner), - task_runner_handle_(task_runner_) { + task_runner_handle_(task_runner_) {} + + void SetUp() override { + prefetch_service_test_taco_ = base::MakeUnique<PrefetchServiceTestTaco>(); test_prefetch_dispatcher_ = new TestPrefetchDispatcher(); - prefetch_service_test_taco_.SetPrefetchDispatcher( + prefetch_service_test_taco_->SetPrefetchDispatcher( base::WrapUnique(test_prefetch_dispatcher_)); - prefetch_service_test_taco_.SetSuggestedArticlesObserver( + prefetch_service_test_taco_->SetSuggestedArticlesObserver( base::MakeUnique<SuggestedArticlesObserver>()); - prefetch_service_test_taco_.CreatePrefetchService(); + prefetch_service_test_taco_->CreatePrefetchService(); + } + + void TearDown() override { + // Ensure the store can be properly disposed off. + prefetch_service_test_taco_.reset(); + task_runner_->RunUntilIdle(); } SuggestedArticlesObserver* observer() { - return prefetch_service_test_taco_.prefetch_service() + return prefetch_service_test_taco_->prefetch_service() ->GetSuggestedArticlesObserver(); } @@ -61,7 +70,7 @@ private: scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; - PrefetchServiceTestTaco prefetch_service_test_taco_; + std::unique_ptr<PrefetchServiceTestTaco> prefetch_service_test_taco_; // Owned by the PrefetchServiceTestTaco. TestPrefetchDispatcher* test_prefetch_dispatcher_;
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index 5837c8d0..b020beb3 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -497,6 +497,11 @@ omnibox::kUIExperimentHideSuggestionUrlScheme)) { format_types |= url_formatter::kFormatUrlExperimentalOmitHTTPS; } + + if (base::FeatureList::IsEnabled( + omnibox::kUIExperimentElideSuggestionUrlAfterHost)) { + format_types |= url_formatter::kFormatUrlExperimentalElideAfterHost; + } return format_types; }
diff --git a/components/omnibox/browser/autocomplete_match_unittest.cc b/components/omnibox/browser/autocomplete_match_unittest.cc index e6627425..ad9aad6 100644 --- a/components/omnibox/browser/autocomplete_match_unittest.cc +++ b/components/omnibox/browser/autocomplete_match_unittest.cc
@@ -115,44 +115,58 @@ struct FormatUrlTestData { const std::string url; bool trim_scheme; - const std::string expected_result; + const wchar_t* expected_result; void Validate() { SCOPED_TRACE(testing::Message() << " url= " << url << " trim_scheme=" << trim_scheme << " expected_result=" << expected_result); auto format_types = AutocompleteMatch::GetFormatTypes(trim_scheme); - EXPECT_EQ(expected_result, - base::UTF16ToASCII(url_formatter::FormatUrl( - GURL(url), format_types, net::UnescapeRule::SPACES, nullptr, - nullptr, nullptr))); + EXPECT_EQ(base::WideToUTF16(expected_result), + url_formatter::FormatUrl(GURL(url), format_types, + net::UnescapeRule::SPACES, nullptr, + nullptr, nullptr)); }; }; - // Sanity check that the trim_strings parameter works. FormatUrlTestData normal_cases[] = { - {"http://google.com", true, "google.com"}, - {"https://google.com", true, "https://google.com"}, - {"http://google.com", false, "http://google.com"}, - {"https://google.com", false, "https://google.com"}, + // Sanity check that the trim_scheme parameter works. + {"http://google.com", true, L"google.com"}, + {"https://google.com", true, L"https://google.com"}, + {"http://google.com", false, L"http://google.com"}, + {"https://google.com", false, L"https://google.com"}, + + // Test that paths are preserved in the default case. + {"http://google.com/foobar", true, L"google.com/foobar"}, }; for (FormatUrlTestData& test_case : normal_cases) test_case.Validate(); - // Test the hide-scheme feature flag. + // Test the hide-scheme feature flag with the trim_scheme parameter. std::unique_ptr<base::test::ScopedFeatureList> feature_list( new base::test::ScopedFeatureList); feature_list->InitAndEnableFeature( omnibox::kUIExperimentHideSuggestionUrlScheme); FormatUrlTestData omit_scheme_cases[] = { - {"http://google.com", true, "google.com"}, - {"https://google.com", true, "google.com"}, - {"http://google.com", false, "http://google.com"}, - {"https://google.com", false, "https://google.com"}, + {"http://google.com", true, L"google.com"}, + {"https://google.com", true, L"google.com"}, + {"http://google.com", false, L"http://google.com"}, + {"https://google.com", false, L"https://google.com"}, }; for (FormatUrlTestData& test_case : omit_scheme_cases) test_case.Validate(); + + // Test the elide-after-host feature flag. + feature_list.reset(new base::test::ScopedFeatureList); + feature_list->InitAndEnableFeature( + omnibox::kUIExperimentElideSuggestionUrlAfterHost); + FormatUrlTestData hide_path_cases[] = { + {"http://google.com/foobar", true, L"google.com/\x2026\x0000"}, + {"http://google.com/foobar", false, L"http://google.com/\x2026\x0000"}, + }; + for (FormatUrlTestData& test_case : hide_path_cases) + test_case.Validate(); } TEST(AutocompleteMatchTest, SupportsDeletion) {
diff --git a/components/omnibox/browser/omnibox_field_trial.cc b/components/omnibox/browser/omnibox_field_trial.cc index 49596e8..6357182 100644 --- a/components/omnibox/browser/omnibox_field_trial.cc +++ b/components/omnibox/browser/omnibox_field_trial.cc
@@ -103,9 +103,10 @@ "OmniboxUIExperimentMaxAutocompleteMatches", base::FEATURE_DISABLED_BY_DEFAULT}; -// Feature used for hiding the suggestion URL path as a UI experiment. -const base::Feature kUIExperimentHideSuggestionUrlPath{ - "OmniboxUIExperimentHideSuggestionUrlPath", +// Feature used for eliding the suggestion URL after the host as a UI +// experiment. +const base::Feature kUIExperimentElideSuggestionUrlAfterHost{ + "OmniboxUIExperimentElideSuggestionUrlAfterHost", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used for hiding the suggestion URL scheme as a UI experiment.
diff --git a/components/omnibox/browser/omnibox_field_trial.h b/components/omnibox/browser/omnibox_field_trial.h index a9d0f7ee..43a8c60a 100644 --- a/components/omnibox/browser/omnibox_field_trial.h +++ b/components/omnibox/browser/omnibox_field_trial.h
@@ -35,7 +35,7 @@ extern const base::Feature kZeroSuggestRedirectToChrome; extern const base::Feature kZeroSuggestSwapTitleAndUrl; extern const base::Feature kDisplayTitleForCurrentUrl; -extern const base::Feature kUIExperimentHideSuggestionUrlPath; +extern const base::Feature kUIExperimentElideSuggestionUrlAfterHost; extern const base::Feature kUIExperimentHideSuggestionUrlScheme; extern const base::Feature kUIExperimentHideSuggestionUrlTrivialSubdomains; extern const base::Feature kUIExperimentMaxAutocompleteMatches;
diff --git a/components/os_crypt/BUILD.gn b/components/os_crypt/BUILD.gn index e91c681..81eb6e3 100644 --- a/components/os_crypt/BUILD.gn +++ b/components/os_crypt/BUILD.gn
@@ -160,7 +160,10 @@ ] if (is_desktop_linux) { - sources += [ "os_crypt_linux_unittest.cc" ] + sources += [ + "key_storage_util_linux_unittest.cc", + "os_crypt_linux_unittest.cc", + ] defines = [] if (use_gnome_keyring) {
diff --git a/components/os_crypt/key_storage_linux.cc b/components/os_crypt/key_storage_linux.cc index c8b1832..12c4a62 100644 --- a/components/os_crypt/key_storage_linux.cc +++ b/components/os_crypt/key_storage_linux.cc
@@ -5,6 +5,9 @@ #include "components/os_crypt/key_storage_linux.h" #include "base/environment.h" +#include "base/files/file.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/nix/xdg_util.h" @@ -37,6 +40,8 @@ std::string store; std::string product_name; scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner; + bool should_use_preference; + base::FilePath user_data_path; }; base::LazyInstance<Configuration>::DestructorAtExit g_config = @@ -62,14 +67,26 @@ } // static +void KeyStorageLinux::ShouldUsePreference(bool should_use_preference) { + g_config.Get().should_use_preference = should_use_preference; +} + +// static +void KeyStorageLinux::SetUserDataPath(const base::FilePath& path) { + g_config.Get().user_data_path = path; +} + +// static std::unique_ptr<KeyStorageLinux> KeyStorageLinux::CreateService() { #if defined(USE_LIBSECRET) || defined(USE_KEYRING) || defined(USE_KWALLET) // Select a backend. + bool use_backend = !g_config.Get().should_use_preference || + os_crypt::GetBackendUse(g_config.Get().user_data_path); std::unique_ptr<base::Environment> env(base::Environment::Create()); base::nix::DesktopEnvironment desktop_env = base::nix::GetDesktopEnvironment(env.get()); os_crypt::SelectedLinuxBackend selected_backend = - os_crypt::SelectBackend(g_config.Get().store, desktop_env); + os_crypt::SelectBackend(g_config.Get().store, use_backend, desktop_env); // Try initializing the selected backend. // In case of GNOME_ANY, prefer Libsecret @@ -117,6 +134,6 @@ // defined(USE_KWALLET) // The appropriate store was not available. - VLOG(1) << "OSCrypt could not initialize a backend."; + VLOG(1) << "OSCrypt did not initialize a backend."; return nullptr; }
diff --git a/components/os_crypt/key_storage_linux.h b/components/os_crypt/key_storage_linux.h index 394b6b3..310b40f 100644 --- a/components/os_crypt/key_storage_linux.h +++ b/components/os_crypt/key_storage_linux.h
@@ -12,6 +12,7 @@ #include "base/memory/ref_counted.h" namespace base { +class FilePath; class SingleThreadTaskRunner; } // namespace base @@ -34,6 +35,12 @@ static void SetMainThreadRunner( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner); + // Controls whether preference on using or ignoring backends is used. + static void ShouldUsePreference(bool should_use_preference); + + // Preferences are stored in a separate file in the user data directory. + static void SetUserDataPath(const base::FilePath& path); + // Tries to load the appropriate key storage. Returns null if none succeed. static std::unique_ptr<KeyStorageLinux> CreateService();
diff --git a/components/os_crypt/key_storage_util_linux.cc b/components/os_crypt/key_storage_util_linux.cc index 5be4252..2daf7b0 100644 --- a/components/os_crypt/key_storage_util_linux.cc +++ b/components/os_crypt/key_storage_util_linux.cc
@@ -4,12 +4,33 @@ #include "components/os_crypt/key_storage_util_linux.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" #include "base/logging.h" +namespace { + +// OSCrypt has a setting that determines whether a backend will be used. +// The presense of this file in the file system means that the backend +// should be ignored. It's absence means we should use the backend. +constexpr const char kPreferenceFileName[] = "Disable Local Encryption"; + +bool ReadBackendUse(const base::FilePath& user_data_dir, bool* use) { + if (user_data_dir.empty()) + return false; + base::FilePath pref_path = user_data_dir.Append(kPreferenceFileName); + *use = !base::PathExists(pref_path); + return true; +} + +} // namespace + namespace os_crypt { SelectedLinuxBackend SelectBackend(const std::string& type, + bool use_backend, base::nix::DesktopEnvironment desktop_env) { + // Explicitly requesting a store overrides other production logic. if (type == "kwallet") return SelectedLinuxBackend::KWALLET; if (type == "kwallet5") @@ -23,11 +44,14 @@ if (type == "basic") return SelectedLinuxBackend::BASIC_TEXT; + // Ignore the backends if requested to. + if (!use_backend) + return SelectedLinuxBackend::BASIC_TEXT; + + // Detect the store to use automatically. const char* name = base::nix::GetDesktopEnvironmentName(desktop_env); VLOG(1) << "Password storage detected desktop environment: " << (name ? name : "(unknown)"); - - // Detect the store to use automatically. switch (desktop_env) { case base::nix::DESKTOP_ENVIRONMENT_KDE4: return SelectedLinuxBackend::KWALLET; @@ -47,4 +71,21 @@ return SelectedLinuxBackend::BASIC_TEXT; } +bool WriteBackendUse(const base::FilePath& user_data_dir, bool use) { + if (user_data_dir.empty()) + return false; + base::FilePath pref_path = user_data_dir.Append(kPreferenceFileName); + if (use) + return base::DeleteFile(pref_path, false); + FILE* f = base::OpenFile(pref_path, "w"); + return f != nullptr && base::CloseFile(f); +} + +bool GetBackendUse(const base::FilePath& user_data_dir) { + bool setting; + if (ReadBackendUse(user_data_dir, &setting)) + return setting; + return true; +} + } // namespace os_crypt
diff --git a/components/os_crypt/key_storage_util_linux.h b/components/os_crypt/key_storage_util_linux.h index d5c04b6..f91bfc68 100644 --- a/components/os_crypt/key_storage_util_linux.h +++ b/components/os_crypt/key_storage_util_linux.h
@@ -9,6 +9,10 @@ #include "base/nix/xdg_util.h" +namespace base { +class FilePath; +} + namespace os_crypt { // The supported Linux backends for storing passwords. @@ -23,13 +27,22 @@ }; // Decide which backend to target. |type| is checked first. If it does not -// match a supported backend, |desktop_env| will be used to decide. +// match a supported backend and |use_backend| is true, |desktop_env| will be +// used to decide. // TODO(crbug/571003): This is exposed as a utility only for password manager to // use. It should be merged into key_storage_linux, once no longer needed in // password manager. SelectedLinuxBackend SelectBackend(const std::string& type, + bool use_backend, base::nix::DesktopEnvironment desktop_env); +// Set the setting that disables using OS-level encryption. If |use| is true, +// a backend will be used. +bool WriteBackendUse(const base::FilePath& user_data_dir, bool use); + +// Decide whether the backend should be used based on the setting. +bool GetBackendUse(const base::FilePath& user_data_dir); + } // namespace os_crypt #endif // COMPONENTS_OS_CRYPT_KEY_STORAGE_UTIL_LINUX_H_
diff --git a/components/os_crypt/key_storage_util_linux_unittest.cc b/components/os_crypt/key_storage_util_linux_unittest.cc new file mode 100644 index 0000000..4a03aaa --- /dev/null +++ b/components/os_crypt/key_storage_util_linux_unittest.cc
@@ -0,0 +1,112 @@ +// 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 "components/os_crypt/key_storage_util_linux.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/macros.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +using namespace os_crypt; + +class KeyStorageUtilLinuxPreferenceTest : public testing::Test { + public: + KeyStorageUtilLinuxPreferenceTest() = default; + ~KeyStorageUtilLinuxPreferenceTest() override = default; + + void SetUp() override { + ASSERT_TRUE(base::CreateNewTempDirectory("", &fake_user_data_dir_)); + } + + void TearDown() override { + ASSERT_TRUE(base::DeleteFile(fake_user_data_dir_, true)); + } + + protected: + base::FilePath fake_user_data_dir_; + + private: + DISALLOW_COPY_AND_ASSIGN(KeyStorageUtilLinuxPreferenceTest); +}; + +TEST_F(KeyStorageUtilLinuxPreferenceTest, FirstTimeDefaultsToTrue) { + EXPECT_TRUE(GetBackendUse(fake_user_data_dir_)); +} + +TEST_F(KeyStorageUtilLinuxPreferenceTest, SetToTrue) { + EXPECT_TRUE(WriteBackendUse(fake_user_data_dir_, true)); + EXPECT_TRUE(GetBackendUse(fake_user_data_dir_)); +} + +TEST_F(KeyStorageUtilLinuxPreferenceTest, SetToFalse) { + EXPECT_TRUE(WriteBackendUse(fake_user_data_dir_, false)); + EXPECT_FALSE(GetBackendUse(fake_user_data_dir_)); +} + +TEST_F(KeyStorageUtilLinuxPreferenceTest, MultipleWrites) { + EXPECT_TRUE(WriteBackendUse(fake_user_data_dir_, false)); + EXPECT_FALSE(GetBackendUse(fake_user_data_dir_)); + + EXPECT_TRUE(WriteBackendUse(fake_user_data_dir_, true)); + EXPECT_TRUE(GetBackendUse(fake_user_data_dir_)); + + EXPECT_TRUE(WriteBackendUse(fake_user_data_dir_, false)); + EXPECT_FALSE(GetBackendUse(fake_user_data_dir_)); +} + +class KeyStorageUtilLinuxTest : public testing::Test { + public: + KeyStorageUtilLinuxTest() = default; + ~KeyStorageUtilLinuxTest() override = default; + + void SetUp() override {} + + void TearDown() override {} + + private: + DISALLOW_COPY_AND_ASSIGN(KeyStorageUtilLinuxTest); +}; + +TEST_F(KeyStorageUtilLinuxTest, PasswordStoreFlagOverrides) { + SelectedLinuxBackend selected; + + selected = SelectBackend( + "basic", true, base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_GNOME); + EXPECT_EQ(selected, SelectedLinuxBackend::BASIC_TEXT); + + selected = + SelectBackend("gnome-libsecret", false, + base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE4); + EXPECT_EQ(selected, SelectedLinuxBackend::GNOME_LIBSECRET); + + selected = + SelectBackend("gnome-libsecret", true, + base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE4); + EXPECT_EQ(selected, SelectedLinuxBackend::GNOME_LIBSECRET); +} + +TEST_F(KeyStorageUtilLinuxTest, IgnoreBackends) { + SelectedLinuxBackend selected; + + selected = SelectBackend( + "", true, base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_GNOME); + EXPECT_EQ(selected, SelectedLinuxBackend::GNOME_ANY); + + selected = SelectBackend( + "", false, base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_GNOME); + EXPECT_EQ(selected, SelectedLinuxBackend::BASIC_TEXT); + + selected = SelectBackend( + "", true, base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE5); + EXPECT_EQ(selected, SelectedLinuxBackend::KWALLET5); + + selected = SelectBackend( + "", false, base::nix::DesktopEnvironment::DESKTOP_ENVIRONMENT_KDE5); + EXPECT_EQ(selected, SelectedLinuxBackend::BASIC_TEXT); +} + +} // namespace os_crypt
diff --git a/components/os_crypt/os_crypt.h b/components/os_crypt/os_crypt.h index b03d726..b17abd1 100644 --- a/components/os_crypt/os_crypt.h +++ b/components/os_crypt/os_crypt.h
@@ -17,6 +17,10 @@ #include "components/os_crypt/key_storage_linux.h" #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) +namespace base { +class FilePath; +} + // The OSCrypt class gives access to simple encryption and decryption of // strings. Note that on Mac, access to the system Keychain is required and // these calls can block the current thread to collect user input. The same is @@ -39,6 +43,13 @@ static void SetMainThreadRunner( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner); + // Enable the feature where we determine if we should try a backend via a + // preference file. + static void ShouldUsePreference(bool should_use_preference); + + // Set the folder, where OSCrypt will check for its preference file. + static void SetUserDataPath(const base::FilePath& path); + // Returns true iff the real secret key (not hardcoded one) is available. static bool IsEncryptionAvailable(); #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
diff --git a/components/os_crypt/os_crypt_linux.cc b/components/os_crypt/os_crypt_linux.cc index b8b6ada..758f06a 100644 --- a/components/os_crypt/os_crypt_linux.cc +++ b/components/os_crypt/os_crypt_linux.cc
@@ -250,6 +250,22 @@ } // static +void OSCrypt::ShouldUsePreference(bool should_use_preference) { + // Setting initialisation parameters makes no sense after initializing. + DCHECK(!g_cache.Get().is_key_storage_cached); + + KeyStorageLinux::ShouldUsePreference(should_use_preference); +} + +// static +void OSCrypt::SetUserDataPath(const base::FilePath& path) { + // Setting initialisation parameters makes no sense after initializing. + DCHECK(!g_cache.Get().is_key_storage_cached); + + KeyStorageLinux::SetUserDataPath(path); +} + +// static bool OSCrypt::IsEncryptionAvailable() { return g_get_password[Version::V11](); }
diff --git a/components/password_manager/content/browser/credential_manager_impl.cc b/components/password_manager/content/browser/credential_manager_impl.cc index d78025d..4048fe58 100644 --- a/components/password_manager/content/browser/credential_manager_impl.cc +++ b/components/password_manager/content/browser/credential_manager_impl.cc
@@ -40,7 +40,10 @@ CredentialManagerImpl::CredentialManagerImpl(content::WebContents* web_contents, PasswordManagerClient* client) - : WebContentsObserver(web_contents), client_(client), weak_factory_(this) { + : WebContentsObserver(web_contents), + client_(client), + binding_(this), + weak_factory_(this) { DCHECK(web_contents); auto_signin_enabled_.Init(prefs::kCredentialsEnableAutosignin, client_->GetPrefs()); @@ -49,8 +52,26 @@ CredentialManagerImpl::~CredentialManagerImpl() {} void CredentialManagerImpl::BindRequest( - mojom::CredentialManagerRequest request) { - bindings_.AddBinding(this, std::move(request)); + mojom::CredentialManagerAssociatedRequest request) { + DCHECK(!binding_.is_bound()); + binding_.Bind(std::move(request)); + + // The browser side will close the message pipe on DidFinishNavigation before + // the renderer side would be destroyed, and the renderer never explicitly + // closes the pipe. So a connection error really means an error here, in which + // case the renderer will try to reconnect when the next call to the API is + // made. Make sure this implementation will no longer be bound to a broken + // pipe once that happens, so the DCHECK above will succeed. + binding_.set_connection_error_handler(base::Bind( + &CredentialManagerImpl::DisconnectBinding, base::Unretained(this))); +} + +bool CredentialManagerImpl::HasBinding() const { + return binding_.is_bound(); +} + +void CredentialManagerImpl::DisconnectBinding() { + binding_.Close(); } void CredentialManagerImpl::Store(const CredentialInfo& credential,
diff --git a/components/password_manager/content/browser/credential_manager_impl.h b/components/password_manager/content/browser/credential_manager_impl.h index 6db0b99..4e6369df 100644 --- a/components/password_manager/content/browser/credential_manager_impl.h +++ b/components/password_manager/content/browser/credential_manager_impl.h
@@ -18,7 +18,7 @@ #include "components/password_manager/core/common/credential_manager_types.h" #include "components/prefs/pref_member.h" #include "content/public/browser/web_contents_observer.h" -#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/associated_binding.h" class GURL; @@ -48,7 +48,9 @@ PasswordManagerClient* client); ~CredentialManagerImpl() override; - void BindRequest(mojom::CredentialManagerRequest request); + void BindRequest(mojom::CredentialManagerAssociatedRequest request); + bool HasBinding() const; + void DisconnectBinding(); // mojom::CredentialManager methods: void Store(const CredentialInfo& credential, StoreCallback callback) override; @@ -97,7 +99,7 @@ std::unique_ptr<CredentialManagerPendingPreventSilentAccessTask> pending_require_user_mediation_; - mojo::BindingSet<mojom::CredentialManager> bindings_; + mojo::AssociatedBinding<mojom::CredentialManager> binding_; base::WeakPtrFactory<CredentialManagerImpl> weak_factory_;
diff --git a/components/password_manager/content/renderer/credential_manager_client.cc b/components/password_manager/content/renderer/credential_manager_client.cc index 8dab130..f0e3081 100644 --- a/components/password_manager/content/renderer/credential_manager_client.cc +++ b/components/password_manager/content/renderer/credential_manager_client.cc
@@ -13,9 +13,9 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "components/password_manager/core/common/credential_manager_types.h" +#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" -#include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/WebKit/public/platform/WebCredential.h" #include "third_party/WebKit/public/platform/WebCredentialManagerError.h" #include "third_party/WebKit/public/platform/WebFederatedCredential.h" @@ -273,7 +273,18 @@ return; content::RenderFrame* main_frame = render_view()->GetMainRenderFrame(); - main_frame->GetRemoteInterfaces()->GetInterface(&mojo_cm_service_); + main_frame->GetRemoteAssociatedInterfaces()->GetInterface(&mojo_cm_service_); + + // The remote end of the pipe will be forcibly closed by the browser side + // after each main frame navigation. Set up an error handler to reset the + // local end so that there will be an attempt at reestablishing the connection + // at the next call to the API. + mojo_cm_service_.set_connection_error_handler(base::Bind( + &CredentialManagerClient::OnMojoConnectionError, base::Unretained(this))); +} + +void CredentialManagerClient::OnMojoConnectionError() { + mojo_cm_service_.reset(); } void CredentialManagerClient::OnDestruct() {
diff --git a/components/password_manager/content/renderer/credential_manager_client.h b/components/password_manager/content/renderer/credential_manager_client.h index 334ac89..513b389e 100644 --- a/components/password_manager/content/renderer/credential_manager_client.h +++ b/components/password_manager/content/renderer/credential_manager_client.h
@@ -58,8 +58,9 @@ void OnDestruct() override; void ConnectToMojoCMIfNeeded(); + void OnMojoConnectionError(); - mojom::CredentialManagerPtr mojo_cm_service_; + mojom::CredentialManagerAssociatedPtr mojo_cm_service_; DISALLOW_COPY_AND_ASSIGN(CredentialManagerClient); };
diff --git a/components/password_manager/content/renderer/credential_manager_client_browsertest.cc b/components/password_manager/content/renderer/credential_manager_client_browsertest.cc index 8e3c029..85647cb 100644 --- a/components/password_manager/content/renderer/credential_manager_client_browsertest.cc +++ b/components/password_manager/content/renderer/credential_manager_client_browsertest.cc
@@ -13,12 +13,12 @@ #include "base/location.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "content/public/common/associated_interface_provider.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" #include "content/public/test/render_view_test.h" #include "content/public/test/test_utils.h" -#include "mojo/public/cpp/bindings/binding_set.h" -#include "services/service_manager/public/cpp/interface_provider.h" +#include "mojo/public/cpp/bindings/associated_binding_set.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/WebCredential.h" #include "third_party/WebKit/public/platform/WebCredentialManagerClient.h" @@ -39,7 +39,7 @@ FakeCredentialManager() {} ~FakeCredentialManager() override {} - void BindRequest(mojom::CredentialManagerRequest request) { + void BindRequest(mojom::CredentialManagerAssociatedRequest request) { bindings_.AddBinding(this, std::move(request)); } @@ -74,7 +74,7 @@ } } - mojo::BindingSet<mojom::CredentialManager> bindings_; + mojo::AssociatedBindingSet<mojom::CredentialManager> bindings_; }; class CredentialManagerClientTest : public content::RenderViewTest { @@ -87,10 +87,9 @@ content::RenderViewTest::SetUp(); client_.reset(new CredentialManagerClient(view_)); - service_manager::InterfaceProvider* remote_interfaces = - view_->GetMainRenderFrame()->GetRemoteInterfaces(); - service_manager::InterfaceProvider::TestApi test_api(remote_interfaces); - test_api.SetBinderForName( + content::AssociatedInterfaceProvider* remote_interfaces = + view_->GetMainRenderFrame()->GetRemoteAssociatedInterfaces(); + remote_interfaces->OverrideBinderForTesting( mojom::CredentialManager::Name_, base::Bind(&CredentialManagerClientTest::BindCredentialManager, base::Unretained(this))); @@ -107,8 +106,9 @@ bool callback_succeeded() const { return callback_succeeded_; } void set_callback_succeeded(bool state) { callback_succeeded_ = state; } - void BindCredentialManager(mojo::ScopedMessagePipeHandle handle) { - fake_cm_.BindRequest(mojom::CredentialManagerRequest(std::move(handle))); + void BindCredentialManager(mojo::ScopedInterfaceEndpointHandle handle) { + fake_cm_.BindRequest( + mojom::CredentialManagerAssociatedRequest(std::move(handle))); } std::unique_ptr<blink::WebPasswordCredential> credential_;
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index 4a2ce05..4b7652e 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -178,13 +178,13 @@ "//components/security_state/core", "//components/strings", "//components/sync", - "//components/ukm", "//components/url_formatter", "//components/variations", "//components/webdata/common", "//crypto", "//google_apis", "//net", + "//services/metrics/public/cpp:metrics_cpp", "//sql", "//third_party/protobuf:protobuf_lite", "//third_party/re2",
diff --git a/components/password_manager/core/browser/DEPS b/components/password_manager/core/browser/DEPS index dfa1659..cf549c2 100644 --- a/components/password_manager/core/browser/DEPS +++ b/components/password_manager/core/browser/DEPS
@@ -5,11 +5,23 @@ "+components/security_state", "+components/sync/base", "+components/sync/driver", - "+components/ukm", "+components/url_formatter", "+components/variations", "+components/webdata/common", "+crypto", "+google_apis", "+grit", + "+services/metrics/public/cpp", ] + +specific_include_rules = { + "password_form_manager_unittest\.cc": [ + "+components/ukm", + ], + "password_form_metrics_recorder_unittest\.cc": [ + "+components/ukm", + ], + "password_manager_metrics_recorder_unittest\.cc": [ + "+components/ukm", + ], +}
diff --git a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc index 8f250dbd..3514f5a 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper.cc
@@ -114,9 +114,10 @@ bool success) { // If there is a number of realms, choose the first in the list. if (success) { - for (const FacetURI& affiliated_facet : results) { - if (affiliated_facet.IsValidWebFacetURI()) { - form->affiliated_web_realm = affiliated_facet.canonical_spec() + "/"; + for (const Facet& affiliated_facet : results) { + if (affiliated_facet.uri.IsValidWebFacetURI()) { + form->affiliated_web_realm = + affiliated_facet.uri.canonical_spec() + "/"; break; } } @@ -154,11 +155,12 @@ bool success) { std::vector<std::string> affiliated_realms; if (success) { - for (const FacetURI& affiliated_facet : results) { - if (affiliated_facet != original_facet_uri && - affiliated_facet.IsValidAndroidFacetURI()) + for (const Facet& affiliated_facet : results) { + if (affiliated_facet.uri != original_facet_uri && + affiliated_facet.uri.IsValidAndroidFacetURI()) // Facet URIs have no trailing slash, whereas realms do. - affiliated_realms.push_back(affiliated_facet.canonical_spec() + "/"); + affiliated_realms.push_back(affiliated_facet.uri.canonical_spec() + + "/"); } } result_callback.Run(affiliated_realms); @@ -170,10 +172,11 @@ bool success) { std::vector<std::string> affiliated_realms; if (success) { - for (const FacetURI& affiliated_facet : results) { - if (affiliated_facet.IsValidWebFacetURI()) + for (const Facet& affiliated_facet : results) { + if (affiliated_facet.uri.IsValidWebFacetURI()) // Facet URIs have no trailing slash, whereas realms do. - affiliated_realms.push_back(affiliated_facet.canonical_spec() + "/"); + affiliated_realms.push_back(affiliated_facet.uri.canonical_spec() + + "/"); } } result_callback.Run(affiliated_realms); @@ -199,11 +202,11 @@ // When the primary key for a login is updated, |changes| will contain both a // REMOVE and ADD change for that login. Cached affiliation data should not be - // deleted in this case. A simple solution is to call TrimCacheForFacet() + // deleted in this case. A simple solution is to call TrimCacheForFacetURI() // always after Prefetch() calls -- the trimming logic will detect that there // is an active prefetch and not delete the corresponding data. for (const FacetURI& facet_uri : facet_uris_to_trim) - affiliation_service_->TrimCacheForFacet(facet_uri); + affiliation_service_->TrimCacheForFacetURI(facet_uri); } void AffiliatedMatchHelper::OnGetPasswordStoreResults(
diff --git a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc index d262c50..6a369fd2 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc
@@ -39,7 +39,7 @@ AffiliatedFacets(const FacetURI&, StrategyOnCacheMiss)); MOCK_METHOD2(Prefetch, void(const FacetURI&, const base::Time&)); MOCK_METHOD2(CancelPrefetch, void(const FacetURI&, const base::Time&)); - MOCK_METHOD1(TrimCacheForFacet, void(const FacetURI&)); + MOCK_METHOD1(TrimCacheForFacetURI, void(const FacetURI&)); void GetAffiliations(const FacetURI& facet_uri, StrategyOnCacheMiss cache_miss_strategy, @@ -63,24 +63,27 @@ StrategyOnCacheMiss expected_cache_miss_strategy) { EXPECT_CALL(*this, OnGetAffiliationsCalled(expected_facet_uri, expected_cache_miss_strategy)) - .WillOnce(testing::Return(std::vector<FacetURI>())); + .WillOnce(testing::Return(AffiliatedFacets())); } void ExpectCallToPrefetch(const char* expected_facet_uri_spec) { EXPECT_CALL(*this, Prefetch(FacetURI::FromCanonicalSpec(expected_facet_uri_spec), - base::Time::Max())).RetiresOnSaturation(); + base::Time::Max())) + .RetiresOnSaturation(); } void ExpectCallToCancelPrefetch(const char* expected_facet_uri_spec) { EXPECT_CALL(*this, CancelPrefetch( FacetURI::FromCanonicalSpec(expected_facet_uri_spec), - base::Time::Max())).RetiresOnSaturation(); + base::Time::Max())) + .RetiresOnSaturation(); } - void ExpectCallToTrimCacheForFacet(const char* expected_facet_uri_spec) { - EXPECT_CALL(*this, TrimCacheForFacet(FacetURI::FromCanonicalSpec( - expected_facet_uri_spec))).RetiresOnSaturation(); + void ExpectCallToTrimCacheForFacetURI(const char* expected_facet_uri_spec) { + EXPECT_CALL(*this, TrimCacheForFacetURI(FacetURI::FromCanonicalSpec( + expected_facet_uri_spec))) + .RetiresOnSaturation(); } private: @@ -116,25 +119,19 @@ const char kTestPassword[] = "secret"; AffiliatedFacets GetTestEquivalenceClassAlpha() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1)); - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha2)); - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1)}, + {FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha2)}, + {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3)}, + }; } AffiliatedFacets GetTestEquivalenceClassBeta() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestWebFacetURIBeta1)); - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta2)); - affiliated_facets.push_back( - FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta3)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestWebFacetURIBeta1)}, + {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta2)}, + {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta3)}, + }; } autofill::PasswordForm GetTestAndroidCredentials(const char* signon_realm) { @@ -240,13 +237,13 @@ } void ExpectTrimCacheForAndroidTestLogins() { - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIBeta2); - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIBeta3); - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIGamma); } @@ -546,9 +543,9 @@ // Verify that whenever the primary key is updated for a credential (in which // case both REMOVE and ADD change notifications are sent out), then Prefetch() -// is called in response to the addition before the call to TrimCacheForFacet() -// in response to the removal, so that cached data is not deleted and then -// immediately re-fetched. +// is called in response to the addition before the call to +// TrimCacheForFacetURI() in response to the removal, so that cached data is not +// deleted and then immediately re-fetched. TEST_F(AffiliatedMatchHelperTest, PrefetchBeforeTrimForPrimaryKeyUpdates) { AddAndroidAndNonAndroidTestLogins(); match_helper()->Initialize(); @@ -562,7 +559,7 @@ testing::InSequence in_sequence; mock_affiliation_service()->ExpectCallToPrefetch( kTestAndroidFacetURIAlpha3); - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); } @@ -579,7 +576,8 @@ DuplicateCredentialsArePrefetchWithMultiplicity) { EXPECT_CALL(*mock_affiliation_service(), Prefetch(FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3), - base::Time::Max())).Times(4); + base::Time::Max())) + .Times(4); autofill::PasswordForm android_form( GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); @@ -608,7 +606,7 @@ for (size_t i = 0; i < 4; ++i) { mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIAlpha3); - mock_affiliation_service()->ExpectCallToTrimCacheForFacet( + mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); }
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc b/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc index 20b8e0c..5ea603a 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend.cc
@@ -97,11 +97,11 @@ facet_managers_.erase(facet_uri); } -void AffiliationBackend::TrimCacheForFacet(const FacetURI& facet_uri) { +void AffiliationBackend::TrimCacheForFacetURI(const FacetURI& facet_uri) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); AffiliatedFacetsWithUpdateTime affiliation; - if (cache_->GetAffiliationsForFacet(facet_uri, &affiliation)) + if (cache_->GetAffiliationsForFacetURI(facet_uri, &affiliation)) DiscardCachedDataIfNoLongerNeeded(affiliation.facets); } @@ -126,8 +126,8 @@ // Discard the equivalence class if there is no facet in the class whose // FacetManager claims that it needs to keep the data. - for (const auto& facet_uri : affiliated_facets) { - auto facet_manager_it = facet_managers_.find(facet_uri); + for (const auto& facet : affiliated_facets) { + auto facet_manager_it = facet_managers_.find(facet.uri); if (facet_manager_it != facet_managers_.end() && !facet_manager_it->second->CanCachedDataBeDiscarded()) { return; @@ -135,7 +135,7 @@ } CHECK(!affiliated_facets.empty()); - cache_->DeleteAffiliationsForFacet(affiliated_facets[0]); + cache_->DeleteAffiliationsForFacetURI(affiliated_facets[0].uri); } void AffiliationBackend::OnSendNotification(const FacetURI& facet_uri) { @@ -153,7 +153,7 @@ bool AffiliationBackend::ReadAffiliationsFromDatabase( const FacetURI& facet_uri, AffiliatedFacetsWithUpdateTime* affiliations) { - return cache_->GetAffiliationsForFacet(facet_uri, affiliations); + return cache_->GetAffiliationsForFacetURI(facet_uri, affiliations); } void AffiliationBackend::SignalNeedNetworkRequest() { @@ -165,8 +165,9 @@ // TODO(engedy): Avoid spamming the task runner; only ever schedule the first // callback. crbug.com/437865. task_runner_->PostDelayedTask( - FROM_HERE, base::Bind(&AffiliationBackend::OnSendNotification, - weak_ptr_factory_.GetWeakPtr(), facet_uri), + FROM_HERE, + base::Bind(&AffiliationBackend::OnSendNotification, + weak_ptr_factory_.GetWeakPtr(), facet_uri), time - clock_->Now()); } @@ -196,14 +197,14 @@ // should be implemented at some point by letting facet managers know if // data. See: https://crbug.com/478832. - for (const auto& facet_uri : affiliated_facets) { - auto facet_manager_it = facet_managers_.find(facet_uri); + for (const auto& facet : affiliated_facets) { + auto facet_manager_it = facet_managers_.find(facet.uri); if (facet_manager_it == facet_managers_.end()) continue; FacetManager* facet_manager = facet_manager_it->second.get(); facet_manager->OnFetchSucceeded(affiliation); if (facet_manager->CanBeDiscarded()) - facet_managers_.erase(facet_uri); + facet_managers_.erase(facet.uri); } }
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_backend.h b/components/password_manager/core/browser/android_affiliation/affiliation_backend.h index 44f3ec9..39edeb1 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_backend.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend.h
@@ -81,7 +81,7 @@ void Prefetch(const FacetURI& facet_uri, const base::Time& keep_fresh_until); void CancelPrefetch(const FacetURI& facet_uri, const base::Time& keep_fresh_until); - void TrimCacheForFacet(const FacetURI& facet_uri); + void TrimCacheForFacetURI(const FacetURI& facet_uri); // Deletes the cache database file at |db_path|, and all auxiliary files. The // database must be closed before calling this.
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc index 9f91baf..e09a601 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_backend_unittest.cc
@@ -105,24 +105,24 @@ const char kTestFacetURIGamma1[] = "https://gamma.example.com"; AffiliatedFacets GetTestEquivalenceClassAlpha() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha2)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha3)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha3)}, + }; } AffiliatedFacets GetTestEquivalenceClassBeta() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIBeta2)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURIBeta2)}, + }; } AffiliatedFacets GetTestEquivalenceClassGamma() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)}, + }; } base::TimeDelta GetCacheHardExpiryPeriod() { @@ -255,12 +255,12 @@ // each facet in |affiliated_facets| are served from cache with no fetches. void ExpectThatEquivalenceClassIsServedFromCache( const AffiliatedFacets& affiliated_facets) { - for (const FacetURI& facet_uri : affiliated_facets) { - SCOPED_TRACE(facet_uri); + for (const Facet& facet : affiliated_facets) { + SCOPED_TRACE(facet.uri); ASSERT_NO_FATAL_FAILURE(GetAffiliationsAndExpectResultWithoutFetch( - facet_uri, StrategyOnCacheMiss::FAIL, affiliated_facets)); + facet.uri, StrategyOnCacheMiss::FAIL, affiliated_facets)); ASSERT_NO_FATAL_FAILURE(GetAffiliationsAndExpectResultWithoutFetch( - facet_uri, StrategyOnCacheMiss::FAIL, affiliated_facets)); + facet.uri, StrategyOnCacheMiss::FAIL, affiliated_facets)); } } @@ -284,12 +284,12 @@ return backend()->facet_manager_count_for_testing(); } - bool IsCachedDataFreshForFacet(const FacetURI& facet_uri) { + bool IsCachedDataFreshForFacetURI(const FacetURI& facet_uri) { std::unique_ptr<base::Clock> clock(backend_task_runner_->GetMockClock()); return FacetManager(facet_uri, backend(), clock.get()).IsCachedDataFresh(); } - bool IsCachedDataNearStaleForFacet(const FacetURI& facet_uri) { + bool IsCachedDataNearStaleForFacetURI(const FacetURI& facet_uri) { std::unique_ptr<base::Clock> clock(backend_task_runner_->GetMockClock()); return FacetManager(facet_uri, backend(), clock.get()) .IsCachedDataNearStale(); @@ -392,23 +392,23 @@ // should be no simultaneous requests, the additional facets should be queried // together in a second fetch after the first fetch completes. TEST_F(AffiliationBackendTest, ConcurrentUnrelatedRequests) { - FacetURI facet_alpha(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); - FacetURI facet_beta(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); - FacetURI facet_gamma(FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)); + FacetURI facet_uri_alpha(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); + FacetURI facet_uri_beta(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); + FacetURI facet_uri_gamma(FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)); // Pretend the fetch is already away when the two other requests come in. MockAffiliationConsumer second_consumer; - GetAffiliations(mock_consumer(), facet_alpha, + GetAffiliations(mock_consumer(), facet_uri_alpha, StrategyOnCacheMiss::FETCH_OVER_NETWORK); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); - GetAffiliations(&second_consumer, facet_beta, + GetAffiliations(&second_consumer, facet_uri_beta, StrategyOnCacheMiss::FETCH_OVER_NETWORK); - Prefetch(facet_gamma, base::Time::Max()); + Prefetch(facet_uri_gamma, base::Time::Max()); std::vector<FacetURI> second_fetch_uris; - second_fetch_uris.push_back(facet_beta); - second_fetch_uris.push_back(facet_gamma); - ASSERT_NO_FATAL_FAILURE(ExpectAndCompleteFetch(facet_alpha)); + second_fetch_uris.push_back(facet_uri_beta); + second_fetch_uris.push_back(facet_uri_gamma); + ASSERT_NO_FATAL_FAILURE(ExpectAndCompleteFetch(facet_uri_alpha)); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); ASSERT_NO_FATAL_FAILURE(ExpectAndCompleteFetch(second_fetch_uris)); @@ -427,21 +427,21 @@ // requests are throttled), so the other requests arrive before it is actually // issued. In this case, all facet URIs should be queried together in one fetch. TEST_F(AffiliationBackendTest, ConcurrentUnrelatedRequests2) { - FacetURI facet_alpha(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); - FacetURI facet_beta(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); - FacetURI facet_gamma(FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)); + FacetURI facet_uri_alpha(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); + FacetURI facet_uri_beta(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); + FacetURI facet_uri_gamma(FacetURI::FromCanonicalSpec(kTestFacetURIGamma1)); MockAffiliationConsumer second_consumer; - GetAffiliations(mock_consumer(), facet_alpha, + GetAffiliations(mock_consumer(), facet_uri_alpha, StrategyOnCacheMiss::FETCH_OVER_NETWORK); - GetAffiliations(&second_consumer, facet_beta, + GetAffiliations(&second_consumer, facet_uri_beta, StrategyOnCacheMiss::FETCH_OVER_NETWORK); - Prefetch(facet_gamma, base::Time::Max()); + Prefetch(facet_uri_gamma, base::Time::Max()); std::vector<FacetURI> fetched_uris; - fetched_uris.push_back(facet_alpha); - fetched_uris.push_back(facet_beta); - fetched_uris.push_back(facet_gamma); + fetched_uris.push_back(facet_uri_alpha); + fetched_uris.push_back(facet_uri_beta); + fetched_uris.push_back(facet_uri_gamma); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); ASSERT_NO_FATAL_FAILURE(ExpectAndCompleteFetch(fetched_uris)); ASSERT_NO_FATAL_FAILURE(ExpectNoFetchNeeded()); @@ -604,7 +604,7 @@ AdvanceTime(GetCacheHardExpiryPeriod() - Epsilon()); - EXPECT_TRUE(IsCachedDataFreshForFacet( + EXPECT_TRUE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectThatEquivalenceClassIsServedFromCache( GetTestEquivalenceClassAlpha())); @@ -613,7 +613,7 @@ // After the data becomes stale, the cached-only request should fail, but the // subsequent on-demand request should fetch the data again and succeed. - EXPECT_FALSE(IsCachedDataFreshForFacet( + EXPECT_FALSE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); GetAffiliationsAndExpectFailureWithoutFetch( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); @@ -641,12 +641,12 @@ AdvanceTime(GetCacheSoftExpiryPeriod() - Epsilon()); ASSERT_NO_FATAL_FAILURE(ExpectNoFetchNeeded()); - EXPECT_FALSE(IsCachedDataNearStaleForFacet( + EXPECT_FALSE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); AdvanceTime(Epsilon()); - EXPECT_TRUE(IsCachedDataNearStaleForFacet( + EXPECT_TRUE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); ASSERT_NO_FATAL_FAILURE( @@ -654,9 +654,9 @@ AdvanceTime(GetCacheHardExpiryPeriod() - Epsilon()); - EXPECT_TRUE(IsCachedDataFreshForFacet( + EXPECT_TRUE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); - EXPECT_TRUE(IsCachedDataNearStaleForFacet( + EXPECT_TRUE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectThatEquivalenceClassIsServedFromCache( GetTestEquivalenceClassAlpha())); @@ -664,7 +664,7 @@ AdvanceTime(Epsilon()); // The data should be allowed to expire and the FacetManager discarded. - EXPECT_FALSE(IsCachedDataFreshForFacet( + EXPECT_FALSE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectNoFetchNeeded()); EXPECT_EQ(0u, backend_facet_manager_count()); @@ -694,16 +694,16 @@ AdvanceTime(GetCacheSoftExpiryPeriod() - Epsilon()); ASSERT_NO_FATAL_FAILURE(ExpectNoFetchNeeded()); - EXPECT_TRUE(IsCachedDataFreshForFacet( + EXPECT_TRUE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); - EXPECT_FALSE(IsCachedDataNearStaleForFacet( + EXPECT_FALSE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectThatEquivalenceClassIsServedFromCache( GetTestEquivalenceClassAlpha())); AdvanceTime(Epsilon()); - EXPECT_TRUE(IsCachedDataNearStaleForFacet( + EXPECT_TRUE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); ASSERT_NO_FATAL_FAILURE(ExpectAndCompleteFetch( @@ -719,7 +719,7 @@ FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1), GetTestEquivalenceClassAlpha())); - EXPECT_FALSE(IsCachedDataNearStaleForFacet( + EXPECT_FALSE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); Prefetch(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1), base::Time::Max()); @@ -746,7 +746,7 @@ // The data should be allowed to expire. EXPECT_FALSE(backend_task_runner()->HasPendingTask()); - EXPECT_TRUE(IsCachedDataNearStaleForFacet( + EXPECT_TRUE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(GetAffiliationsAndExpectFailureWithoutFetch( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); @@ -770,7 +770,7 @@ // However, there is a second Prefetch() request which should keep the data // fresh. EXPECT_EQ(1u, backend_facet_manager_count()); - EXPECT_TRUE(IsCachedDataNearStaleForFacet( + EXPECT_TRUE(IsCachedDataNearStaleForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectNeedForFetchAndLetItBeSent()); ASSERT_NO_FATAL_FAILURE( @@ -778,7 +778,7 @@ AdvanceTime(GetCacheHardExpiryPeriod() - GetCacheSoftExpiryPeriod()); - EXPECT_TRUE(IsCachedDataFreshForFacet( + EXPECT_TRUE(IsCachedDataFreshForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1))); ASSERT_NO_FATAL_FAILURE(ExpectThatEquivalenceClassIsServedFromCache( GetTestEquivalenceClassAlpha())); @@ -793,10 +793,10 @@ EXPECT_FALSE(backend_task_runner()->HasPendingTask()); } -// Verify that TrimCacheForFacet() only removes the equivalence class for the +// Verify that TrimCacheForFacetURI() only removes the equivalence class for the // given facet, and preserves others (even if they could be discarded). TEST_F(AffiliationBackendTest, - TrimCacheForFacetOnlyRemovesDataForTheGivenFacet) { + TrimCacheForFacetURIOnlyRemovesDataForTheGivenFacet) { FacetURI preserved_facet_uri(FacetURI::FromCanonicalSpec(kTestFacetURIBeta1)); ASSERT_NO_FATAL_FAILURE(GetAffiliationsAndExpectFetchAndThenResult( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1), @@ -805,18 +805,18 @@ preserved_facet_uri, GetTestEquivalenceClassBeta())); EXPECT_EQ(2u, GetNumOfEquivalenceClassInDatabase()); - backend()->TrimCacheForFacet( + backend()->TrimCacheForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURIAlpha2)); EXPECT_EQ(1u, GetNumOfEquivalenceClassInDatabase()); // Also verify that the last update time of the affiliation data is preserved, // i.e., that it expires when it would normally have expired. AdvanceTime(GetCacheHardExpiryPeriod() - Epsilon()); - EXPECT_TRUE(IsCachedDataFreshForFacet(preserved_facet_uri)); + EXPECT_TRUE(IsCachedDataFreshForFacetURI(preserved_facet_uri)); ASSERT_NO_FATAL_FAILURE(ExpectThatEquivalenceClassIsServedFromCache( GetTestEquivalenceClassBeta())); AdvanceTime(Epsilon()); - EXPECT_FALSE(IsCachedDataFreshForFacet(preserved_facet_uri)); + EXPECT_FALSE(IsCachedDataFreshForFacetURI(preserved_facet_uri)); ASSERT_NO_FATAL_FAILURE( GetAffiliationsAndExpectFailureWithoutFetch(preserved_facet_uri)); }
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_database.cc b/components/password_manager/core/browser/android_affiliation/affiliation_database.cc index 35484d72..2049604 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_database.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database.cc
@@ -61,7 +61,7 @@ return true; } -bool AffiliationDatabase::GetAffiliationsForFacet( +bool AffiliationDatabase::GetAffiliationsForFacetURI( const FacetURI& facet_uri, AffiliatedFacetsWithUpdateTime* result) const { DCHECK(result); @@ -76,7 +76,7 @@ while (statement.Step()) { result->facets.push_back( - FacetURI::FromCanonicalSpec(statement.ColumnString(0))); + {FacetURI::FromCanonicalSpec(statement.ColumnString(0))}); result->last_update_time = base::Time::FromInternalValue(statement.ColumnInt64(1)); } @@ -104,13 +104,13 @@ last_eq_class_id = eq_class_id; } results->back().facets.push_back( - FacetURI::FromCanonicalSpec(statement.ColumnString(0))); + {FacetURI::FromCanonicalSpec(statement.ColumnString(0))}); results->back().last_update_time = base::Time::FromInternalValue(statement.ColumnInt64(1)); } } -void AffiliationDatabase::DeleteAffiliationsForFacet( +void AffiliationDatabase::DeleteAffiliationsForFacetURI( const FacetURI& facet_uri) { sql::Transaction transaction(sql_connection_.get()); if (!transaction.Begin()) @@ -177,9 +177,9 @@ return false; int64_t eq_class_id = sql_connection_->GetLastInsertRowId(); - for (const FacetURI& uri : affiliated_facets.facets) { + for (const Facet& facet : affiliated_facets.facets) { statement_child.Reset(true); - statement_child.BindString(0, uri.canonical_spec()); + statement_child.BindString(0, facet.uri.canonical_spec()); statement_child.BindInt64(1, eq_class_id); if (!statement_child.Run()) return false; @@ -199,14 +199,14 @@ if (!transaction.Begin()) return; - for (const FacetURI& uri : affiliation.facets) { + for (const Facet& facet : affiliation.facets) { AffiliatedFacetsWithUpdateTime old_affiliation; - if (GetAffiliationsForFacet(uri, &old_affiliation)) { + if (GetAffiliationsForFacetURI(facet.uri, &old_affiliation)) { if (!AreEquivalenceClassesEqual(old_affiliation.facets, affiliation.facets)) { removed_affiliations->push_back(old_affiliation); } - DeleteAffiliationsForFacet(uri); + DeleteAffiliationsForFacetURI(facet.uri); } }
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_database.h b/components/password_manager/core/browser/android_affiliation/affiliation_database.h index a79c94f..a8810474 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_database.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database.h
@@ -41,15 +41,15 @@ // Looks up the equivalence class containing |facet_uri|, and returns true if // such a class is found, in which case it is also stored into |result|. - bool GetAffiliationsForFacet(const FacetURI& facet_uri, - AffiliatedFacetsWithUpdateTime* result) const; + bool GetAffiliationsForFacetURI(const FacetURI& facet_uri, + AffiliatedFacetsWithUpdateTime* result) const; // Retrieves all stored equivalence classes. void GetAllAffiliations( std::vector<AffiliatedFacetsWithUpdateTime>* results) const; // Removes the stored equivalence class, if any, containing |facet_uri|. - void DeleteAffiliationsForFacet(const FacetURI& facet_uri); + void DeleteAffiliationsForFacetURI(const FacetURI& facet_uri); // Removes stored equivalence classes that were last updated before the // |cutoff_threshold|.
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc index 127ca55..250a368f 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_database_unittest.cc
@@ -37,31 +37,36 @@ const AffiliatedFacetsWithUpdateTime& reality) { EXPECT_EQ(expectation.last_update_time, reality.last_update_time); EXPECT_THAT(reality.facets, - testing::UnorderedElementsAreArray(reality.facets)); + testing::UnorderedElementsAreArray(expectation.facets)); } AffiliatedFacetsWithUpdateTime TestEquivalenceClass1() { AffiliatedFacetsWithUpdateTime affiliation; affiliation.last_update_time = base::Time::FromInternalValue(kTestTimeUs1); - affiliation.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - affiliation.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); - affiliation.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); + affiliation.facets = { + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + }; return affiliation; } AffiliatedFacetsWithUpdateTime TestEquivalenceClass2() { AffiliatedFacetsWithUpdateTime affiliation; affiliation.last_update_time = base::Time::FromInternalValue(kTestTimeUs2); - affiliation.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI4)); - affiliation.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI5)); + affiliation.facets = { + {FacetURI::FromCanonicalSpec(kTestFacetURI4)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI5)}, + }; return affiliation; } AffiliatedFacetsWithUpdateTime TestEquivalenceClass3() { AffiliatedFacetsWithUpdateTime affiliation; affiliation.last_update_time = base::Time::FromInternalValue(kTestTimeUs3); - affiliation.facets.push_back( - FacetURI::FromCanonicalSpec(kTestAndroidFacetURI)); + affiliation.facets = { + {FacetURI::FromCanonicalSpec(kTestAndroidFacetURI)}, + }; return affiliation; } @@ -124,8 +129,10 @@ sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CONSTRAINT); AffiliatedFacetsWithUpdateTime intersecting; - intersecting.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); - intersecting.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI4)); + intersecting.facets = { + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI4)}, + }; EXPECT_FALSE(db().Store(intersecting)); EXPECT_TRUE(expecter.SawExpectedErrors()); } @@ -153,9 +160,9 @@ // Verify that querying any element in the first equivalence class yields that // class. - for (const auto& facet_uri : TestEquivalenceClass1().facets) { + for (const auto& facet : TestEquivalenceClass1().facets) { AffiliatedFacetsWithUpdateTime affiliation; - EXPECT_TRUE(db().GetAffiliationsForFacet(facet_uri, &affiliation)); + EXPECT_TRUE(db().GetAffiliationsForFacetURI(facet.uri, &affiliation)); ExpectEquivalenceClassesAreEqual(TestEquivalenceClass1(), affiliation); } @@ -163,7 +170,7 @@ // that class. { AffiliatedFacetsWithUpdateTime affiliation; - EXPECT_TRUE(db().GetAffiliationsForFacet( + EXPECT_TRUE(db().GetAffiliationsForFacetURI( FacetURI::FromCanonicalSpec(kTestAndroidFacetURI), &affiliation)); ExpectEquivalenceClassesAreEqual(TestEquivalenceClass3(), affiliation); } @@ -171,7 +178,7 @@ // Verify that querying a facet not in the database yields no result. { AffiliatedFacetsWithUpdateTime affiliation; - EXPECT_FALSE(db().GetAffiliationsForFacet( + EXPECT_FALSE(db().GetAffiliationsForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURI6), &affiliation)); ExpectEquivalenceClassesAreEqual(AffiliatedFacetsWithUpdateTime(), affiliation); @@ -192,7 +199,7 @@ EXPECT_EQ(0u, removed.size()); AffiliatedFacetsWithUpdateTime affiliation; - EXPECT_TRUE(db().GetAffiliationsForFacet( + EXPECT_TRUE(db().GetAffiliationsForFacetURI( FacetURI::FromCanonicalSpec(kTestFacetURI1), &affiliation)); ExpectEquivalenceClassesAreEqual(updated, affiliation); } @@ -203,8 +210,10 @@ AffiliatedFacetsWithUpdateTime intersecting; std::vector<AffiliatedFacetsWithUpdateTime> removed; intersecting.last_update_time = base::Time::FromInternalValue(5000000); - intersecting.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); - intersecting.facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI4)); + intersecting.facets = { + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI4)}, + }; db().StoreAndRemoveConflicting(intersecting, &removed); ASSERT_EQ(2u, removed.size());
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc index b05d66b5..c2954cc 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher.cc
@@ -185,42 +185,42 @@ const affiliation_pb::Affiliation& equivalence_class( response.affiliation(i)); - AffiliatedFacets affiliated_uris; + AffiliatedFacets affiliated_facets; for (int j = 0; j < equivalence_class.facet_size(); ++j) { const std::string& uri_spec(equivalence_class.facet(j).id()); FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec); // Ignore potential future kinds of facet URIs (e.g. for new platforms). if (!uri.is_valid()) continue; - affiliated_uris.push_back(uri); + affiliated_facets.push_back({uri}); } // Be lenient and ignore empty (after filtering) equivalence classes. - if (affiliated_uris.empty()) + if (affiliated_facets.empty()) continue; // Ignore equivalence classes that are duplicates of earlier ones. However, // fail in the case of a partial overlap, which violates the invariant that // affiliations must form an equivalence relation. - for (const FacetURI& uri : affiliated_uris) { - if (!facet_uri_to_class_index.count(uri)) - facet_uri_to_class_index[uri] = result->size(); - if (facet_uri_to_class_index[uri] != - facet_uri_to_class_index[affiliated_uris[0]]) { + for (const Facet& facet : affiliated_facets) { + if (!facet_uri_to_class_index.count(facet.uri)) + facet_uri_to_class_index[facet.uri] = result->size(); + if (facet_uri_to_class_index[facet.uri] != + facet_uri_to_class_index[affiliated_facets[0].uri]) { return false; } } // Filter out duplicate equivalence classes in the response. - if (facet_uri_to_class_index[affiliated_uris[0]] == result->size()) - result->push_back(affiliated_uris); + if (facet_uri_to_class_index[affiliated_facets[0].uri] == result->size()) + result->push_back(affiliated_facets); } // Synthesize an equivalence class (of size one) for each facet that did not // appear in the server response due to not being affiliated with any others. for (const FacetURI& uri : requested_facet_uris_) { if (!facet_uri_to_class_index.count(uri)) - result->push_back(AffiliatedFacets(1, uri)); + result->push_back({{uri}}); } return true;
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc index cf82af6..dee6c40d 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_fetcher_unittest.cc
@@ -144,13 +144,14 @@ ASSERT_EQ(2u, mock_delegate.result().size()); EXPECT_THAT(mock_delegate.result()[0], testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kExampleWebFacet1URI), - FacetURI::FromCanonicalSpec(kExampleWebFacet2URI), - FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI))); - EXPECT_THAT(mock_delegate.result()[1], - testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kNotExampleWebFacetURI), - FacetURI::FromCanonicalSpec(kNotExampleAndroidFacetURI))); + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet1URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet2URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI)})); + EXPECT_THAT( + mock_delegate.result()[1], + testing::UnorderedElementsAre( + Facet{FacetURI::FromCanonicalSpec(kNotExampleWebFacetURI)}, + Facet{FacetURI::FromCanonicalSpec(kNotExampleAndroidFacetURI)})); } // The API contract of this class is to return an equivalence class for all @@ -177,7 +178,7 @@ ASSERT_EQ(1u, mock_delegate.result().size()); EXPECT_THAT(mock_delegate.result()[0], testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kExampleWebFacet1URI))); + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet1URI)})); } TEST_F(AffiliationFetcherTest, DuplicateEquivalenceClassesAreIgnored) { @@ -206,9 +207,9 @@ ASSERT_EQ(1u, mock_delegate.result().size()); EXPECT_THAT(mock_delegate.result()[0], testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kExampleWebFacet1URI), - FacetURI::FromCanonicalSpec(kExampleWebFacet2URI), - FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI))); + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet1URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet2URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI)})); } TEST_F(AffiliationFetcherTest, EmptyEquivalenceClassesAreIgnored) { @@ -233,7 +234,7 @@ ASSERT_EQ(1u, mock_delegate.result().size()); EXPECT_THAT(mock_delegate.result()[0], testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kExampleWebFacet1URI))); + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet1URI)})); } TEST_F(AffiliationFetcherTest, UnrecognizedFacetURIsAreIgnored) { @@ -264,9 +265,9 @@ ASSERT_EQ(1u, mock_delegate.result().size()); EXPECT_THAT(mock_delegate.result()[0], testing::UnorderedElementsAre( - FacetURI::FromCanonicalSpec(kExampleWebFacet1URI), - FacetURI::FromCanonicalSpec(kExampleWebFacet2URI), - FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI))); + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet1URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleWebFacet2URI)}, + Facet{FacetURI::FromCanonicalSpec(kExampleAndroidFacetURI)})); } TEST_F(AffiliationFetcherTest, FailureBecauseResponseIsNotAProtobuf) {
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_service.cc b/components/password_manager/core/browser/android_affiliation/affiliation_service.cc index 98eb5f56..c10adbed 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_service.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service.cc
@@ -81,11 +81,11 @@ base::Unretained(backend_), facet_uri, keep_fresh_until)); } -void AffiliationService::TrimCacheForFacet(const FacetURI& facet_uri) { +void AffiliationService::TrimCacheForFacetURI(const FacetURI& facet_uri) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(backend_); backend_task_runner_->PostTask( - FROM_HERE, base::Bind(&AffiliationBackend::TrimCacheForFacet, + FROM_HERE, base::Bind(&AffiliationBackend::TrimCacheForFacetURI, base::Unretained(backend_), facet_uri)); }
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_service.h b/components/password_manager/core/browser/android_affiliation/affiliation_service.h index 168cae9..9789c48 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_service.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service.h
@@ -142,7 +142,7 @@ // triggered by this call. It will only potentially remove data // corresponding to the given |facet_uri|, but still only as long as the // data is no longer needed. - virtual void TrimCacheForFacet(const FacetURI& facet_uri); + virtual void TrimCacheForFacetURI(const FacetURI& facet_uri); private: // The backend, owned by this AffiliationService instance, but living on the
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc index f33f95c..16e78e4d 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_service_unittest.cc
@@ -33,11 +33,11 @@ const char kTestFacetURIBeta1[] = "https://one.beta.example.com"; AffiliatedFacets GetTestEquivalenceClassAlpha() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha2)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURIAlpha3)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURIAlpha3)}, + }; } } // namespace
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc index 9583702e..bd69920 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.cc
@@ -187,6 +187,17 @@ return false; } +// Extracts and sorts the facet URIs of the given affiliated facets. This is +// used to determine whether two equivalence classes are equal. +std::vector<FacetURI> ExtractAndSortFacetURIs(const AffiliatedFacets& facets) { + std::vector<FacetURI> uris; + uris.reserve(facets.size()); + std::transform(facets.begin(), facets.end(), std::back_inserter(uris), + [](const Facet& facet) { return facet.uri; }); + std::sort(uris.begin(), uris.end()); + return uris; +}; + } // namespace @@ -278,16 +289,27 @@ return os << facet_uri.potentially_invalid_spec(); } +bool operator==(const FacetBrandingInfo& lhs, const FacetBrandingInfo& rhs) { + return std::tie(lhs.name, lhs.icon_url) == std::tie(rhs.name, rhs.icon_url); +} + +bool operator!=(const FacetBrandingInfo& lhs, const FacetBrandingInfo& rhs) { + return !(lhs == rhs); +} + +bool operator==(const Facet& lhs, const Facet& rhs) { + return std::tie(lhs.uri, lhs.branding_info) == + std::tie(rhs.uri, rhs.branding_info); +} + +bool operator!=(const Facet& lhs, const Facet& rhs) { + return !(lhs == rhs); +} + bool AreEquivalenceClassesEqual(const AffiliatedFacets& a, const AffiliatedFacets& b) { - if (a.size() != b.size()) - return false; - - std::vector<FacetURI> a_sorted(a.begin(), a.end()); - std::vector<FacetURI> b_sorted(b.begin(), b.end()); - std::sort(a_sorted.begin(), a_sorted.end()); - std::sort(b_sorted.begin(), b_sorted.end()); - return std::equal(a_sorted.begin(), a_sorted.end(), b_sorted.begin()); + return a.size() == b.size() && + ExtractAndSortFacetURIs(a) == ExtractAndSortFacetURIs(b); } bool IsValidAndroidFacetURI(const std::string& url) {
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils.h b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h index 33ab8e4..187288d 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils.h +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils.h
@@ -53,6 +53,7 @@ #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" +#include "url/gurl.h" #include "url/third_party/mozilla/url_parse.h" namespace autofill { @@ -150,8 +151,35 @@ url::Parsed parsed_; }; +// The branding information for a given facet. Corresponds to the |BrandingInfo| +// message in affiliation_api.proto. +struct FacetBrandingInfo { + // Human readable name of this facet, or empty if this information is not + // available. + // + // For example, this would be something like "Netflix" for the popular + // video-on-demand application corresponding to FacetURIs + // `android://...@com.netflix.mediaclient` and `https://netflix.com`. + std::string name; + + // URL of the icon of this facet, or empty if this information is not + // available. + // + // For example, this would be something like + // "https://lh3.googleusercontent.com/..." for the popular video-on-demand + // application corresponding to FacetURIs + // `android://...@com.netflix.mediaclient` and `https://netflix.com`. + GURL icon_url; +}; + +// Facet struct, corresponds to the |Facet| message in affiliation_api.proto. +struct Facet { + FacetURI uri; + FacetBrandingInfo branding_info; +}; + // A collection of facets affiliated with each other, i.e. an equivalence class. -typedef std::vector<FacetURI> AffiliatedFacets; +typedef std::vector<Facet> AffiliatedFacets; // A collection of facets affiliated with each other, i.e. an equivalence class, // plus a timestamp that indicates the last time the data was updated from an @@ -166,7 +194,8 @@ }; // Returns whether or not equivalence classes |a| and |b| are equal, that is, -// whether or not they consist of the same set of facets. +// whether or not they consist of the same set of facet URIs. Note that branding +// information is ignored for this check. // // Note that this will do some sorting, so it can be expensive for large inputs. bool AreEquivalenceClassesEqual(const AffiliatedFacets& a, @@ -185,6 +214,14 @@ // For logging use only. std::ostream& operator<<(std::ostream& os, const FacetURI& facet_uri); +// Needed for testing. +bool operator==(const FacetBrandingInfo& lhs, const FacetBrandingInfo& rhs); +bool operator!=(const FacetBrandingInfo& lhs, const FacetBrandingInfo& rhs); + +// Needed for testing. +bool operator==(const Facet& lhs, const Facet& rhs); +bool operator!=(const Facet& lhs, const Facet& rhs); + struct FacetURIHash { size_t operator()(const FacetURI& facet_uri) const { return std::hash<std::string>()(facet_uri.potentially_invalid_spec());
diff --git a/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc index 99b32c2..cc36bcfd 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliation_utils_unittest.cc
@@ -21,6 +21,44 @@ const char kTestFacetURI3[] = "https://gamma.example.com/"; } // namespace +TEST(AffiliationUtilsTest, FacetBrandingInfoOperatorEq) { + FacetBrandingInfo facet_1 = {"First Facet", GURL()}; + FacetBrandingInfo facet_1_with_icon = { + "First Facet", GURL("https://example.com/icon_1.png")}; + FacetBrandingInfo facet_2 = {"Second Facet", GURL()}; + FacetBrandingInfo facet_2_with_icon = { + "Second Facet", GURL("https://example.com/icon_2.png")}; + + EXPECT_EQ(facet_1, facet_1); + EXPECT_NE(facet_1, facet_1_with_icon); + EXPECT_NE(facet_1, facet_2); + EXPECT_NE(facet_1, facet_2_with_icon); + + EXPECT_NE(facet_1_with_icon, facet_1); + EXPECT_EQ(facet_1_with_icon, facet_1_with_icon); + EXPECT_NE(facet_1_with_icon, facet_2); + EXPECT_NE(facet_1_with_icon, facet_2_with_icon); + + EXPECT_NE(facet_2, facet_1); + EXPECT_NE(facet_2, facet_1_with_icon); + EXPECT_EQ(facet_2, facet_2); + EXPECT_NE(facet_2, facet_2_with_icon); + + EXPECT_NE(facet_2_with_icon, facet_1); + EXPECT_NE(facet_2_with_icon, facet_1_with_icon); + EXPECT_NE(facet_2_with_icon, facet_2); + EXPECT_EQ(facet_2_with_icon, facet_2_with_icon); +} + +TEST(AffiliationUtilsTest, FacetOperatorEq) { + Facet facet_1 = {FacetURI::FromPotentiallyInvalidSpec(kTestFacetURI1)}; + Facet facet_2 = {FacetURI::FromPotentiallyInvalidSpec(kTestFacetURI2)}; + EXPECT_EQ(facet_1, facet_1); + EXPECT_NE(facet_1, facet_2); + EXPECT_NE(facet_2, facet_1); + EXPECT_EQ(facet_2, facet_2); +} + TEST(AffiliationUtilsTest, ValidWebFacetURIs) { struct { const char* valid_facet_uri; @@ -160,15 +198,17 @@ } TEST(AffiliationUtilsTest, EqualEquivalenceClasses) { - AffiliatedFacets a; - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); + AffiliatedFacets a = { + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + }; - AffiliatedFacets b; - b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); - b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); + AffiliatedFacets b = { + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + }; EXPECT_TRUE(AreEquivalenceClassesEqual(a, a)); EXPECT_TRUE(AreEquivalenceClassesEqual(b, b)); @@ -177,18 +217,20 @@ } TEST(AffiliationUtilsTest, NotEqualEquivalenceClasses) { - AffiliatedFacets a; - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); + AffiliatedFacets a = { + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + }; - AffiliatedFacets b; - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); - b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); + AffiliatedFacets b = { + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + }; AffiliatedFacets c; - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - a.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); - b.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); EXPECT_FALSE(AreEquivalenceClassesEqual(a, b)); EXPECT_FALSE(AreEquivalenceClassesEqual(a, c));
diff --git a/components/password_manager/core/browser/android_affiliation/facet_manager_host.h b/components/password_manager/core/browser/android_affiliation/facet_manager_host.h index cc5f14e..7536b07 100644 --- a/components/password_manager/core/browser/android_affiliation/facet_manager_host.h +++ b/components/password_manager/core/browser/android_affiliation/facet_manager_host.h
@@ -6,6 +6,7 @@ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_ANDROID_AFFILIATION_FACET_MANAGER_HOST_H_ #include "base/macros.h" +#include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc b/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc index afd6c61..7d81a7d2 100644 --- a/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/facet_manager_unittest.cc
@@ -12,6 +12,7 @@ #include "base/bind_helpers.h" #include "base/location.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/rand_util.h" #include "base/test/test_mock_time_task_runner.h" @@ -149,11 +150,11 @@ const char kTestFacetURI3[] = "https://three.example.com"; AffiliatedFacets GetTestEquivalenceClass() { - AffiliatedFacets affiliated_facets; - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI1)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI2)); - affiliated_facets.push_back(FacetURI::FromCanonicalSpec(kTestFacetURI3)); - return affiliated_facets; + return { + {FacetURI::FromCanonicalSpec(kTestFacetURI1)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI2)}, + {FacetURI::FromCanonicalSpec(kTestFacetURI3)}, + }; } AffiliatedFacetsWithUpdateTime GetTestEquivalenceClassWithUpdateTime( @@ -233,9 +234,9 @@ // The order is important: FacetManager will read the DB in its constructor. facet_manager_host_.set_expected_facet_uri( FacetURI::FromCanonicalSpec(kTestFacetURI1)); - facet_manager_.reset( - new FacetManager(FacetURI::FromCanonicalSpec(kTestFacetURI1), - fake_facet_manager_host(), main_clock_.get())); + facet_manager_ = base::MakeUnique<FacetManager>( + FacetURI::FromCanonicalSpec(kTestFacetURI1), fake_facet_manager_host(), + main_clock_.get()); facet_manager_notifier_.set_facet_manager(facet_manager_.get()); facet_manager_creation_ = Now(); }
diff --git a/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc index d8ccd22..c926b0b 100644 --- a/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc +++ b/components/password_manager/core/browser/android_affiliation/fake_affiliation_api.cc
@@ -48,9 +48,11 @@ for (const auto& preset_equivalence_class : preset_equivalence_relation_) { bool had_intersection_with_request = false; for (const auto& requested_facet_uri : fetcher->requested_facet_uris()) { - if (std::find(preset_equivalence_class.begin(), - preset_equivalence_class.end(), - requested_facet_uri) != preset_equivalence_class.end()) { + if (std::any_of(preset_equivalence_class.begin(), + preset_equivalence_class.end(), + [&requested_facet_uri](const Facet& facet) { + return facet.uri == requested_facet_uri; + })) { had_intersection_with_request = true; break; }
diff --git a/components/password_manager/core/browser/password_form_metrics_recorder.h b/components/password_manager/core/browser/password_form_metrics_recorder.h index b09d84d..3c7ab92 100644 --- a/components/password_manager/core/browser/password_form_metrics_recorder.h +++ b/components/password_manager/core/browser/password_form_metrics_recorder.h
@@ -14,7 +14,7 @@ #include "base/memory/ref_counted.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/password_form_user_action.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc b/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc index e421927b..b93956e8 100644 --- a/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc +++ b/components/password_manager/core/browser/password_form_metrics_recorder_unittest.cc
@@ -9,9 +9,9 @@ #include "base/test/histogram_tester.h" #include "base/test/user_action_tester.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/ukm/test_ukm_recorder.h" #include "components/ukm/ukm_source.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/password_manager_client.h b/components/password_manager/core/browser/password_manager_client.h index 1053080f..907ea62 100644 --- a/components/password_manager/core/browser/password_manager_client.h +++ b/components/password_manager/core/browser/password_manager_client.h
@@ -12,7 +12,7 @@ #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/credentials_filter.h" #include "components/password_manager/core/browser/password_store.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" class PrefService;
diff --git a/components/password_manager/core/browser/password_manager_metrics_recorder.h b/components/password_manager/core/browser/password_manager_metrics_recorder.h index 26dbd52e..ea9b816 100644 --- a/components/password_manager/core/browser/password_manager_metrics_recorder.h +++ b/components/password_manager/core/browser/password_manager_metrics_recorder.h
@@ -10,7 +10,7 @@ #include <memory> #include "base/macros.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" class GURL;
diff --git a/components/password_manager/core/browser/password_manager_metrics_recorder_unittest.cc b/components/password_manager/core/browser/password_manager_metrics_recorder_unittest.cc index d3c1119f..89874c4 100644 --- a/components/password_manager/core/browser/password_manager_metrics_recorder_unittest.cc +++ b/components/password_manager/core/browser/password_manager_metrics_recorder_unittest.cc
@@ -7,9 +7,9 @@ #include <memory> #include "base/metrics/metrics_hashes.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/ukm/test_ukm_recorder.h" #include "components/ukm/ukm_source.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "testing/gtest/include/gtest/gtest.h" namespace password_manager {
diff --git a/components/payments/content/payment_request.cc b/components/payments/content/payment_request.cc index a4717e2..cf0c0718 100644 --- a/components/payments/content/payment_request.cc +++ b/components/payments/content/payment_request.cc
@@ -85,7 +85,7 @@ delegate_->GetApplicationLocale()); state_ = base::MakeUnique<PaymentRequestState>( spec_.get(), this, delegate_->GetApplicationLocale(), - delegate_->GetPersonalDataManager(), delegate_.get()); + delegate_->GetPersonalDataManager(), delegate_.get(), &journey_logger_); return; } @@ -107,7 +107,7 @@ delegate_->GetApplicationLocale()); state_ = base::MakeUnique<PaymentRequestState>( spec_.get(), this, delegate_->GetApplicationLocale(), - delegate_->GetPersonalDataManager(), delegate_.get()); + delegate_->GetPersonalDataManager(), delegate_.get(), &journey_logger_); } void PaymentRequest::Show() {
diff --git a/components/payments/content/payment_request_state.cc b/components/payments/content/payment_request_state.cc index 740a4d6..1fefb16 100644 --- a/components/payments/content/payment_request_state.cc +++ b/components/payments/content/payment_request_state.cc
@@ -16,6 +16,7 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/payments/content/payment_response_helper.h" #include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/journey_logger.h" #include "components/payments/core/payment_instrument.h" #include "components/payments/core/payment_request_data_util.h" #include "components/payments/core/payment_request_delegate.h" @@ -27,13 +28,15 @@ Delegate* delegate, const std::string& app_locale, autofill::PersonalDataManager* personal_data_manager, - PaymentRequestDelegate* payment_request_delegate) + PaymentRequestDelegate* payment_request_delegate, + JourneyLogger* journey_logger) : is_ready_to_pay_(false), is_waiting_for_merchant_validation_(false), app_locale_(app_locale), spec_(spec), delegate_(delegate), personal_data_manager_(personal_data_manager), + journey_logger_(journey_logger), selected_shipping_profile_(nullptr), selected_shipping_option_error_profile_(nullptr), selected_contact_profile_(nullptr), @@ -272,12 +275,29 @@ shipping_profiles_ = profile_comparator()->FilterProfilesForShipping( raw_profiles_for_filtering); + // Set the number of suggestions shown for the sections requested by the + // merchant. + if (spec_->request_payer_name() || spec_->request_payer_phone() || + spec_->request_payer_email()) { + journey_logger_->SetNumberOfSuggestionsShown( + JourneyLogger::Section::SECTION_CONTACT_INFO, contact_profiles_.size()); + } + if (spec_->request_shipping()) { + journey_logger_->SetNumberOfSuggestionsShown( + JourneyLogger::Section::SECTION_SHIPPING_ADDRESS, + shipping_profiles_.size()); + } + // Create the list of available instruments. A copy of each card will be made // by their respective AutofillPaymentInstrument. const std::vector<autofill::CreditCard*>& cards = personal_data_manager_->GetCreditCardsToSuggest(); for (autofill::CreditCard* card : cards) AddAutofillPaymentInstrument(/*selected=*/false, *card); + + journey_logger_->SetNumberOfSuggestionsShown( + JourneyLogger::Section::SECTION_CREDIT_CARDS, + available_instruments().size()); } void PaymentRequestState::SetDefaultProfileSelections() {
diff --git a/components/payments/content/payment_request_state.h b/components/payments/content/payment_request_state.h index 19fcb35..cf25e016 100644 --- a/components/payments/content/payment_request_state.h +++ b/components/payments/content/payment_request_state.h
@@ -26,6 +26,7 @@ namespace payments { +class JourneyLogger; class PaymentInstrument; class PaymentRequestDelegate; @@ -70,7 +71,8 @@ Delegate* delegate, const std::string& app_locale, autofill::PersonalDataManager* personal_data_manager, - PaymentRequestDelegate* payment_request_delegate); + PaymentRequestDelegate* payment_request_delegate, + JourneyLogger* journey_logger); ~PaymentRequestState() override; // PaymentResponseHelper::Delegate @@ -215,10 +217,11 @@ const std::string app_locale_; - // Not owned. Never null. Both outlive this object. + // Not owned. Never null. Will outlive this object. PaymentRequestSpec* spec_; Delegate* delegate_; autofill::PersonalDataManager* personal_data_manager_; + JourneyLogger* journey_logger_; autofill::AutofillProfile* selected_shipping_profile_; autofill::AutofillProfile* selected_shipping_option_error_profile_;
diff --git a/components/payments/content/payment_request_state_unittest.cc b/components/payments/content/payment_request_state_unittest.cc index bb6c602..0e0a014 100644 --- a/components/payments/content/payment_request_state_unittest.cc +++ b/components/payments/content/payment_request_state_unittest.cc
@@ -13,6 +13,7 @@ #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/payments/content/payment_request_spec.h" +#include "components/payments/core/journey_logger.h" #include "components/payments/core/test_payment_request_delegate.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/public/platform/modules/payments/payment_request.mojom.h" @@ -26,6 +27,9 @@ PaymentRequestStateTest() : num_on_selected_information_changed_called_(0), test_payment_request_delegate_(/*personal_data_manager=*/nullptr), + journey_logger_(test_payment_request_delegate_.IsIncognito(), + GURL("http://www.test.com"), + test_payment_request_delegate_.GetUkmRecorder()), address_(autofill::test::GetFullProfile()), credit_card_visa_(autofill::test::GetCreditCard()) { test_personal_data_manager_.AddTestingProfile(&address_); @@ -59,7 +63,7 @@ /*observer=*/nullptr, "en-US"); state_ = base::MakeUnique<PaymentRequestState>( spec_.get(), this, "en-US", &test_personal_data_manager_, - &test_payment_request_delegate_); + &test_payment_request_delegate_, &journey_logger_); state_->AddObserver(this); } @@ -115,6 +119,7 @@ mojom::PaymentAddressPtr selected_shipping_address_; autofill::TestPersonalDataManager test_personal_data_manager_; TestPaymentRequestDelegate test_payment_request_delegate_; + JourneyLogger journey_logger_; // Test data. autofill::AutofillProfile address_;
diff --git a/components/payments/core/DEPS b/components/payments/core/DEPS index 7086c89..8325aae1 100644 --- a/components/payments/core/DEPS +++ b/components/payments/core/DEPS
@@ -7,8 +7,14 @@ "+components/prefs", "+components/pref_registry", "+components/strings", - "+components/ukm", + "+services/metrics/public", "+third_party/libaddressinput", "+third_party/libphonenumber", "+ui/base", ] + +specific_include_rules = { + "journey_logger_unittest\.cc": [ + "+components/ukm", + ], +}
diff --git a/components/payments/core/journey_logger.cc b/components/payments/core/journey_logger.cc index c2170ac..ccf337b3 100644 --- a/components/payments/core/journey_logger.cc +++ b/components/payments/core/journey_logger.cc
@@ -8,8 +8,8 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" namespace payments { @@ -164,18 +164,15 @@ has_recorded_ = true; RecordCheckoutFlowMetrics(); - - RecordPaymentMethodMetric(); - - RecordRequestedInformationMetrics(); - - RecordSectionSpecificStats(completion_status); - - // Record the CanMakePayment metrics based on whether the transaction was - // completed or aborted by the user (UserAborted) or otherwise (OtherAborted). RecordCanMakePaymentStats(completion_status); - RecordUrlKeyedMetrics(completion_status); + + // These following metrics only make sense if the UI was shown to the user. + if (was_show_called_) { + RecordPaymentMethodMetric(); + RecordRequestedInformationMetrics(); + RecordSectionSpecificStats(completion_status); + } } void JourneyLogger::RecordCheckoutFlowMetrics() { @@ -201,10 +198,6 @@ } void JourneyLogger::RecordRequestedInformationMetrics() { - if (!was_show_called_) { - return; - } - DCHECK(requested_information_ != REQUESTED_INFORMATION_MAX); UMA_HISTOGRAM_ENUMERATION("PaymentRequest.RequestedInformation", requested_information_, REQUESTED_INFORMATION_MAX);
diff --git a/components/payments/core/journey_logger_unittest.cc b/components/payments/core/journey_logger_unittest.cc index 26211be..2fd288e 100644 --- a/components/payments/core/journey_logger_unittest.cc +++ b/components/payments/core/journey_logger_unittest.cc
@@ -439,9 +439,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user completes the checkout. logger.SetCompleted(); @@ -463,9 +471,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user aborts the checkout. logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER); @@ -487,9 +503,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the checkout is aborted. logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER); @@ -512,9 +536,17 @@ JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user completes the checkout. logger.SetCompleted(); @@ -536,9 +568,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); - // Simulate that the user had suggestions for all the requested sections. + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + + // Simulate that the user had suggestions for none of the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user completes the checkout. logger.SetCompleted(); @@ -561,9 +601,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); - // Simulate that the user had suggestions for all the requested sections. + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + + // Simulate that the user had suggestions for none of the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user aborts the checkout. logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER); @@ -586,9 +634,17 @@ JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); - // Simulate that the user had suggestions for all the requested sections. + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + + // Simulate that the user had suggestions for none of the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the the checkout is aborted. logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER); @@ -612,9 +668,17 @@ JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""), /*ukm_recorder=*/nullptr); - // Simulate that the user had suggestions for all the requested sections. + // The merchant only requests payment information. + logger.SetRequestedInformation( + /*requested_shipping=*/false, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); + + // Simulate that the user had suggestions for none of the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); + // Simulate that the Payment Request was shown to the user. + logger.SetShowCalled(); + // Simulate that the user aborts the checkout. logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER); @@ -640,9 +704,13 @@ // Make the two loggers have different data. logger1.SetShowCalled(); - logger1.SetRequestedInformation(true, true, false, false); + logger1.SetRequestedInformation( + /*requested_shipping=*/true, /*requested_email=*/true, + /*requested_phone=*/false, /*requested_name=*/false); logger2.SetShowCalled(); - logger2.SetRequestedInformation(true, false, false, false); + logger2.SetRequestedInformation( + /*requested_shipping=*/true, /*requested_email=*/false, + /*requested_phone=*/false, /*requested_name=*/false); logger1.SetCanMakePaymentValue(true);
diff --git a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc index f4b2699..381b5f9d 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc +++ b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.cc
@@ -202,15 +202,6 @@ base::Unretained(this))); } -void CloudPolicyClientRegistrationHelper::StartRegistrationWithAccessToken( - const std::string& access_token, - const base::Closure& callback) { - DCHECK(!client_->is_registered()); - callback_ = callback; - client_->AddObserver(this); - OnTokenFetched(access_token); -} - // static std::vector<std::string> CloudPolicyClientRegistrationHelper::GetScopes() {
diff --git a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h index 85253d5..59a894a 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h +++ b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h
@@ -56,12 +56,6 @@ void StartRegistrationWithLoginToken(const std::string& login_refresh_token, const base::Closure& callback); - // Starts the client registration process. |access_token| must be a valid - // OAuth access token for the scopes returned by the |GetScopes| static - // function. - void StartRegistrationWithAccessToken(const std::string& access_token, - const base::Closure& callback); - // Returns the scopes required for policy client registration. static std::vector<std::string> GetScopes(); #endif
diff --git a/components/proximity_auth/webui/reachable_phone_flow.cc b/components/proximity_auth/webui/reachable_phone_flow.cc index c518216..86629ec 100644 --- a/components/proximity_auth/webui/reachable_phone_flow.cc +++ b/components/proximity_auth/webui/reachable_phone_flow.cc
@@ -13,6 +13,7 @@ #include "components/cryptauth/cryptauth_client.h" #include "components/cryptauth/proto/cryptauth_api.pb.h" #include "components/proximity_auth/logging/logging.h" +#include "net/traffic_annotation/network_traffic_annotation.h" namespace proximity_auth { @@ -43,11 +44,35 @@ // Ping the user's devices to update themselves with CryptAuth. cryptauth::SendDeviceSyncTickleRequest tickle_request; tickle_request.set_tickle_type(cryptauth::UPDATE_ENROLLMENT); + net::PartialNetworkTrafficAnnotationTag partial_traffic_annotation = + net::DefinePartialNetworkTrafficAnnotation("cryptauth_device_sync_tickle", + "oauth2_api_call_flow", R"( + semantics { + sender: "EasyUnlock Debug UI" + description: + "Triggers a sync on all other device (for the same user) registered " + "on CryptAuth." + trigger: "User manually opens the EasyUnlock debug UI." + data: "OAuth 2.0 token and the device public key." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled in settings, but this request will " + "only be sent if the user opens the EasyUnlock debug UI." + chrome_policy { + SigninAllowed { + SigninAllowed: false + } + } + })"); client_->SendDeviceSyncTickle( - tickle_request, base::Bind(&ReachablePhoneFlow::OnSyncTickleSuccess, - weak_ptr_factory_.GetWeakPtr()), + tickle_request, + base::Bind(&ReachablePhoneFlow::OnSyncTickleSuccess, + weak_ptr_factory_.GetWeakPtr()), base::Bind(&ReachablePhoneFlow::OnApiCallError, - weak_ptr_factory_.GetWeakPtr())); + weak_ptr_factory_.GetWeakPtr()), + partial_traffic_annotation); } void ReachablePhoneFlow::OnSyncTickleSuccess(
diff --git a/components/safe_browsing/base_resource_throttle.h b/components/safe_browsing/base_resource_throttle.h index 62938ca..2ae5070 100644 --- a/components/safe_browsing/base_resource_throttle.h +++ b/components/safe_browsing/base_resource_throttle.h
@@ -66,6 +66,10 @@ SBThreatType threat_type, const ThreatMetadata& metadata) override; + // Called on the IO thread when the user has decided to proceed with the + // current request, or go back. + void OnBlockingPageComplete(bool proceed); + protected: BaseResourceThrottle( const net::URLRequest* request, @@ -96,6 +100,13 @@ // page, but may be overridden in a subclass. virtual void CancelResourceLoad(); + // Starts displaying the safe browsing interstitial page. Called on the UI + // thread. + static void StartDisplayingBlockingPage( + const base::WeakPtr<BaseResourceThrottle>& throttle, + scoped_refptr<BaseUIManager> ui_manager, + const security_interstitials::UnsafeResource& resource); + scoped_refptr<BaseUIManager> ui_manager(); private: @@ -120,10 +131,6 @@ scoped_refptr<BaseUIManager> ui_manager_; - // Called on the IO thread when the user has decided to proceed with the - // current request, or go back. - void OnBlockingPageComplete(bool proceed); - // Starts running |url| through the safe browsing check. Returns true if the // URL is safe to visit. Otherwise returns false and will call // OnBrowseUrlResult() when the check has completed. @@ -133,13 +140,6 @@ // StartCheckingUrl()) has taken longer than kCheckUrlTimeoutMs. void OnCheckUrlTimeout(); - // Starts displaying the safe browsing interstitial page. Called on the UI - // thread. - static void StartDisplayingBlockingPage( - const base::WeakPtr<BaseResourceThrottle>& throttle, - scoped_refptr<BaseUIManager> ui_manager, - const security_interstitials::UnsafeResource& resource); - void ResumeRequest(); // For marking network events. |name| and |value| can be null.
diff --git a/components/safe_browsing_db/BUILD.gn b/components/safe_browsing_db/BUILD.gn index 33eb8e5..031ccc7 100644 --- a/components/safe_browsing_db/BUILD.gn +++ b/components/safe_browsing_db/BUILD.gn
@@ -275,6 +275,15 @@ ] } +if (is_android) { + import("//build/config/android/rules.gni") + java_cpp_enum("sb_threat_values") { + sources = [ + "v4_protocol_manager_util.h", + ] + } +} + source_set("v4_rice") { sources = [ "v4_rice.cc",
diff --git a/components/safe_browsing_db/v4_protocol_manager_util.h b/components/safe_browsing_db/v4_protocol_manager_util.h index 2f345d9..9c083542 100644 --- a/components/safe_browsing_db/v4_protocol_manager_util.h +++ b/components/safe_browsing_db/v4_protocol_manager_util.h
@@ -77,6 +77,8 @@ // Different types of threats that SafeBrowsing protects against. This is the // type that's returned to the clients of SafeBrowsing in Chromium. +// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.safe_browsing +// GENERATED_JAVA_PREFIX_TO_STRIP: SB_THREAT_TYPE_ enum SBThreatType { // This type can be used for lists that can be checked synchronously so a // client callback isn't required, or for whitelists.
diff --git a/components/security_state/DEPS b/components/security_state/DEPS index b2f6f8e..f042025 100644 --- a/components/security_state/DEPS +++ b/components/security_state/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+net", + "+third_party/WebKit/public/platform", ] \ No newline at end of file
diff --git a/components/security_state/content/content_utils.cc b/components/security_state/content/content_utils.cc index 3432722..9d4b4a1 100644 --- a/components/security_state/content/content_utils.cc +++ b/components/security_state/content/content_utils.cc
@@ -23,6 +23,7 @@ #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_cipher_suite_names.h" #include "net/ssl/ssl_connection_status_flags.h" +#include "third_party/WebKit/public/platform/WebMixedContentContextType.h" #include "third_party/boringssl/src/include/openssl/ssl.h" #include "ui/base/l10n/l10n_util.h" @@ -229,7 +230,8 @@ content::SecurityStyleExplanation( l10n_util::GetStringUTF8(IDS_SHA1), l10n_util::GetStringUTF8(IDS_SHA1_DESCRIPTION), - !!security_info.certificate)); + !!security_info.certificate, + blink::WebMixedContentContextType::kNotMixedContent)); } if (security_info.cert_missing_subject_alt_name) { @@ -237,7 +239,8 @@ content::SecurityStyleExplanation( l10n_util::GetStringUTF8(IDS_SUBJECT_ALT_NAME_MISSING), l10n_util::GetStringUTF8(IDS_SUBJECT_ALT_NAME_MISSING_DESCRIPTION), - !!security_info.certificate)); + !!security_info.certificate, + blink::WebMixedContentContextType::kNotMixedContent)); } // Record the presence of mixed content (HTTP subresources on an HTTPS @@ -287,7 +290,8 @@ l10n_util::GetStringUTF8(IDS_CERTIFICATE_CHAIN_ERROR), l10n_util::GetStringFUTF8( IDS_CERTIFICATE_CHAIN_ERROR_DESCRIPTION_FORMAT, error_string), - !!security_info.certificate); + !!security_info.certificate, + blink::WebMixedContentContextType::kNotMixedContent); if (is_cert_status_minor_error) { security_style_explanations->neutral_explanations.push_back(explanation); @@ -317,7 +321,8 @@ l10n_util::GetStringUTF8(IDS_VALID_SERVER_CERTIFICATE), l10n_util::GetStringFUTF8( IDS_VALID_SERVER_CERTIFICATE_DESCRIPTION, issuer_name), - !!security_info.certificate)); + !!security_info.certificate, + blink::WebMixedContentContextType::kNotMixedContent)); } }
diff --git a/components/security_state/content/content_utils_unittest.cc b/components/security_state/content/content_utils_unittest.cc index 2fbf436bb..e031970 100644 --- a/components/security_state/content/content_utils_unittest.cc +++ b/components/security_state/content/content_utils_unittest.cc
@@ -18,6 +18,7 @@ #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebMixedContentContextType.h" namespace { @@ -319,4 +320,14 @@ EXPECT_EQ(0u, explanations.insecure_explanations.size()); } +// Tests that an explanation using the shorter constructor sets the correct +// default values for other fields. +TEST(SecurityStateContentUtilsTest, DefaultSecurityStyleExplanation) { + content::SecurityStyleExplanation explanation("summary", "description"); + + EXPECT_EQ(false, explanation.has_certificate); + EXPECT_EQ(blink::WebMixedContentContextType::kNotMixedContent, + explanation.mixed_content_type); +} + } // namespace
diff --git a/components/signin/core/browser/refresh_token_annotation_request.cc b/components/signin/core/browser/refresh_token_annotation_request.cc index d1e11c9..15c4314 100644 --- a/components/signin/core/browser/refresh_token_annotation_request.cc +++ b/components/signin/core/browser/refresh_token_annotation_request.cc
@@ -17,6 +17,7 @@ #include "google_apis/gaia/gaia_constants.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context_getter.h" namespace { @@ -171,3 +172,34 @@ base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, request_callback_); request_callback_.Reset(); } + +net::PartialNetworkTrafficAnnotationTag +RefreshTokenAnnotationRequest::GetNetworkTrafficAnnotationTag() { + return net::DefinePartialNetworkTrafficAnnotation( + "refresh_token_annotation_request", "oauth2_api_call_flow", R"( + semantics { + sender: "Account Fetcher Service" + description: + "Sends request to /IssueToken endpoint with device_id to backfill " + "device info for refresh tokens issued pre-M38." + trigger: + "When refreshing account information in AccountFetcherService. On " + "chrome startup and at most once per day." + data: + "OAuth 2.0 access token, Chrome's client id and version number, and " + "a single signin scoped, randomly generated device id for Chrome " + "profile." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled by settings, however the request is " + "made only for signed-in users." + chrome_policy { + SigninAllowed { + policy_options {mode: MANDATORY} + SigninAllowed: false + } + } + })"); +}
diff --git a/components/signin/core/browser/refresh_token_annotation_request.h b/components/signin/core/browser/refresh_token_annotation_request.h index 4965ef8..2e0868c 100644 --- a/components/signin/core/browser/refresh_token_annotation_request.h +++ b/components/signin/core/browser/refresh_token_annotation_request.h
@@ -58,6 +58,8 @@ std::string CreateApiCallBody() override; void ProcessApiCallSuccess(const net::URLFetcher* source) override; void ProcessApiCallFailure(const net::URLFetcher* source) override; + net::PartialNetworkTrafficAnnotationTag GetNetworkTrafficAnnotationTag() + override; private: FRIEND_TEST_ALL_PREFIXES(RefreshTokenAnnotationRequestTest, ShouldSendNow);
diff --git a/components/signin/core/browser/signin_manager.cc b/components/signin/core/browser/signin_manager.cc index 7856c7855..5ced320 100644 --- a/components/signin/core/browser/signin_manager.cc +++ b/components/signin/core/browser/signin_manager.cc
@@ -54,6 +54,8 @@ return "No Signin"; case SIGNIN_TYPE_WITH_REFRESH_TOKEN: return "With refresh token"; + case SIGNIN_TYPE_WITHOUT_REFRESH_TOKEN: + return "Without refresh token"; } NOTREACHED(); @@ -101,19 +103,21 @@ const std::string& password, const OAuthTokenFetchedCallback& callback) { DCHECK(!IsAuthenticated()); - - if (!PrepareForSignin(SIGNIN_TYPE_WITH_REFRESH_TOKEN, gaia_id, username, - password)) { + SigninType signin_type = refresh_token.empty() + ? SIGNIN_TYPE_WITHOUT_REFRESH_TOKEN + : SIGNIN_TYPE_WITH_REFRESH_TOKEN; + if (!PrepareForSignin(signin_type, gaia_id, username, password)) { return; } - // Store our token. + // Store the refresh token. temp_refresh_token_ = refresh_token; - if (!callback.is_null() && !temp_refresh_token_.empty()) { + if (!callback.is_null()) { + // Callback present, let the caller complete the pending sign-in. callback.Run(temp_refresh_token_); } else { - // No oauth token or callback, so just complete our pending signin. + // No callback, so just complete the pending signin. CompletePendingSignin(); } } @@ -350,13 +354,13 @@ DCHECK(!possibly_invalid_account_id_.empty()); OnSignedIn(); - DCHECK(!temp_refresh_token_.empty()); DCHECK(IsAuthenticated()); - std::string account_id = GetAuthenticatedAccountId(); - token_service_->UpdateCredentials(account_id, temp_refresh_token_); - temp_refresh_token_.clear(); - + if (!temp_refresh_token_.empty()) { + std::string account_id = GetAuthenticatedAccountId(); + token_service_->UpdateCredentials(account_id, temp_refresh_token_); + temp_refresh_token_.clear(); + } MergeSigninCredentialIntoCookieJar(); }
diff --git a/components/signin/core/browser/signin_manager.h b/components/signin/core/browser/signin_manager.h index 92e9ff5..bae32cf7 100644 --- a/components/signin/core/browser/signin_manager.h +++ b/components/signin/core/browser/signin_manager.h
@@ -74,8 +74,10 @@ const std::string& policy); // Attempt to sign in this user with a refresh token. + // If |refresh_token| is not empty, then SigninManager will add it to the + // |token_service_| when the sign-in flow is completed. // If non-null, the passed |oauth_fetched_callback| callback is invoked once - // signin has been completed. + // sign-in has been completed. // The callback should invoke SignOut() or CompletePendingSignin() to either // continue or cancel the in-process signin. virtual void StartSignInWithRefreshToken( @@ -152,7 +154,11 @@ signin_metrics::SignoutDelete signout_delete_metric); private: - enum SigninType { SIGNIN_TYPE_NONE, SIGNIN_TYPE_WITH_REFRESH_TOKEN }; + enum SigninType { + SIGNIN_TYPE_NONE, + SIGNIN_TYPE_WITH_REFRESH_TOKEN, + SIGNIN_TYPE_WITHOUT_REFRESH_TOKEN + }; std::string SigninTypeToString(SigninType type); friend class FakeSigninManager;
diff --git a/components/subresource_filter/core/common/indexed_ruleset.cc b/components/subresource_filter/core/common/indexed_ruleset.cc index d24fde53..009258e7 100644 --- a/components/subresource_filter/core/common/indexed_ruleset.cc +++ b/components/subresource_filter/core/common/indexed_ruleset.cc
@@ -16,7 +16,7 @@ // RulesetIndexer -------------------------------------------------------------- // static -const int RulesetIndexer::kIndexedFormatVersion = 17; +const int RulesetIndexer::kIndexedFormatVersion = 18; RulesetIndexer::RulesetIndexer() : blacklist_(&builder_), whitelist_(&builder_), deactivation_(&builder_) {}
diff --git a/components/sync/android/OWNERS b/components/sync/android/OWNERS index d241d2b..25c1d80 100644 --- a/components/sync/android/OWNERS +++ b/components/sync/android/OWNERS
@@ -1,3 +1,2 @@ -maxbogue@chromium.org nyquist@chromium.org yfriedman@chromium.org
diff --git a/components/sync/engine_impl/directory_update_handler.cc b/components/sync/engine_impl/directory_update_handler.cc index 7b71cf6..b7a5725 100644 --- a/components/sync/engine_impl/directory_update_handler.cc +++ b/components/sync/engine_impl/directory_update_handler.cc
@@ -33,7 +33,9 @@ : dir_(dir), type_(type), worker_(worker), - debug_info_emitter_(debug_info_emitter) {} + debug_info_emitter_(debug_info_emitter), + cached_gc_directive_version_(0), + cached_gc_directive_aged_out_day_(base::Time::FromDoubleT(0)) {} DirectoryUpdateHandler::~DirectoryUpdateHandler() {} @@ -271,28 +273,12 @@ void DirectoryUpdateHandler::UpdateProgressMarker( const sync_pb::DataTypeProgressMarker& progress_marker) { - if (progress_marker.has_gc_directive() || !cached_gc_directive_) { - dir_->SetDownloadProgress(type_, progress_marker); - } else { - sync_pb::DataTypeProgressMarker merged_marker = progress_marker; - merged_marker.mutable_gc_directive()->CopyFrom(*cached_gc_directive_); - dir_->SetDownloadProgress(type_, merged_marker); - } + dir_->SetDownloadProgress(type_, progress_marker); } void DirectoryUpdateHandler::ExpireEntriesIfNeeded( syncable::ModelNeutralWriteTransaction* trans, const sync_pb::DataTypeProgressMarker& progress_marker) { - if (!cached_gc_directive_) { - sync_pb::DataTypeProgressMarker current_marker; - GetDownloadProgress(¤t_marker); - if (current_marker.has_gc_directive()) { - cached_gc_directive_ = - base::MakeUnique<sync_pb::GarbageCollectionDirective>( - current_marker.gc_directive()); - } - } - if (!progress_marker.has_gc_directive()) return; @@ -300,15 +286,28 @@ progress_marker.gc_directive(); if (new_gc_directive.has_version_watermark() && - (!cached_gc_directive_ || - cached_gc_directive_->version_watermark() < - new_gc_directive.version_watermark())) { + (cached_gc_directive_version_ < new_gc_directive.version_watermark())) { ExpireEntriesByVersion(dir_, trans, type_, new_gc_directive.version_watermark()); + cached_gc_directive_version_ = new_gc_directive.version_watermark(); } - cached_gc_directive_ = - base::MakeUnique<sync_pb::GarbageCollectionDirective>(new_gc_directive); + if (new_gc_directive.has_age_watermark_in_days()) { + DCHECK(new_gc_directive.age_watermark_in_days()); + // For saving resource purpose(ex. cpu, battery), We round up garbage + // collection age to day, so we only run GC once a day if server did not + // change the |age_watermark_in_days|. + if (cached_gc_directive_aged_out_day_ != + base::Time::Now().LocalMidnight() - + base::TimeDelta::FromDays( + new_gc_directive.age_watermark_in_days())) { + ExpireEntriesByAge(dir_, trans, type_, + new_gc_directive.age_watermark_in_days()); + cached_gc_directive_aged_out_day_ = + base::Time::Now().LocalMidnight() - + base::TimeDelta::FromDays(new_gc_directive.age_watermark_in_days()); + } + } } } // namespace syncer
diff --git a/components/sync/engine_impl/directory_update_handler.h b/components/sync/engine_impl/directory_update_handler.h index e137fe4..5e5da24d2 100644 --- a/components/sync/engine_impl/directory_update_handler.h +++ b/components/sync/engine_impl/directory_update_handler.h
@@ -99,7 +99,11 @@ scoped_refptr<ModelSafeWorker> worker_; DataTypeDebugInfoEmitter* debug_info_emitter_; - std::unique_ptr<sync_pb::GarbageCollectionDirective> cached_gc_directive_; + // The version which directory already ran garbage collection against on. + int64_t cached_gc_directive_version_; + + // The day which directory already ran garbage collection against on. + base::Time cached_gc_directive_aged_out_day_; DISALLOW_COPY_AND_ASSIGN(DirectoryUpdateHandler); };
diff --git a/components/sync/engine_impl/directory_update_handler_unittest.cc b/components/sync/engine_impl/directory_update_handler_unittest.cc index 64a4e20..3df1018 100644 --- a/components/sync/engine_impl/directory_update_handler_unittest.cc +++ b/components/sync/engine_impl/directory_update_handler_unittest.cc
@@ -299,6 +299,63 @@ EXPECT_TRUE(EntryExists(e2->id_string())); } +// Create 2 entries, one is 15-days-old, another is 5-days-old. Check if sync +// will delete 15-days-old entry when server set expired age is 10 days. +TEST_F(DirectoryUpdateHandlerProcessUpdateTest, GarbageCollectionByAge) { + DirectoryTypeDebugInfoEmitter emitter(SYNCED_NOTIFICATIONS, &type_observers_); + DirectoryUpdateHandler handler(dir(), SYNCED_NOTIFICATIONS, ui_worker(), + &emitter); + StatusController status; + + sync_pb::DataTypeProgressMarker progress; + progress.set_data_type_id( + GetSpecificsFieldNumberFromModelType(SYNCED_NOTIFICATIONS)); + progress.set_token("token"); + progress.mutable_gc_directive()->set_age_watermark_in_days(20); + + sync_pb::DataTypeContext context; + context.set_data_type_id( + GetSpecificsFieldNumberFromModelType(SYNCED_NOTIFICATIONS)); + context.set_context("context"); + context.set_version(1); + + std::unique_ptr<sync_pb::SyncEntity> e1 = + CreateUpdate(SyncableIdToProto(Id::CreateFromServerId("e1")), "", + SYNCED_NOTIFICATIONS); + e1->set_mtime( + TimeToProtoTime(base::Time::Now() - base::TimeDelta::FromDays(15))); + + std::unique_ptr<sync_pb::SyncEntity> e2 = + CreateUpdate(SyncableIdToProto(Id::CreateFromServerId("e2")), "", + SYNCED_NOTIFICATIONS); + e2->set_mtime( + TimeToProtoTime(base::Time::Now() - base::TimeDelta::FromDays(5))); + + // Add to the applicable updates list. + SyncEntityList updates; + updates.push_back(e1.get()); + updates.push_back(e2.get()); + + // Process and apply updates. + EXPECT_EQ(SYNCER_OK, handler.ProcessGetUpdatesResponse(progress, context, + updates, &status)); + handler.ApplyUpdates(&status); + + // Verify none is deleted because they are unapplied during GC. + EXPECT_TRUE(TypeRootExists(SYNCED_NOTIFICATIONS)); + EXPECT_TRUE(EntryExists(e1->id_string())); + EXPECT_TRUE(EntryExists(e2->id_string())); + + // Process and apply again. 15-days-old entry is deleted but not 5-days-old + // entry. + progress.mutable_gc_directive()->set_age_watermark_in_days(10); + EXPECT_EQ(SYNCER_OK, handler.ProcessGetUpdatesResponse( + progress, context, SyncEntityList(), &status)); + handler.ApplyUpdates(&status); + EXPECT_FALSE(EntryExists(e1->id_string())); + EXPECT_TRUE(EntryExists(e2->id_string())); +} + TEST_F(DirectoryUpdateHandlerProcessUpdateTest, ContextVersion) { DirectoryTypeDebugInfoEmitter emitter(SYNCED_NOTIFICATIONS, &type_observers_); DirectoryUpdateHandler handler(dir(), SYNCED_NOTIFICATIONS, ui_worker(),
diff --git a/components/sync/engine_impl/process_updates_util.cc b/components/sync/engine_impl/process_updates_util.cc index 0592b52..fbbdd22 100644 --- a/components/sync/engine_impl/process_updates_util.cc +++ b/components/sync/engine_impl/process_updates_util.cc
@@ -331,4 +331,30 @@ } } +void ExpireEntriesByAge(syncable::Directory* dir, + syncable::ModelNeutralWriteTransaction* trans, + ModelType type, + int32_t age_watermark_in_days) { + syncable::Directory::Metahandles handles; + base::Time to_be_expired = + base::Time::Now() - base::TimeDelta::FromDays(age_watermark_in_days); + dir->GetMetaHandlesOfType(trans, type, &handles); + for (size_t i = 0; i < handles.size(); ++i) { + syncable::ModelNeutralMutableEntry entry(trans, syncable::GET_BY_HANDLE, + handles[i]); + if (!entry.good() || !entry.GetId().ServerKnows() || + entry.GetUniqueServerTag() == ModelTypeToRootTag(type) || + entry.GetIsUnappliedUpdate() || entry.GetIsUnsynced() || + entry.GetIsDel() || entry.GetServerIsDel() || + entry.GetMtime() > to_be_expired) { + continue; + } + + // Mark entry as unapplied update first to ensure journaling the deletion. + entry.PutIsUnappliedUpdate(true); + // Mark entry as deleted by server. + entry.PutServerIsDel(true); + } +} + } // namespace syncer
diff --git a/components/sync/engine_impl/process_updates_util.h b/components/sync/engine_impl/process_updates_util.h index b816899..56ebc766 100644 --- a/components/sync/engine_impl/process_updates_util.h +++ b/components/sync/engine_impl/process_updates_util.h
@@ -42,6 +42,13 @@ ModelType type, int64_t version_watermark); +// Tombstones all entries of |type| whose ages are older than +// |age_watermark_in_days| unless they are type root or unsynced/unapplied. +void ExpireEntriesByAge(syncable::Directory* dir, + syncable::ModelNeutralWriteTransaction* trans, + ModelType type, + int32_t age_watermark_in_days); + } // namespace syncer #endif // COMPONENTS_SYNC_ENGINE_IMPL_PROCESS_UPDATES_UTIL_H_
diff --git a/components/sync/protocol/password_specifics.proto b/components/sync/protocol/password_specifics.proto index a277b87a..8f17fbc 100644 --- a/components/sync/protocol/password_specifics.proto +++ b/components/sync/protocol/password_specifics.proto
@@ -42,7 +42,7 @@ // For parsed web forms and normal passwords saved through Credential Manager // API: url-scheme://url-host[:url-port]/ // For Android apps (local + federated): - // "android://<hash of cert>@<package name>" + // "android://<hash of cert>@<package name>/" // where the hash is base64 encoded SHA512 of the app's public certificate. // For federated credentials: // "federation://" + origin_host + "/" + federation_host @@ -52,7 +52,7 @@ // For parsed web forms and Credential Manager API: // url-scheme://url-host[:url-port]/path - // For Android: "android://<hash of cert>@<package name>" + // For Android: "android://<hash of cert>@<package name>/" // For proxy/HTTP auth: url-scheme://url-host[:url-port]/path optional string origin = 3;
diff --git a/components/sync/test/android/OWNERS b/components/sync/test/android/OWNERS index c1627421..35d33f1 100644 --- a/components/sync/test/android/OWNERS +++ b/components/sync/test/android/OWNERS
@@ -1,4 +1,3 @@ -maxbogue@chromium.org nyquist@chromium.org shashishekhar@chromium.org yfriedman@chromium.org
diff --git a/components/translate/core/browser/DEPS b/components/translate/core/browser/DEPS index 0c2beda..1f91dbb 100644 --- a/components/translate/core/browser/DEPS +++ b/components/translate/core/browser/DEPS
@@ -2,5 +2,11 @@ "+components/keyed_service/core", "+components/metrics", "+components/machine_intelligence", - "+components/ukm", + "+services/metrics/public", ] + +specific_include_rules = { + "translate_ranker_impl_unittest\.cc": [ + "+components/ukm", + ] +}
diff --git a/components/translate/core/browser/translate_browser_metrics.h b/components/translate/core/browser/translate_browser_metrics.h index e15759a..1db33bb 100644 --- a/components/translate/core/browser/translate_browser_metrics.h +++ b/components/translate/core/browser/translate_browser_metrics.h
@@ -44,6 +44,7 @@ INITIATION_STATUS_ABORTED_BY_RANKER, INITIATION_STATUS_ABORTED_BY_TOO_OFTEN_DENIED, INITIATION_STATUS_ABORTED_BY_MATCHES_PREVIOUS_LANGUAGE, + INITIATION_STATUS_CREATE_INFOBAR, // Insert new items here. INITIATION_STATUS_MAX, };
diff --git a/components/translate/core/browser/translate_ranker_impl.cc b/components/translate/core/browser/translate_ranker_impl.cc index 64fab45..27f36f69 100644 --- a/components/translate/core/browser/translate_ranker_impl.cc +++ b/components/translate/core/browser/translate_ranker_impl.cc
@@ -24,9 +24,9 @@ #include "components/metrics/proto/translate_event.pb.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/common/translate_switches.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/variations/variations_associated_data.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/gurl.h" namespace translate {
diff --git a/components/ukm/BUILD.gn b/components/ukm/BUILD.gn index 35160d05..165a341 100644 --- a/components/ukm/BUILD.gn +++ b/components/ukm/BUILD.gn
@@ -27,8 +27,8 @@ public_deps = [ "//components/metrics/proto", - "//components/ukm/public", - "//components/ukm/public/interfaces", + "//services/metrics/public/cpp:metrics_cpp", + "//services/metrics/public/interfaces", ] deps = [ @@ -49,7 +49,7 @@ public_deps = [ "//base", - "//components/ukm/public/interfaces", + "//services/metrics/public/interfaces", ] deps = [
diff --git a/components/ukm/DEPS b/components/ukm/DEPS index abd3591..099b24d0 100644 --- a/components/ukm/DEPS +++ b/components/ukm/DEPS
@@ -3,5 +3,6 @@ "+components/prefs", "+components/variations", "+mojo/public", + "+services/metrics/public", "+third_party/zlib/google", ]
diff --git a/components/ukm/public/ukm_export.h b/components/ukm/public/ukm_export.h deleted file mode 100644 index 6c460eb5..0000000 --- a/components/ukm/public/ukm_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_UKM_PUBLIC_UKM_EXPORT_H_ -#define COMPONENTS_UKM_PUBLIC_UKM_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(UKM_IMPLEMENTATION) -#define UKM_EXPORT __declspec(dllexport) -#else -#define UKM_EXPORT __declspec(dllimport) -#endif // defined(UKM_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(UKM_IMPLEMENTATION) -#define UKM_EXPORT __attribute__((visibility("default"))) -#else -#define UKM_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define UKM_EXPORT -#endif - -#endif // COMPONENTS_UKM_PUBLIC_UKM_EXPORT_H_
diff --git a/components/ukm/ukm_interface.cc b/components/ukm/ukm_interface.cc index 99decf0..de60163 100644 --- a/components/ukm/ukm_interface.cc +++ b/components/ukm/ukm_interface.cc
@@ -6,8 +6,8 @@ #include "base/atomic_sequence_num.h" #include "base/memory/ptr_util.h" -#include "components/ukm/public/ukm_recorder.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/gurl.h" namespace ukm {
diff --git a/components/ukm/ukm_interface.h b/components/ukm/ukm_interface.h index a3047738..1a3b0c6 100644 --- a/components/ukm/ukm_interface.h +++ b/components/ukm/ukm_interface.h
@@ -5,7 +5,7 @@ #ifndef COMPONENTS_UKM_UKM_INTERFACE_H_ #define COMPONENTS_UKM_UKM_INTERFACE_H_ -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" namespace service_manager { struct BindSourceInfo;
diff --git a/components/ukm/ukm_recorder_impl.h b/components/ukm/ukm_recorder_impl.h index 50976e4..1a20dda 100644 --- a/components/ukm/ukm_recorder_impl.h +++ b/components/ukm/ukm_recorder_impl.h
@@ -10,8 +10,8 @@ #include <vector> #include "base/threading/thread_checker.h" -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" namespace metrics { class UkmBrowserTest;
diff --git a/components/ukm/ukm_service_unittest.cc b/components/ukm/ukm_service_unittest.cc index 3f3e6432..60dec08 100644 --- a/components/ukm/ukm_service_unittest.cc +++ b/components/ukm/ukm_service_unittest.cc
@@ -19,10 +19,10 @@ #include "components/metrics/test_metrics_service_client.h" #include "components/prefs/testing_pref_service.h" #include "components/ukm/persisted_logs_metrics_impl.h" -#include "components/ukm/public/ukm_entry_builder.h" #include "components/ukm/ukm_pref_names.h" #include "components/ukm/ukm_source.h" #include "components/variations/variations_associated_data.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/compression_utils.h"
diff --git a/components/update_client/background_downloader_win.cc b/components/update_client/background_downloader_win.cc index 51ec40a..6f139d4 100644 --- a/components/update_client/background_downloader_win.cc +++ b/components/update_client/background_downloader_win.cc
@@ -104,7 +104,7 @@ // All jobs created by this module have a specific description so they can // be found at run-time or by using system administration tools. -const base::char16 kJobDescription[] = L"Chrome Component Updater"; +const base::char16 kJobName[] = L"Chrome Component Updater"; // How often the code looks for changes in the BITS job state. const int kJobPollingIntervalSec = 4; @@ -256,12 +256,12 @@ return S_OK; } -HRESULT GetJobDescription(IBackgroundCopyJob* job, base::string16* name) { - ScopedCoMem<base::char16> description; - const HRESULT hr = job->GetDescription(&description); +HRESULT GetJobDisplayName(IBackgroundCopyJob* job, base::string16* name) { + ScopedCoMem<base::char16> local_name; + const HRESULT hr = job->GetDisplayName(&local_name); if (FAILED(hr)) return hr; - *name = description.get(); + *name = local_name.get(); return S_OK; } @@ -308,9 +308,9 @@ ScopedComPtr<IBackgroundCopyJob> current_job; if (enum_jobs->Next(1, current_job.GetAddressOf(), NULL) == S_OK && pred(current_job.Get())) { - base::string16 job_description; - hr = GetJobDescription(current_job.Get(), &job_description); - if (job_description.compare(kJobDescription) == 0) + base::string16 job_name; + hr = GetJobDisplayName(current_job.Get(), &job_name); + if (job_name.compare(kJobName) == 0) jobs->push_back(current_job); } } @@ -381,16 +381,29 @@ return S_OK; } -void CleanupJobFiles(IBackgroundCopyJob* job) { - std::vector<ScopedComPtr<IBackgroundCopyFile>> files; - if (FAILED(GetFilesInJob(job, &files))) +void CleanupJob(IBackgroundCopyJob* job) { + if (!job) return; - for (size_t i = 0; i != files.size(); ++i) { + + // Get the file paths associated with this job before canceling the job. + // Canceling the job removes it from the BITS queue right away. It appears + // that it is still possible to query for the properties of the job after + // the job has been canceled. It seems safer though to get the paths first. + std::vector<ScopedComPtr<IBackgroundCopyFile>> files; + GetFilesInJob(job, &files); + + std::vector<base::FilePath> paths; + for (const auto& file : files) { base::string16 local_name; - HRESULT hr(GetJobFileProperties(files[i].Get(), &local_name, NULL, NULL)); + HRESULT hr = GetJobFileProperties(file.Get(), &local_name, NULL, NULL); if (SUCCEEDED(hr)) - DeleteFileAndEmptyParentDirectory(base::FilePath(local_name)); + paths.push_back(base::FilePath(local_name)); } + + job->Cancel(); + + for (const auto& path : paths) + DeleteFileAndEmptyParentDirectory(path); } // Cleans up incompleted jobs that are too old. @@ -416,10 +429,8 @@ if (FAILED(hr)) return hr; - for (size_t i = 0; i != jobs.size(); ++i) { - jobs[i]->Cancel(); - CleanupJobFiles(jobs[i].Get()); - } + for (const auto& job : jobs) + CleanupJob(job.Get()); return S_OK; } @@ -599,10 +610,8 @@ int64_t total_bytes = -1; GetJobByteCount(job_.Get(), &downloaded_bytes, &total_bytes); - if (FAILED(error) && job_.Get()) { - job_->Cancel(); - CleanupJobFiles(job_.Get()); - } + if (FAILED(error)) + CleanupJob(job_.Get()); CleanupStaleJobs(bits_manager_); @@ -734,24 +743,20 @@ GetBackgroundDownloaderJobCount(bits_manager_, &num_jobs); UMA_HISTOGRAM_COUNTS_100("UpdateClient.BackgroundDownloaderJobs", num_jobs); - ScopedComPtr<IBackgroundCopyJob> p; - HRESULT hr = CreateOrOpenJob(url, p.GetAddressOf()); - if (FAILED(hr)) + ScopedComPtr<IBackgroundCopyJob> local_job; + HRESULT hr = CreateOrOpenJob(url, local_job.GetAddressOf()); + if (FAILED(hr)) { + CleanupJob(local_job.Get()); return hr; - - if (hr == S_OK) { - // This is a new job and it needs initialization. - hr = InitializeNewJob(p, url); - if (FAILED(hr)) - return hr; } - hr = p->Resume(); - if (FAILED(hr)) + hr = local_job->Resume(); + if (FAILED(hr)) { + CleanupJob(local_job.Get()); return hr; + } - *job = p.Detach(); - + *job = local_job.Detach(); return S_OK; } @@ -763,40 +768,44 @@ bits_manager_.Get(), &jobs); if (SUCCEEDED(hr) && !jobs.empty()) { *job = jobs.front().Detach(); - return S_FALSE; + return hr; } - // Use kJobDescription as a temporary job display name until the proper - // display name is initialized later on. - GUID guid = {0}; - hr = bits_manager_->CreateJob(kJobDescription, BG_JOB_TYPE_DOWNLOAD, &guid, - job); - if (FAILED(hr)) - return hr; + ScopedComPtr<IBackgroundCopyJob> local_job; + GUID guid = {0}; + hr = bits_manager_->CreateJob(kJobName, BG_JOB_TYPE_DOWNLOAD, &guid, + local_job.GetAddressOf()); + if (FAILED(hr)) { + CleanupJob(local_job.Get()); + return hr; + } + + hr = InitializeNewJob(local_job, url); + if (FAILED(hr)) { + CleanupJob(local_job.Get()); + return hr; + } + + *job = local_job.Detach(); return S_OK; } HRESULT BackgroundDownloader::InitializeNewJob( const base::win::ScopedComPtr<IBackgroundCopyJob>& job, const GURL& url) { - const base::string16 filename(base::SysUTF8ToWide(url.ExtractFileName())); - base::FilePath tempdir; if (!base::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome_BITS_"), &tempdir)) return E_FAIL; + const base::string16 filename(base::SysUTF8ToWide(url.ExtractFileName())); HRESULT hr = job->AddFile(base::SysUTF8ToWide(url.spec()).c_str(), tempdir.Append(filename).AsUTF16Unsafe().c_str()); if (FAILED(hr)) return hr; - hr = job->SetDisplayName(filename.c_str()); - if (FAILED(hr)) - return hr; - - hr = job->SetDescription(kJobDescription); + hr = job->SetDescription(filename.c_str()); if (FAILED(hr)) return hr;
diff --git a/components/url_pattern_index/flat/url_pattern_index.fbs b/components/url_pattern_index/flat/url_pattern_index.fbs index 3a3cc7d..cb5d305a 100644 --- a/components/url_pattern_index/flat/url_pattern_index.fbs +++ b/components/url_pattern_index/flat/url_pattern_index.fbs
@@ -28,19 +28,46 @@ IS_MATCH_CASE, } +// The options controlling whether or not to activate filtering for subresources +// of documents that match the URL pattern of the rule. +// Corresponds to url_pattern_index::proto::ActivationType. +enum ActivationType : ubyte (bit_flags) { + DOCUMENT, // Disable all rules on the page. + GENERIC_BLOCK, // Disable generic URL rules on the page. +} + +// The types of subresource requests that a URL rule should be applied to. +// Corresponds to url_pattern_index::proto::ElementType. +enum ElementType : ushort (bit_flags) { + OTHER, + SCRIPT, + IMAGE, + STYLESHEET, + OBJECT, + XMLHTTPREQUEST, + // TODO(crbug.com/713774): Remove OBJECT_SUBREQUEST type once + // url_pattern_index no longer has a dependency on proto::UrlRule. + OBJECT_SUBREQUEST, + SUBDOCUMENT, + PING, + MEDIA, + FONT, + WEBSOCKET, + // Note: Update the default value for |element_types| field in UrlRule, on + // adding/removing values from this enum. +} + // The flat representation of a single URL rule. For more details regarding the // fields please see the comments to url_pattern_index::proto::UrlRule. table UrlRule { // Rule matching options, a bitmask consisting of OptionFlags. options : ubyte; - // A bitmask of element types, same as proto::UrlRule::element_types. Enables - // all element types except POPUP by default. - // Note: Keep it equal to ELEMENT_TYPE_ALL-ELEMENT_TYPE_POPUP for compactness. - element_types : ushort = 6143; + // A bitmask of ElementType. Equals ElementType_ANY by default for + // compactness. + element_types : ushort = 4095; - // A bitmask of activation types, same as proto::UrlRule::activation_types. - // Disables all activation types by default. + // A bitmask of ActivationType. Disables all activation types by default. activation_types : ubyte = 0; // Use SUBSTRING as default, since it's the most used pattern type. Same as @@ -52,6 +79,8 @@ anchor_right : AnchorType = NONE; // The list of domains to be included/excluded from the filter's affected set. + // Kept sorted for fast matching. Should either be null or have at least a + // single element. domains_included : [string]; domains_excluded : [string];
diff --git a/components/url_pattern_index/url_pattern_index.cc b/components/url_pattern_index/url_pattern_index.cc index c18091ae..f0586d0 100644 --- a/components/url_pattern_index/url_pattern_index.cc +++ b/components/url_pattern_index/url_pattern_index.cc
@@ -8,6 +8,7 @@ #include <limits> #include <string> +#include "base/containers/flat_map.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_piece.h" @@ -25,6 +26,55 @@ using FlatDomains = flatbuffers::Vector<FlatStringOffset>; using FlatDomainsOffset = flatbuffers::Offset<FlatDomains>; +// Maps proto::ActivationType to flat::ActivationType. +const base::flat_map<proto::ActivationType, flat::ActivationType> + kActivationTypeMap( + { + {proto::ACTIVATION_TYPE_UNSPECIFIED, flat::ActivationType_NONE}, + {proto::ACTIVATION_TYPE_DOCUMENT, flat::ActivationType_DOCUMENT}, + // ELEMHIDE is not supported. + {proto::ACTIVATION_TYPE_ELEMHIDE, flat::ActivationType_NONE}, + // GENERICHIDE is not supported. + {proto::ACTIVATION_TYPE_GENERICHIDE, flat::ActivationType_NONE}, + {proto::ACTIVATION_TYPE_GENERICBLOCK, + flat::ActivationType_GENERIC_BLOCK}, + }, + base::KEEP_FIRST_OF_DUPES); + +// Maps proto::ElementType to flat::ElementType. +const base::flat_map<proto::ElementType, flat::ElementType> kElementTypeMap( + { + {proto::ELEMENT_TYPE_UNSPECIFIED, flat::ElementType_NONE}, + {proto::ELEMENT_TYPE_OTHER, flat::ElementType_OTHER}, + {proto::ELEMENT_TYPE_SCRIPT, flat::ElementType_SCRIPT}, + {proto::ELEMENT_TYPE_IMAGE, flat::ElementType_IMAGE}, + {proto::ELEMENT_TYPE_STYLESHEET, flat::ElementType_STYLESHEET}, + {proto::ELEMENT_TYPE_OBJECT, flat::ElementType_OBJECT}, + {proto::ELEMENT_TYPE_XMLHTTPREQUEST, flat::ElementType_XMLHTTPREQUEST}, + {proto::ELEMENT_TYPE_OBJECT_SUBREQUEST, + flat::ElementType_OBJECT_SUBREQUEST}, + {proto::ELEMENT_TYPE_SUBDOCUMENT, flat::ElementType_SUBDOCUMENT}, + {proto::ELEMENT_TYPE_PING, flat::ElementType_PING}, + {proto::ELEMENT_TYPE_MEDIA, flat::ElementType_MEDIA}, + {proto::ELEMENT_TYPE_FONT, flat::ElementType_FONT}, + // Filtering popups is not supported. + {proto::ELEMENT_TYPE_POPUP, flat::ElementType_NONE}, + {proto::ELEMENT_TYPE_WEBSOCKET, flat::ElementType_WEBSOCKET}, + }, + base::KEEP_FIRST_OF_DUPES); + +flat::ActivationType ProtoToFlatActivationType(proto::ActivationType type) { + const auto it = kActivationTypeMap.find(type); + DCHECK(it != kActivationTypeMap.end()); + return it->second; +} + +flat::ElementType ProtoToFlatElementType(proto::ElementType type) { + const auto it = kElementTypeMap.find(type); + DCHECK(it != kElementTypeMap.end()); + return it->second; +} + base::StringPiece ToStringPiece(const flatbuffers::String* string) { DCHECK(string); return base::StringPiece(string->c_str(), string->size()); @@ -43,6 +93,15 @@ [](char c) { return base::IsAsciiUpper(c); }); } +// Returns a bitmask of all the keys of the |map| passed. +template <typename T> +int GetKeysMask(const T& map) { + int mask = 0; + for (const auto& pair : map) + mask |= pair.first; + return mask; +} + // Checks whether a URL |rule| can be converted to its FlatBuffers equivalent, // and performs the actual conversion. class UrlRuleFlatBufferConverter { @@ -142,6 +201,9 @@ } bool InitializeOptions() { + static_assert(flat::OptionFlag_ANY <= std::numeric_limits<uint8_t>::max(), + "Option flags can not be stored in uint8_t."); + if (rule_.semantics() == proto::RULE_SEMANTICS_WHITELIST) { options_ |= flat::OptionFlag_IS_WHITELIST; } else if (rule_.semantics() != proto::RULE_SEMANTICS_BLACKLIST) { @@ -170,33 +232,41 @@ } bool InitializeElementTypes() { - static_assert( - proto::ELEMENT_TYPE_ALL <= std::numeric_limits<uint16_t>::max(), - "Element types can not be stored in uint16_t."); - element_types_ = static_cast<uint16_t>(rule_.element_types()); + static_assert(flat::ElementType_ANY <= std::numeric_limits<uint16_t>::max(), + "Element types can not be stored in uint16_t."); - // Note: Normally we can not distinguish between the main plugin resource - // and any other loads it makes. We treat them both as OBJECT requests. - if (element_types_ & proto::ELEMENT_TYPE_OBJECT_SUBREQUEST) - element_types_ |= proto::ELEMENT_TYPE_OBJECT; + // Ensure all proto::ElementType(s) are mapped in |kElementTypeMap|. + DCHECK_EQ(proto::ELEMENT_TYPE_ALL, GetKeysMask(kElementTypeMap)); - // Ignore unknown element types. - element_types_ &= proto::ELEMENT_TYPE_ALL; - // Filtering popups is not supported. - element_types_ &= ~proto::ELEMENT_TYPE_POPUP; + element_types_ = flat::ElementType_NONE; + + for (const auto& pair : kElementTypeMap) + if (rule_.element_types() & pair.first) + element_types_ |= pair.second; + + // Normally we can not distinguish between the main plugin resource and any + // other loads it makes. We treat them both as OBJECT requests. Hence an + // OBJECT request would also match OBJECT_SUBREQUEST rules, but not the + // the other way round. + if (element_types_ & flat::ElementType_OBJECT_SUBREQUEST) + element_types_ |= flat::ElementType_OBJECT; return true; } bool InitializeActivationTypes() { static_assert( - proto::ACTIVATION_TYPE_ALL <= std::numeric_limits<uint8_t>::max(), + flat::ActivationType_ANY <= std::numeric_limits<uint8_t>::max(), "Activation types can not be stored in uint8_t."); - activation_types_ = static_cast<uint8_t>(rule_.activation_types()); - // Only the following activation types are supported, ignore the others. - activation_types_ &= - proto::ACTIVATION_TYPE_DOCUMENT | proto::ACTIVATION_TYPE_GENERICBLOCK; + // Ensure all proto::ActivationType(s) are mapped in |kActivationTypeMap|. + DCHECK_EQ(proto::ACTIVATION_TYPE_ALL, GetKeysMask(kActivationTypeMap)); + + activation_types_ = flat::ActivationType_NONE; + + for (const auto& pair : kActivationTypeMap) + if (rule_.activation_types() & pair.first) + activation_types_ |= pair.second; return true; } @@ -430,21 +500,21 @@ // Returns whether the request matches flags of the specified URL |rule|. Takes // into account: -// - |element_type| of the requested resource, if not *_UNSPECIFIED. -// - |activation_type| for a subdocument request, if not *_UNSPECIFIED. +// - |element_type| of the requested resource, if not *_NONE. +// - |activation_type| for a subdocument request, if not *_NONE. // - Whether the resource |is_third_party| w.r.t. its embedding document. bool DoesRuleFlagsMatch(const flat::UrlRule& rule, - proto::ElementType element_type, - proto::ActivationType activation_type, + flat::ElementType element_type, + flat::ActivationType activation_type, bool is_third_party) { - DCHECK((element_type == proto::ELEMENT_TYPE_UNSPECIFIED) != - (activation_type == proto::ACTIVATION_TYPE_UNSPECIFIED)); + DCHECK((element_type == flat::ElementType_NONE) != + (activation_type == flat::ActivationType_NONE)); - if (element_type != proto::ELEMENT_TYPE_UNSPECIFIED && + if (element_type != flat::ElementType_NONE && !(rule.element_types() & element_type)) { return false; } - if (activation_type != proto::ACTIVATION_TYPE_UNSPECIFIED && + if (activation_type != flat::ActivationType_NONE && !(rule.activation_types() & activation_type)) { return false; } @@ -465,8 +535,8 @@ const FlatUrlRuleList* candidates, const GURL& url, const url::Origin& document_origin, - proto::ElementType element_type, - proto::ActivationType activation_type, + flat::ElementType element_type, + flat::ActivationType activation_type, bool is_third_party, bool disable_generic_rules) { if (!candidates) @@ -497,8 +567,8 @@ const flat::UrlPatternIndex& index, const GURL& url, const url::Origin& document_origin, - proto::ElementType element_type, - proto::ActivationType activation_type, + flat::ElementType element_type, + flat::ActivationType activation_type, bool is_third_party, bool disable_generic_rules) { const FlatNGramIndex* hash_table = index.ngram_index(); @@ -552,10 +622,23 @@ proto::ActivationType activation_type, bool is_third_party, bool disable_generic_rules) const { + return FindMatch(url, first_party_origin, + ProtoToFlatElementType(element_type), + ProtoToFlatActivationType(activation_type), is_third_party, + disable_generic_rules); +} + +const flat::UrlRule* UrlPatternIndexMatcher::FindMatch( + const GURL& url, + const url::Origin& first_party_origin, + flat::ElementType element_type, + flat::ActivationType activation_type, + bool is_third_party, + bool disable_generic_rules) const { if (!flat_index_ || !url.is_valid()) return nullptr; - if ((element_type == proto::ELEMENT_TYPE_UNSPECIFIED) == - (activation_type == proto::ACTIVATION_TYPE_UNSPECIFIED)) { + if ((element_type == flat::ElementType_NONE) == + (activation_type == flat::ActivationType_NONE)) { return nullptr; }
diff --git a/components/url_pattern_index/url_pattern_index.h b/components/url_pattern_index/url_pattern_index.h index 22e84b1..8f76188 100644 --- a/components/url_pattern_index/url_pattern_index.h +++ b/components/url_pattern_index/url_pattern_index.h
@@ -124,6 +124,16 @@ bool disable_generic_rules) const; private: + // Helper function to work with flat::*Type(s). If the index contains one or + // more UrlRules that match the request, returns one of them (it is undefined + // which one). Otherwise, returns nullptr. + const flat::UrlRule* FindMatch(const GURL& url, + const url::Origin& first_party_origin, + flat::ElementType element_type, + flat::ActivationType activation_type, + bool is_third_party, + bool disable_generic_rules) const; + // Must outlive this instance. const flat::UrlPatternIndex* flat_index_;
diff --git a/components/viz/service/frame_sinks/frame_sink_manager_impl.cc b/components/viz/service/frame_sinks/frame_sink_manager_impl.cc index 51ce97d..0c156ce 100644 --- a/components/viz/service/frame_sinks/frame_sink_manager_impl.cc +++ b/components/viz/service/frame_sinks/frame_sink_manager_impl.cc
@@ -26,8 +26,8 @@ display_provider_(display_provider), binding_(this) { manager_.AddObserver(this); - dependency_tracker_ = base::MakeUnique<cc::SurfaceDependencyTracker>( - &manager_, manager_.GetPrimaryBeginFrameSource()); + dependency_tracker_ = + base::MakeUnique<cc::SurfaceDependencyTracker>(&manager_); manager_.SetDependencyTracker(dependency_tracker_.get()); }
diff --git a/components/wallpaper/BUILD.gn b/components/wallpaper/BUILD.gn index 15ae1dfa..5bd8026d 100644 --- a/components/wallpaper/BUILD.gn +++ b/components/wallpaper/BUILD.gn
@@ -8,6 +8,7 @@ "wallpaper_color_calculator.h", "wallpaper_color_calculator_observer.h", "wallpaper_color_extraction_result.h", + "wallpaper_color_profile.h", "wallpaper_files_id.cc", "wallpaper_files_id.h", "wallpaper_layout.h",
diff --git a/components/wallpaper/wallpaper_color_profile.h b/components/wallpaper/wallpaper_color_profile.h new file mode 100644 index 0000000..3112eec --- /dev/null +++ b/components/wallpaper/wallpaper_color_profile.h
@@ -0,0 +1,25 @@ +// 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 COMPONENTS_WALLPAPER_WALLPAPER_COLOR_PROFILE_H_ +#define COMPONENTS_WALLPAPER_WALLPAPER_COLOR_PROFILE_H_ + +namespace wallpaper { + +// The color profile type, ordered as the color profiles applied in +// ash::WallpaperController. +enum class ColorProfileType { + DARK_VIBRANT = 0, + NORMAL_VIBRANT, + LIGHT_VIBRANT, + DARK_MUTED, + NORMAL_MUTED, + LIGHT_MUTED, + + NUM_OF_COLOR_PROFILES, +}; + +} // namespace wallpaper + +#endif // COMPONENTS_WALLPAPER_WALLPAPER_COLOR_PROFILE_H_
diff --git a/content/app/BUILD.gn b/content/app/BUILD.gn index 93f31ef..f3c4f2b 100644 --- a/content/app/BUILD.gn +++ b/content/app/BUILD.gn
@@ -51,7 +51,6 @@ "//content/public/android:jni", "//device/bluetooth", "//device/gamepad", - "//device/generic_sensor", "//device/geolocation", "//device/power_save_blocker", "//device/sensors",
diff --git a/content/app/DEPS b/content/app/DEPS index c2fd94f..f4d19c5 100644 --- a/content/app/DEPS +++ b/content/app/DEPS
@@ -3,7 +3,6 @@ "+content", "+device/bluetooth", "+device/gamepad", - "+device/generic_sensor", "+device/geolocation", "+device/power_save_blocker", "+device/sensors",
diff --git a/content/app/android/library_loader_hooks.cc b/content/app/android/library_loader_hooks.cc index 7de91d059..46d1993 100644 --- a/content/app/android/library_loader_hooks.cc +++ b/content/app/android/library_loader_hooks.cc
@@ -26,7 +26,6 @@ #include "content/public/common/result_codes.h" #include "device/bluetooth/android/bluetooth_jni_registrar.h" #include "device/gamepad/android/gamepad_jni_registrar.h" -#include "device/generic_sensor/android/sensors_jni_registrar.h" #include "device/geolocation/android/geolocation_jni_registrar.h" #include "device/sensors/android/device_sensor_jni_registrar.h" #include "device/usb/android/usb_jni_registrar.h" @@ -90,9 +89,6 @@ if (!device::android::RegisterGeolocationJni(env)) return false; - if (!device::android::RegisterSensorsJni(env)) - return false; - if (!device::android::RegisterUsbJni(env)) return false;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 0cc7f6ac..9d7600a 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -50,7 +50,6 @@ "//components/rappor", "//components/tracing", "//components/tracing:startup_tracing", - "//components/ukm/public", "//components/url_formatter", "//components/variations", "//components/viz/common", @@ -97,6 +96,7 @@ "//media/midi:mojo", "//media/mojo:features", "//media/mojo/interfaces", + "//media/mojo/interfaces:constants", "//media/mojo/services", "//mojo/common", "//mojo/edk/system", @@ -117,6 +117,7 @@ "//services/device/public/interfaces:constants", "//services/file:lib", "//services/file/public/interfaces", + "//services/metrics/public/cpp:metrics_cpp", "//services/resource_coordinator:lib", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", "//services/service_manager", @@ -131,6 +132,7 @@ "//services/ui/public/cpp/gpu", "//services/video_capture/public/cpp", "//services/video_capture/public/interfaces:constants", + "//services/video_capture/public/uma", "//skia", "//sql", "//storage/browser",
diff --git a/content/browser/DEPS b/content/browser/DEPS index b282c92..51010eb 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -23,7 +23,6 @@ "+content/public/browser", "+device/base/synchronization", "+device/gamepad", # For gamepad API - "+device/generic_sensor", # For sensors service. "+device/geolocation", "+device/nfc", "+device/power_save_blocker",
diff --git a/content/browser/android/browser_jni_registrar.cc b/content/browser/android/browser_jni_registrar.cc index a16748d..f657268 100644 --- a/content/browser/android/browser_jni_registrar.cc +++ b/content/browser/android/browser_jni_registrar.cc
@@ -14,7 +14,6 @@ #include "content/browser/android/browser_startup_controller.h" #include "content/browser/android/content_feature_list.h" #include "content/browser/android/content_video_view.h" -#include "content/browser/android/content_view_core_impl.h" #include "content/browser/android/content_view_render_view.h" #include "content/browser/android/content_view_statics.h" #include "content/browser/android/date_time_chooser_android.h"
diff --git a/content/browser/android/content_video_view.cc b/content/browser/android/content_video_view.cc index cd4e786..056060e 100644 --- a/content/browser/android/content_video_view.cc +++ b/content/browser/android/content_video_view.cc
@@ -4,16 +4,10 @@ #include "content/browser/android/content_video_view.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" -#include "content/browser/android/content_view_core_impl.h" -#include "content/browser/media/android/browser_media_player_manager.h" -#include "content/public/common/content_switches.h" #include "jni/ContentVideoView_jni.h" using base::android::AttachCurrentThread; -using base::android::CheckException; using base::android::JavaParamRef; using base::android::JavaRef; using base::android::ScopedJavaGlobalRef;
diff --git a/content/browser/android/nfc_host.cc b/content/browser/android/nfc_host.cc index 90a17ec4..e5e7b09 100644 --- a/content/browser/android/nfc_host.cc +++ b/content/browser/android/nfc_host.cc
@@ -7,7 +7,6 @@ #include <utility> #include "base/atomic_sequence_num.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/common/service_manager_connection.h" #include "jni/NfcHost_jni.h" #include "services/device/public/interfaces/constants.mojom.h"
diff --git a/content/browser/appcache/appcache_subresource_url_factory.cc b/content/browser/appcache/appcache_subresource_url_factory.cc index 70f002df..e971ba6 100644 --- a/content/browser/appcache/appcache_subresource_url_factory.cc +++ b/content/browser/appcache/appcache_subresource_url_factory.cc
@@ -10,9 +10,9 @@ #include "content/browser/appcache/appcache_url_loader_job.h" #include "content/browser/appcache/appcache_url_loader_request.h" #include "content/browser/url_loader_factory_getter.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/resource_request.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_ptr.h"
diff --git a/content/browser/appcache/appcache_subresource_url_factory.h b/content/browser/appcache/appcache_subresource_url_factory.h index f55afc47..a5620cf 100644 --- a/content/browser/appcache/appcache_subresource_url_factory.h +++ b/content/browser/appcache/appcache_subresource_url_factory.h
@@ -6,7 +6,7 @@ #define CONTENT_BROWSER_APPCACHE_APPCACHE_SUBRESOURCE_URL_FACTORY_H_ #include "base/memory/ref_counted.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "url/gurl.h"
diff --git a/content/browser/appcache/appcache_url_loader_job.h b/content/browser/appcache/appcache_url_loader_job.h index f3470cb5d..42615a68 100644 --- a/content/browser/appcache/appcache_url_loader_job.h +++ b/content/browser/appcache/appcache_url_loader_job.h
@@ -16,8 +16,8 @@ #include "content/browser/appcache/appcache_storage.h" #include "content/browser/loader/url_loader_request_handler.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" #include "content/public/common/resource_request.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/data_pipe.h"
diff --git a/content/browser/blob_storage/blob_internals_url_loader.h b/content/browser/blob_storage/blob_internals_url_loader.h index 4dc9ef2..858584d9 100644 --- a/content/browser/blob_storage/blob_internals_url_loader.h +++ b/content/browser/blob_storage/blob_internals_url_loader.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_BROWSER_BLOB_STORAGE_BLOB_INTERNALS_URL_LOADER_H_ #define CONTENT_BROWSER_BLOB_STORAGE_BLOB_INTERNALS_URL_LOADER_H_ -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" namespace content { class ChromeBlobStorageContext;
diff --git a/content/browser/blob_storage/blob_url_loader_factory.cc b/content/browser/blob_storage/blob_url_loader_factory.cc index dbb2883..f9c2da3 100644 --- a/content/browser/blob_storage/blob_url_loader_factory.cc +++ b/content/browser/blob_storage/blob_url_loader_factory.cc
@@ -13,8 +13,8 @@ #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/browser/storage_partition_impl.h" #include "content/common/net_adapters.h" -#include "content/common/url_loader.mojom.h" #include "content/public/browser/browser_thread.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/base/io_buffer.h" #include "net/http/http_byte_range.h"
diff --git a/content/browser/blob_storage/blob_url_loader_factory.h b/content/browser/blob_storage/blob_url_loader_factory.h index 9f01143..a58effb3 100644 --- a/content/browser/blob_storage/blob_url_loader_factory.h +++ b/content/browser/blob_storage/blob_url_loader_factory.h
@@ -9,8 +9,8 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/browser_thread.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h" namespace storage {
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index 20f9660d..cfda90f4 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -926,6 +926,11 @@ #endif } +gpu::GpuChannelEstablishFactory* +BrowserMainLoop::gpu_channel_establish_factory() const { + return BrowserGpuChannelHostFactory::instance(); +} + #if defined(OS_ANDROID) void BrowserMainLoop::SynchronouslyFlushStartupTasks() { startup_task_runner_->RunAllTasksNow();
diff --git a/content/browser/browser_main_loop.h b/content/browser/browser_main_loop.h index f771cf9..7b72970 100644 --- a/content/browser/browser_main_loop.h +++ b/content/browser/browser_main_loop.h
@@ -43,6 +43,10 @@ class DiscardableSharedMemoryManager; } +namespace gpu { +class GpuChannelEstablishFactory; +} + namespace media { class AudioManager; class AudioSystem; @@ -170,6 +174,8 @@ return startup_trace_file_; } + gpu::GpuChannelEstablishFactory* gpu_channel_establish_factory() const; + #if defined(OS_ANDROID) void SynchronouslyFlushStartupTasks(); #endif // OS_ANDROID
diff --git a/content/browser/devtools/devtools_http_handler.cc b/content/browser/devtools/devtools_http_handler.cc index 6ecc1be4..498f0c40 100644 --- a/content/browser/devtools/devtools_http_handler.cc +++ b/content/browser/devtools/devtools_http_handler.cc
@@ -70,10 +70,8 @@ const char kTargetWebSocketDebuggerUrlField[] = "webSocketDebuggerUrl"; const char kTargetDevtoolsFrontendUrlField[] = "devtoolsFrontendUrl"; -// Maximum write buffer size of devtools http/websocket connections. -// TODO(rmcilroy/pfieldman): Reduce this back to 100Mb when we have -// added back pressure on the TraceComplete message protocol - crbug.com/456845. const int32_t kSendBufferSizeForDevTools = 256 * 1024 * 1024; // 256Mb +const int32_t kReceiveBufferSizeForDevTools = 100 * 1024 * 1024; // 100Mb } // namespace @@ -137,6 +135,7 @@ void ServerWrapper::AcceptWebSocket(int connection_id, const net::HttpServerRequestInfo& request) { server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools); + server_->SetReceiveBufferSize(connection_id, kReceiveBufferSizeForDevTools); server_->AcceptWebSocket(connection_id, request); }
diff --git a/content/browser/devtools/protocol/network_handler.cc b/content/browser/devtools/protocol/network_handler.cc index 4e735e2..e5a831c 100644 --- a/content/browser/devtools/protocol/network_handler.cc +++ b/content/browser/devtools/protocol/network_handler.cc
@@ -21,7 +21,6 @@ #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/common/navigation_params.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/browsing_data_remover.h" @@ -35,6 +34,7 @@ #include "content/public/common/content_switches.h" #include "content/public/common/resource_devtools_info.h" #include "content/public/common/resource_request.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "net/base/net_errors.h" #include "net/base/upload_bytes_element_reader.h"
diff --git a/content/browser/devtools/protocol/security_handler.cc b/content/browser/devtools/protocol/security_handler.cc index ba2d2e1b..0ba37a9 100644 --- a/content/browser/devtools/protocol/security_handler.cc +++ b/content/browser/devtools/protocol/security_handler.cc
@@ -14,6 +14,7 @@ #include "content/public/browser/ssl_status.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" +#include "third_party/WebKit/public/platform/WebMixedContentContextType.h" namespace content { namespace protocol { @@ -41,17 +42,39 @@ } } +std::string MixedContentTypeToProtocolMixedContentType( + blink::WebMixedContentContextType mixed_content_type) { + switch (mixed_content_type) { + case blink::WebMixedContentContextType::kNotMixedContent: + return Security::MixedContentTypeEnum::None; + case blink::WebMixedContentContextType::kBlockable: + return Security::MixedContentTypeEnum::Blockable; + case blink::WebMixedContentContextType::kOptionallyBlockable: + return Security::MixedContentTypeEnum::OptionallyBlockable; + case blink::WebMixedContentContextType::kShouldBeBlockable: + // kShouldBeBlockable is not used for explanations. + NOTREACHED(); + return Security::MixedContentTypeEnum::OptionallyBlockable; + default: + NOTREACHED(); + return Security::MixedContentTypeEnum::None; + } +} + void AddExplanations( const std::string& security_style, const std::vector<SecurityStyleExplanation>& explanations_to_add, Explanations* explanations) { for (const auto& it : explanations_to_add) { - explanations->addItem(Security::SecurityStateExplanation::Create() - .SetSecurityState(security_style) - .SetSummary(it.summary) - .SetDescription(it.description) - .SetHasCertificate(it.has_certificate) - .Build()); + explanations->addItem( + Security::SecurityStateExplanation::Create() + .SetSecurityState(security_style) + .SetSummary(it.summary) + .SetDescription(it.description) + .SetHasCertificate(it.has_certificate) + .SetMixedContentType(MixedContentTypeToProtocolMixedContentType( + it.mixed_content_type)) + .Build()); } }
diff --git a/content/browser/download/download_item_impl.cc b/content/browser/download/download_item_impl.cc index bbdd45cd..aeb9c9ba 100644 --- a/content/browser/download/download_item_impl.cc +++ b/content/browser/download/download_item_impl.cc
@@ -2140,6 +2140,30 @@ BrowserContext::GetStoragePartitionForSite(GetBrowserContext(), request_info_.site_url); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("download_manager_resume", R"( + semantics { + sender: "Download Manager" + description: + "When user resumes downloading a file, a network request is made " + "to fetch it." + trigger: + "User resumes a download." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: + "This feature cannot be disabled in settings, but it is activated " + "by direct user action." + chrome_policy { + DownloadRestrictions { + DownloadRestrictions: 3 + } + } + })"); // Avoid using the WebContents even if it's still around. Resumption requests // are consistently routed through the no-renderer code paths so that the // request will not be dropped if the WebContents (and by extension, the @@ -2147,7 +2171,7 @@ std::unique_ptr<DownloadUrlParameters> download_params( new DownloadUrlParameters(GetURL(), storage_partition->GetURLRequestContext(), - NO_TRAFFIC_ANNOTATION_YET)); + traffic_annotation)); download_params->set_file_path(GetFullPath()); if (received_slices_.size() > 0) { std::vector<DownloadItem::ReceivedSlice> slices_to_download
diff --git a/content/browser/download/drag_download_file.cc b/content/browser/download/drag_download_file.cc index 6c295a4..78611a1b0c 100644 --- a/content/browser/download/drag_download_file.cc +++ b/content/browser/download/drag_download_file.cc
@@ -68,9 +68,32 @@ RecordDownloadSource(INITIATED_BY_DRAG_N_DROP); // TODO(https://crbug.com/614134) This should use the frame actually // containing the link being dragged rather than the main frame of the tab. + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("drag_download_file", R"( + semantics { + sender: "Drag To Download" + description: + "Users can download files by dragging them out of browser and into " + "a disk related area." + trigger: "When user drags a file from the browser." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: + "This feature cannot be disabled in settings, but it is only " + "activated by direct user action." + chrome_policy { + DownloadRestrictions { + DownloadRestrictions: 3 + } + } + })"); std::unique_ptr<content::DownloadUrlParameters> params( DownloadUrlParameters::CreateForWebContentsMainFrame( - web_contents_, url_, NO_TRAFFIC_ANNOTATION_YET)); + web_contents_, url_, traffic_annotation)); params->set_referrer(referrer_); params->set_referrer_encoding(referrer_encoding_); params->set_callback(base::Bind(&DragDownloadFileUI::OnDownloadStarted,
diff --git a/content/browser/download/parallel_download_job.cc b/content/browser/download/parallel_download_job.cc index 338514cd2..4ce373f3 100644 --- a/content/browser/download/parallel_download_job.cc +++ b/content/browser/download/parallel_download_job.cc
@@ -212,11 +212,33 @@ BrowserContext::GetStoragePartitionForSite( download_item_->GetBrowserContext(), download_item_->GetSiteUrl()); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("parallel_download_job", R"( + semantics { + sender: "Parallel Download" + description: + "Chrome makes parallel request to speed up download of a file." + trigger: + "When user starts a download request, if it would be technically " + "possible, Chrome starts parallel downloading." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: "This feature cannot be disabled in settings." + chrome_policy { + DownloadRestrictions { + DownloadRestrictions: 3 + } + } + })"); // The parallel requests only use GET method. std::unique_ptr<DownloadUrlParameters> download_params( new DownloadUrlParameters(download_item_->GetURL(), storage_partition->GetURLRequestContext(), - NO_TRAFFIC_ANNOTATION_YET)); + traffic_annotation)); download_params->set_file_path(download_item_->GetFullPath()); download_params->set_last_modified(download_item_->GetLastModifiedTime()); download_params->set_etag(download_item_->GetETag());
diff --git a/content/browser/download/save_file_manager.cc b/content/browser/download/save_file_manager.cc index 256ef281..982eeac 100644 --- a/content/browser/download/save_file_manager.cc +++ b/content/browser/download/save_file_manager.cc
@@ -25,6 +25,7 @@ #include "content/public/common/previews_state.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_job_factory.h" @@ -307,8 +308,27 @@ return; } - std::unique_ptr<net::URLRequest> request( - request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL)); + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("save_file_manager", R"( + semantics { + sender: "Save File" + description: "Saving url to local file." + trigger: + "User clicks on 'Save link as...' context menu command to save a " + "link." + data: "None." + destination: WEBSITE + } + policy { + cookies_allowed: true + cookies_store: "user" + setting: + "This feature cannot be disable by settings. The request is made " + "only if user chooses 'Save link as...' in context menu." + policy_exception_justification: "Not implemented." + })"); + std::unique_ptr<net::URLRequest> request(request_context->CreateRequest( + url, net::DEFAULT_PRIORITY, NULL, traffic_annotation)); request->set_method("GET"); // The URLRequest needs to be initialized with the referrer and other
diff --git a/content/browser/fileapi/file_system_operation_runner_unittest.cc b/content/browser/fileapi/file_system_operation_runner_unittest.cc index 8825162..168d52e 100644 --- a/content/browser/fileapi/file_system_operation_runner_unittest.cc +++ b/content/browser/fileapi/file_system_operation_runner_unittest.cc
@@ -8,6 +8,8 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" @@ -193,7 +195,7 @@ base::FilePath base_dir = base_.GetPath(); file_system_context_ = new FileSystemContext( base::ThreadTaskRunnerHandle::Get().get(), - BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get(), + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}).get(), storage::ExternalMountPoints::CreateRefCounted().get(), make_scoped_refptr(new MockSpecialStoragePolicy()).get(), nullptr, std::vector<std::unique_ptr<storage::FileSystemBackend>>(),
diff --git a/content/browser/frame_host/navigator_impl.cc b/content/browser/frame_host/navigator_impl.cc index e7f78f4..dd1dc184 100644 --- a/content/browser/frame_host/navigator_impl.cc +++ b/content/browser/frame_host/navigator_impl.cc
@@ -29,7 +29,6 @@ #include "content/common/navigation_params.h" #include "content/common/page_messages.h" #include "content/common/site_isolation_policy.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/content_browser_client.h" @@ -45,6 +44,7 @@ #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" #include "content/public/common/resource_response.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/base/net_errors.h" #include "url/gurl.h" #include "url/url_util.h"
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 98efcf2..1f3d428 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -924,9 +924,11 @@ void RenderFrameHostImpl::OnAssociatedInterfaceRequest( const std::string& interface_name, mojo::ScopedInterfaceEndpointHandle handle) { + ContentBrowserClient* browser_client = GetContentClient()->browser(); if (associated_registry_->CanBindRequest(interface_name)) { associated_registry_->BindRequest(interface_name, std::move(handle)); - } else { + } else if (!browser_client->BindAssociatedInterfaceRequestFromFrame( + this, interface_name, &handle)) { delegate_->OnAssociatedInterfaceRequest(this, interface_name, std::move(handle)); } @@ -3460,6 +3462,10 @@ base::MakeUnique<resource_coordinator::ResourceCoordinatorInterface>( ServiceManagerConnection::GetForProcess()->GetConnector(), resource_coordinator::CoordinationUnitType::kFrame); + if (parent_) { + parent_->GetFrameResourceCoordinator()->AddChild( + *frame_resource_coordinator_); + } } return frame_resource_coordinator_.get(); }
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 9a1a5ac..b326ec43 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -41,10 +41,10 @@ #include "content/common/frame_replication_state.h" #include "content/common/image_downloader/image_downloader.mojom.h" #include "content/common/navigation_params.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/render_frame_host.h" #include "content/public/common/javascript_dialog_type.h" #include "content/public/common/previews_state.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "device/wake_lock/public/interfaces/wake_lock_context.mojom.h" #include "media/mojo/interfaces/interface_factory.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h"
diff --git a/content/browser/generic_sensor_browsertest.cc b/content/browser/generic_sensor_browsertest.cc index 8b3b9ee..9963d19 100644 --- a/content/browser/generic_sensor_browsertest.cc +++ b/content/browser/generic_sensor_browsertest.cc
@@ -18,14 +18,14 @@ #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_javascript_dialog_manager.h" #include "device/base/synchronization/one_writer_seqlock.h" -#include "device/generic_sensor/public/cpp/platform_sensor_configuration.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/public/cpp/system/buffer.h" +#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" #include "services/device/public/interfaces/constants.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor_provider.mojom.h" #include "services/service_manager/public/cpp/service_context.h" namespace content {
diff --git a/content/browser/gpu/browser_gpu_channel_host_factory.cc b/content/browser/gpu/browser_gpu_channel_host_factory.cc index 62d1ae1..9c77f8a 100644 --- a/content/browser/gpu/browser_gpu_channel_host_factory.cc +++ b/content/browser/gpu/browser_gpu_channel_host_factory.cc
@@ -182,10 +182,6 @@ } } -bool BrowserGpuChannelHostFactory::CanUseForTesting() { - return GpuDataManager::GetInstance()->GpuAccessAllowed(NULL); -} - void BrowserGpuChannelHostFactory::Initialize(bool establish_gpu_channel) { DCHECK(!instance_); instance_ = new BrowserGpuChannelHostFactory();
diff --git a/content/browser/gpu/browser_gpu_channel_host_factory.h b/content/browser/gpu/browser_gpu_channel_host_factory.h index ed50f12..a2ba4d1 100644 --- a/content/browser/gpu/browser_gpu_channel_host_factory.h +++ b/content/browser/gpu/browser_gpu_channel_host_factory.h
@@ -44,9 +44,6 @@ // thread stops. void CloseChannel(); - // Used to skip GpuChannelHost tests when there can be no GPU process. - static bool CanUseForTesting(); - // Overridden from gpu::GpuChannelEstablishFactory: // The factory will return a null GpuChannelHost in the callback during // shutdown.
diff --git a/content/browser/gpu/gpu_ipc_browsertests.cc b/content/browser/gpu/gpu_ipc_browsertests.cc index de30097..6073e19 100644 --- a/content/browser/gpu/gpu_ipc_browsertests.cc +++ b/content/browser/gpu/gpu_ipc_browsertests.cc
@@ -6,14 +6,15 @@ #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "build/build_config.h" +#include "content/browser/browser_main_loop.h" #include "content/browser/compositor/image_transport_factory.h" -#include "content/browser/gpu/browser_gpu_channel_host_factory.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/common/gpu_stream_constants.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/gpu_utils.h" #include "content/public/common/content_switches.h" #include "content/public/test/content_browser_test.h" +#include "gpu/ipc/client/gpu_channel_host.h" #include "services/ui/gpu/interfaces/gpu_service.mojom.h" #include "services/ui/public/cpp/gpu/context_provider_command_buffer.h" #include "third_party/skia/include/core/SkCanvas.h" @@ -59,11 +60,9 @@ ~EstablishGpuChannelHelper() {} scoped_refptr<gpu::GpuChannelHost> EstablishGpuChannelSyncRunLoop() { - if (!content::BrowserGpuChannelHostFactory::instance()) - content::BrowserGpuChannelHostFactory::Initialize(true); - - content::BrowserGpuChannelHostFactory* factory = - content::BrowserGpuChannelHostFactory::instance(); + gpu::GpuChannelEstablishFactory* factory = + content::BrowserMainLoop::GetInstance() + ->gpu_channel_establish_factory(); CHECK(factory); base::RunLoop run_loop; factory->EstablishGpuChannel(base::Bind( @@ -82,7 +81,7 @@ void SetUpOnMainThread() override { // This may leave the provider_ null in some cases, so tests need to early // out. - if (!content::BrowserGpuChannelHostFactory::CanUseForTesting()) + if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr)) return; EstablishGpuChannelHelper helper; @@ -124,15 +123,9 @@ class BrowserGpuChannelHostFactoryTest : public ContentBrowserTest { public: void SetUpOnMainThread() override { - if (!BrowserGpuChannelHostFactory::CanUseForTesting()) + if (!GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr)) return; - - // Start all tests without a gpu channel so that the tests exercise a - // consistent codepath. - if (!BrowserGpuChannelHostFactory::instance()) - BrowserGpuChannelHostFactory::Initialize(false); CHECK(GetFactory()); - ContentBrowserTest::SetUpOnMainThread(); } @@ -155,8 +148,8 @@ } protected: - BrowserGpuChannelHostFactory* GetFactory() { - return BrowserGpuChannelHostFactory::instance(); + gpu::GpuChannelEstablishFactory* GetFactory() { + return BrowserMainLoop::GetInstance()->gpu_channel_establish_factory(); } bool IsChannelEstablished() {
diff --git a/content/browser/histogram_internals_url_loader.h b/content/browser/histogram_internals_url_loader.h index a867809..15cd781 100644 --- a/content/browser/histogram_internals_url_loader.h +++ b/content/browser/histogram_internals_url_loader.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_BROWSER_HISTOGRAM_INTERNALS_URL_LOADER_H_ #define CONTENT_BROWSER_HISTOGRAM_INTERNALS_URL_LOADER_H_ -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" namespace content {
diff --git a/content/browser/loader/DEPS b/content/browser/loader/DEPS index 3622dab2..33ce038 100644 --- a/content/browser/loader/DEPS +++ b/content/browser/loader/DEPS
@@ -29,15 +29,15 @@ # TODO: To be replaced by mojo. "+content/common/resource_messages.h", - "+content/common/resource_request_completion_status.h", "+content/common/view_messages.h", + "+content/public/common/resource_request_completion_status.h", ], "downloaded_temp_file_impl\.(cc|h)": [ "-content", "+content/browser/loader/downloaded_temp_file_impl.h", "+content/browser/loader/resource_dispatcher_host_impl.h", "+content/common/content_export.h", - "+content/common/url_loader_factory.mojom.h" + "+content/public/common/url_loader_factory.mojom.h" ], "resource_buffer.*\.(cc|h)": [ "-content", @@ -67,11 +67,11 @@ "+content/browser/loader/resource_scheduler.h", "+content/browser/loader/upload_progress_tracker.h", "+content/common/content_export.h", - "+content/common/resource_request_completion_status.h", - "+content/common/url_loader.mojom.h", "+content/public/browser/global_request_id.h", + "+content/public/common/resource_request_completion_status.h", "+content/public/common/resource_response.h", "+content/public/common/resource_type.h", + "+content/public/common/url_loader.mojom.h", ], "mojo_async_resource_handler_unittest\.cc": [ "-content", @@ -82,9 +82,6 @@ "+content/browser/loader/resource_dispatcher_host_impl.h", "+content/browser/loader/resource_request_info_impl.h", "+content/browser/loader/resource_scheduler.h", - "+content/common/resource_request_completion_status.h", - "+content/common/url_loader.mojom.h", - "+content/common/url_loader_factory.mojom.h", "+content/public/browser/appcache_service.h", "+content/public/browser/navigation_data.h", "+content/public/browser/resource_context.h", @@ -93,8 +90,11 @@ "+content/public/browser/stream_info.h", "+content/public/common/previews_state.h", "+content/public/common/resource_request.h", + "+content/public/common/resource_request_completion_status.h", "+content/public/common/resource_response.h", "+content/public/common/resource_type.h", + "+content/public/common/url_loader.mojom.h", + "+content/public/common/url_loader_factory.mojom.h", "+content/public/test/test_browser_context.h", "+content/public/test/test_browser_thread_bundle.h", ], @@ -127,7 +127,6 @@ "+content/browser/loader/throttling_resource_handler.h", "+content/browser/loader/wake_lock_resource_throttle.h", "+content/common/resource_request_body.h", - "+content/common/url_loader.mojom.h", "+content/public/browser/global_request_id.h", "+content/public/browser/resource_dispatcher_host.h", "+content/public/browser/resource_dispatcher_host_delegate.h", @@ -135,6 +134,7 @@ "+content/public/browser/resource_throttle.h", "+content/public/common/previews_state.h", "+content/public/common/resource_request_body.h", + "+content/public/common/url_loader.mojom.h", # TODO: These all have to be removed. "+content/browser/appcache/appcache_interceptor.h", @@ -180,9 +180,9 @@ # TODO: To be replaced by mojo. "+content/common/resource_messages.h", - "+content/common/resource_request_completion_status.h", "+content/common/view_messages.h", "+content/public/common/resource_request.h", + "+content/public/common/resource_request_completion_status.h", ], "resource_handler\.(cc|h)": [ "-content", @@ -230,13 +230,13 @@ "+content/browser/loader/resource_request_info_impl.h", "+content/browser/loader/resource_requester_info.h", "+content/common/content_export.h", - "+content/common/url_loader.mojom.h", "+content/public/browser/global_request_id.h", "+content/public/browser/resource_request_info.h", "+content/public/common/previews_state.h", "+content/public/common/referrer.h", "+content/public/common/resource_request_body.h", "+content/public/common/resource_type.h", + "+content/public/common/url_loader.mojom.h", # TODO: these all have to be removed. "+content/browser/frame_host/frame_tree_node.h", @@ -304,10 +304,10 @@ "test_url_loader_client\.(cc|h)": [ "-content", "+content/browser/loader/test_url_loader_client.h", - "+content/common/resource_request_completion_status.h", - "+content/common/url_loader.mojom.h", - "+content/common/url_loader_factory.mojom.h", + "+content/public/common/resource_request_completion_status.h", "+content/public/common/resource_response.h", + "+content/public/common/url_loader.mojom.h", + "+content/public/common/url_loader_factory.mojom.h", ], "upload_progress_tracker\.(cc|h)": [ "-content", @@ -320,9 +320,9 @@ "+content/browser/loader/resource_requester_info.h", "+content/browser/loader/url_loader_factory_impl.h", "+content/common/content_export.h", - "+content/common/url_loader.mojom.h", - "+content/common/url_loader_factory.mojom.h", "+content/public/common/resource_request.h", + "+content/public/common/url_loader.mojom.h", + "+content/public/common/url_loader_factory.mojom.h", ], "url_loader_factory_impl_unittest\.cc": [ "-content", @@ -334,13 +334,13 @@ "+content/browser/loader/resource_request_info_impl.h", "+content/browser/loader/url_loader_factory_impl.h", "+content/browser/loader_delegate_impl.h", - "+content/common/resource_request_completion_status.h", - "+content/common/url_loader.mojom.h", - "+content/common/url_loader_factory.mojom.h", "+content/public/browser/resource_context.h", "+content/public/browser/resource_dispatcher_host_delegate.h", "+content/public/common/content_paths.h", "+content/public/common/resource_request.h", + "+content/public/common/resource_request_completion_status.h", + "+content/public/common/url_loader.mojom.h", + "+content/public/common/url_loader_factory.mojom.h", "+content/public/test/test_browser_context.h", "+content/public/test/test_browser_thread_bundle.h",
diff --git a/content/browser/loader/async_resource_handler.cc b/content/browser/loader/async_resource_handler.cc index a9b2e0e..c8c8dd0 100644 --- a/content/browser/loader/async_resource_handler.cc +++ b/content/browser/loader/async_resource_handler.cc
@@ -25,8 +25,8 @@ #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/upload_progress_tracker.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/common/view_messages.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "ipc/ipc_message_macros.h" #include "net/base/io_buffer.h"
diff --git a/content/browser/loader/downloaded_temp_file_impl.h b/content/browser/loader/downloaded_temp_file_impl.h index 160511b..0ef0231 100644 --- a/content/browser/loader/downloaded_temp_file_impl.h +++ b/content/browser/loader/downloaded_temp_file_impl.h
@@ -7,7 +7,7 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" namespace content {
diff --git a/content/browser/loader/mojo_async_resource_handler.cc b/content/browser/loader/mojo_async_resource_handler.cc index 7ec6e4a..1a84825 100644 --- a/content/browser/loader/mojo_async_resource_handler.cc +++ b/content/browser/loader/mojo_async_resource_handler.cc
@@ -23,8 +23,8 @@ #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/resource_scheduler.h" #include "content/browser/loader/upload_progress_tracker.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/browser/global_request_id.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "mojo/public/c/system/data_pipe.h" #include "mojo/public/cpp/bindings/message.h"
diff --git a/content/browser/loader/mojo_async_resource_handler.h b/content/browser/loader/mojo_async_resource_handler.h index bbe3370..e139f12 100644 --- a/content/browser/loader/mojo_async_resource_handler.h +++ b/content/browser/loader/mojo_async_resource_handler.h
@@ -16,8 +16,8 @@ #include "content/browser/loader/resource_handler.h" #include "content/browser/loader/upload_progress_tracker.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h"
diff --git a/content/browser/loader/mojo_async_resource_handler_unittest.cc b/content/browser/loader/mojo_async_resource_handler_unittest.cc index 92fdb49..1fe6c2b 100644 --- a/content/browser/loader/mojo_async_resource_handler_unittest.cc +++ b/content/browser/loader/mojo_async_resource_handler_unittest.cc
@@ -24,9 +24,6 @@ #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/resource_scheduler.h" #include "content/browser/loader/test_url_loader_client.h" -#include "content/common/resource_request_completion_status.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/appcache_service.h" #include "content/public/browser/navigation_data.h" #include "content/public/browser/resource_context.h" @@ -34,8 +31,11 @@ #include "content/public/browser/resource_throttle.h" #include "content/public/browser/stream_info.h" #include "content/public/common/previews_state.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_browser_thread_bundle.h" #include "mojo/public/c/system/data_pipe.h"
diff --git a/content/browser/loader/navigation_url_loader_delegate.h b/content/browser/loader/navigation_url_loader_delegate.h index c31a9e0..34723cf 100644 --- a/content/browser/loader/navigation_url_loader_delegate.h +++ b/content/browser/loader/navigation_url_loader_delegate.h
@@ -10,7 +10,7 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/system/data_pipe.h" namespace net {
diff --git a/content/browser/loader/navigation_url_loader_network_service.cc b/content/browser/loader/navigation_url_loader_network_service.cc index 588f30c..d558945 100644 --- a/content/browser/loader/navigation_url_loader_network_service.cc +++ b/content/browser/loader/navigation_url_loader_network_service.cc
@@ -27,7 +27,6 @@ #include "content/browser/webui/url_data_manager_backend.h" #include "content/browser/webui/web_ui_url_loader_factory.h" #include "content/common/throttling_url_loader.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" @@ -38,6 +37,7 @@ #include "content/public/browser/stream_handle.h" #include "content/public/common/referrer.h" #include "content/public/common/url_constants.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/base/load_flags.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_request_context.h"
diff --git a/content/browser/loader/navigation_url_loader_network_service.h b/content/browser/loader/navigation_url_loader_network_service.h index 6e57f8f..c15a4dad 100644 --- a/content/browser/loader/navigation_url_loader_network_service.h +++ b/content/browser/loader/navigation_url_loader_network_service.h
@@ -8,8 +8,8 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "content/browser/loader/navigation_url_loader.h" -#include "content/common/url_loader.mojom.h" #include "content/public/browser/ssl_status.h" +#include "content/public/common/url_loader.mojom.h" namespace net { struct RedirectInfo;
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index 0ccbee7..88185f1 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -74,7 +74,6 @@ #include "content/browser/streams/stream_registry.h" #include "content/common/net/url_request_service_worker_data.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/common/site_isolation_policy.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_thread.h" @@ -91,6 +90,7 @@ #include "content/public/common/content_switches.h" #include "content/public/common/resource_request.h" #include "content/public/common/resource_request_body.h" +#include "content/public/common/resource_request_completion_status.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_message_start.h" #include "net/base/auth.h"
diff --git a/content/browser/loader/resource_dispatcher_host_impl.h b/content/browser/loader/resource_dispatcher_host_impl.h index 49673ff9..0b3d32c 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.h +++ b/content/browser/loader/resource_dispatcher_host_impl.h
@@ -30,7 +30,6 @@ #include "content/browser/loader/global_routing_id.h" #include "content/browser/loader/resource_loader_delegate.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/resource_dispatcher_host.h" #include "content/public/browser/resource_request_info.h" @@ -38,6 +37,7 @@ #include "content/public/common/previews_state.h" #include "content/public/common/request_context_type.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" #include "ipc/ipc_message.h" #include "net/base/load_states.h" #include "net/base/request_priority.h"
diff --git a/content/browser/loader/resource_message_filter.h b/content/browser/loader/resource_message_filter.h index eead286..b318a552 100644 --- a/content/browser/loader/resource_message_filter.h +++ b/content/browser/loader/resource_message_filter.h
@@ -14,10 +14,10 @@ #include "base/sequenced_task_runner_helpers.h" #include "base/single_thread_task_runner.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/browser_associated_interface.h" #include "content/public/browser/browser_message_filter.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace storage {
diff --git a/content/browser/loader/resource_request_info_impl.h b/content/browser/loader/resource_request_info_impl.h index e03a6876..a306acb 100644 --- a/content/browser/loader/resource_request_info_impl.h +++ b/content/browser/loader/resource_request_info_impl.h
@@ -16,13 +16,13 @@ #include "base/supports_user_data.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/browser/loader/resource_requester_info.h" -#include "content/common/url_loader.mojom.h" #include "content/public/browser/navigation_ui_data.h" #include "content/public/browser/resource_request_info.h" #include "content/public/common/previews_state.h" #include "content/public/common/referrer.h" #include "content/public/common/resource_request_body.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" #include "net/base/load_states.h" namespace content {
diff --git a/content/browser/loader/test_url_loader_client.h b/content/browser/loader/test_url_loader_client.h index 3e10b7a..bb5e249 100644 --- a/content/browser/loader/test_url_loader_client.h +++ b/content/browser/loader/test_url_loader_client.h
@@ -10,10 +10,10 @@ #include "base/callback.h" #include "base/macros.h" -#include "content/common/resource_request_completion_status.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/c/system/data_pipe.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/url_request/redirect_info.h"
diff --git a/content/browser/loader/url_loader_factory_impl.cc b/content/browser/loader/url_loader_factory_impl.cc index 2c82c87..2de2e1f 100644 --- a/content/browser/loader/url_loader_factory_impl.cc +++ b/content/browser/loader/url_loader_factory_impl.cc
@@ -7,8 +7,8 @@ #include "base/memory/ptr_util.h" #include "content/browser/loader/resource_dispatcher_host_impl.h" #include "content/browser/loader/resource_requester_info.h" -#include "content/common/url_loader.mojom.h" #include "content/public/common/resource_request.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/strong_binding.h" namespace content {
diff --git a/content/browser/loader/url_loader_factory_impl.h b/content/browser/loader/url_loader_factory_impl.h index 39404f7..6177975c 100644 --- a/content/browser/loader/url_loader_factory_impl.h +++ b/content/browser/loader/url_loader_factory_impl.h
@@ -9,7 +9,7 @@ #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace content {
diff --git a/content/browser/loader/url_loader_factory_impl_unittest.cc b/content/browser/loader/url_loader_factory_impl_unittest.cc index a15126d..ab9dd1fc 100644 --- a/content/browser/loader/url_loader_factory_impl_unittest.cc +++ b/content/browser/loader/url_loader_factory_impl_unittest.cc
@@ -28,13 +28,13 @@ #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/test_url_loader_client.h" #include "content/browser/loader_delegate_impl.h" -#include "content/common/resource_request_completion_status.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/resource_context.h" #include "content/public/browser/resource_dispatcher_host_delegate.h" #include "content/public/common/content_paths.h" #include "content/public/common/resource_request.h" +#include "content/public/common/resource_request_completion_status.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_browser_thread_bundle.h" #include "mojo/public/c/system/data_pipe.h"
diff --git a/content/browser/loader/url_loader_request_handler.h b/content/browser/loader/url_loader_request_handler.h index f52974c0..fb0a1f4b 100644 --- a/content/browser/loader/url_loader_request_handler.h +++ b/content/browser/loader/url_loader_request_handler.h
@@ -8,8 +8,8 @@ #include <memory> #include "base/callback_forward.h" #include "base/macros.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" namespace content {
diff --git a/content/browser/media/media_interface_proxy.cc b/content/browser/media/media_interface_proxy.cc index 0c95324..c7c76d3 100644 --- a/content/browser/media/media_interface_proxy.cc +++ b/content/browser/media/media_interface_proxy.cc
@@ -13,6 +13,7 @@ #include "content/public/common/content_client.h" #include "content/public/common/service_manager_connection.h" #include "media/mojo/features.h" +#include "media/mojo/interfaces/constants.mojom.h" #include "media/mojo/interfaces/media_service.mojom.h" #include "media/mojo/services/media_interface_provider.h" #include "services/service_manager/public/cpp/connector.h" @@ -123,7 +124,7 @@ media::mojom::MediaServicePtr media_service; service_manager::Connector* connector = ServiceManagerConnection::GetForProcess()->GetConnector(); - connector->BindInterface("media", &media_service); + connector->BindInterface(media::mojom::kMediaServiceName, &media_service); media_service->CreateInterfaceFactory(MakeRequest(&interface_factory_ptr_), std::move(interfaces)); interface_factory_ptr_.set_connection_error_handler(base::Bind(
diff --git a/content/browser/media/media_internals.cc b/content/browser/media/media_internals.cc index 84b9b9d..d5482d90 100644 --- a/content/browser/media/media_internals.cc +++ b/content/browser/media/media_internals.cc
@@ -19,8 +19,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/browser/renderer_host/media/media_stream_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -34,6 +32,8 @@ #include "media/base/media_log_event.h" #include "media/base/watch_time_keys.h" #include "media/filters/gpu_video_decoder.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #if !defined(OS_ANDROID) #include "media/filters/decrypting_video_decoder.h"
diff --git a/content/browser/net/reporting_service_proxy.cc b/content/browser/net/reporting_service_proxy.cc index c6785a2..b5d17d0 100644 --- a/content/browser/net/reporting_service_proxy.cc +++ b/content/browser/net/reporting_service_proxy.cc
@@ -14,6 +14,7 @@ #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "net/reporting/reporting_report.h" #include "net/reporting/reporting_service.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" @@ -40,13 +41,17 @@ net::URLRequestContext* request_context = request_context_getter_->GetURLRequestContext(); - if (!request_context) + if (!request_context) { + net::ReportingReport::RecordReportDiscardedForNoURLRequestContext(); return; + } net::ReportingService* reporting_service = request_context->reporting_service(); - if (!reporting_service) + if (!reporting_service) { + net::ReportingReport::RecordReportDiscardedForNoReportingService(); return; + } reporting_service->QueueReport(url, group, type, std::move(const_body)); }
diff --git a/content/browser/payments/payment_app_browsertest.cc b/content/browser/payments/payment_app_browsertest.cc index bab82aec..9d97a40 100644 --- a/content/browser/payments/payment_app_browsertest.cc +++ b/content/browser/payments/payment_app_browsertest.cc
@@ -84,7 +84,7 @@ ASSERT_EQ("registered", script_result); } - std::map<std::string, int64_t> GetAllPaymentInstrumentRegistrationIDs() { + std::vector<int64_t> GetAllPaymentAppRegistrationIDs() { base::RunLoop run_loop; PaymentAppProvider::PaymentApps apps; PaymentAppProvider::GetInstance()->GetAllPaymentApps( @@ -93,12 +93,9 @@ &apps)); run_loop.Run(); - std::map<std::string, int64_t> registrationIds; + std::vector<int64_t> registrationIds; for (const auto& app_info : apps) { - for (const auto& instrument : app_info.second->instruments) { - registrationIds.insert(std::pair<std::string, int64_t>( - instrument->instrument_key, app_info.second->registration_id)); - } + registrationIds.push_back(app_info.second->registration_id); } return registrationIds; @@ -170,18 +167,16 @@ IN_PROC_BROWSER_TEST_F(PaymentAppBrowserTest, PaymentAppInvocation) { RegisterPaymentApp(); - std::map<std::string, int64_t> registrationIds = - GetAllPaymentInstrumentRegistrationIDs(); - ASSERT_EQ(2U, registrationIds.size()); + std::vector<int64_t> registrationIds = GetAllPaymentAppRegistrationIDs(); + ASSERT_EQ(1U, registrationIds.size()); PaymentAppResponsePtr response(InvokePaymentAppWithTestData( - registrationIds.at("basic-card-payment-app-id"), "basic-card", - "basic-card-payment-app-id")); + registrationIds[0], "basic-card", "basic-card-payment-app-id")); ASSERT_EQ("test", response->method_name); ClearStoragePartitionData(); - registrationIds = GetAllPaymentInstrumentRegistrationIDs(); + registrationIds = GetAllPaymentAppRegistrationIDs(); ASSERT_EQ(0U, registrationIds.size()); EXPECT_EQ("https://example.com/", PopConsoleString() /* topLevelOrigin */); @@ -206,20 +201,18 @@ IN_PROC_BROWSER_TEST_F(PaymentAppBrowserTest, PaymentAppOpenWindowFailed) { RegisterPaymentApp(); - std::map<std::string, int64_t> registrationIds = - GetAllPaymentInstrumentRegistrationIDs(); - ASSERT_EQ(2U, registrationIds.size()); + std::vector<int64_t> registrationIds = GetAllPaymentAppRegistrationIDs(); + ASSERT_EQ(1U, registrationIds.size()); PaymentAppResponsePtr response(InvokePaymentAppWithTestData( - registrationIds.at("bobpay-payment-app-id"), "https://bobpay.com", - "bobpay-payment-app-id")); + registrationIds[0], "https://bobpay.com", "bobpay-payment-app-id")); // InvokePaymentAppCallback returns empty method_name in case of failure, like // in PaymentRequestRespondWithObserver::OnResponseRejected. ASSERT_EQ("", response->method_name); ClearStoragePartitionData(); - registrationIds = GetAllPaymentInstrumentRegistrationIDs(); + registrationIds = GetAllPaymentAppRegistrationIDs(); ASSERT_EQ(0U, registrationIds.size()); EXPECT_EQ("https://example.com/", PopConsoleString() /* topLevelOrigin */);
diff --git a/content/browser/payments/payment_app_database.cc b/content/browser/payments/payment_app_database.cc index cc7b7b3..c0825107 100644 --- a/content/browser/payments/payment_app_database.cc +++ b/content/browser/payments/payment_app_database.cc
@@ -17,7 +17,6 @@ #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/service_worker/service_worker_registration.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/stored_payment_instrument.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" @@ -105,35 +104,6 @@ return app; } -std::unique_ptr<StoredPaymentInstrument> ToStoredPaymentInstrument( - const std::string& input) { - StoredPaymentInstrumentProto instrument_proto; - if (!instrument_proto.ParseFromString(input)) - return std::unique_ptr<StoredPaymentInstrument>(); - - std::unique_ptr<StoredPaymentInstrument> instrument = - base::MakeUnique<StoredPaymentInstrument>(); - instrument->instrument_key = instrument_proto.instrument_key(); - instrument->origin = GURL(instrument_proto.origin()); - instrument->name = instrument_proto.name(); - - if (!instrument_proto.decoded_instrument_icon().empty()) { - std::string icon_raw_data; - base::Base64Decode(instrument_proto.decoded_instrument_icon(), - &icon_raw_data); - // Note that the icon has been decoded to PNG raw data regardless of the - // original icon format that was downloaded. - gfx::Image icon_image = gfx::Image::CreateFrom1xPNGBytes( - reinterpret_cast<const unsigned char*>(icon_raw_data.data()), - icon_raw_data.size()); - instrument->icon = base::MakeUnique<SkBitmap>(icon_image.AsBitmap()); - } - for (const auto& method : instrument_proto.enabled_methods()) - instrument->enabled_methods.push_back(method); - - return instrument; -} - } // namespace PaymentAppDatabase::PaymentAppDatabase( @@ -302,7 +272,8 @@ StoredPaymentAppProto payment_app_proto; payment_app_proto.set_registration_id(registration->id()); - payment_app_proto.set_origin(registration->pattern().GetOrigin().spec()); + payment_app_proto.set_origin( + url::Origin(registration->pattern().GetOrigin()).Serialize()); payment_app_proto.set_name(name.empty() ? payment_app_proto.origin() : name); payment_app_proto.set_icon(icon); @@ -391,11 +362,17 @@ } for (const auto& item_of_raw_data : raw_data) { - std::unique_ptr<StoredPaymentInstrument> instrument = - ToStoredPaymentInstrument(item_of_raw_data.second); - if (!instrument || !base::ContainsKey(apps, instrument->origin)) + StoredPaymentInstrumentProto instrument_proto; + if (!instrument_proto.ParseFromString(item_of_raw_data.second)) continue; - apps[instrument->origin]->instruments.push_back(std::move(instrument)); + + GURL origin = GURL(instrument_proto.origin()); + if (!base::ContainsKey(apps, origin)) + continue; + + for (const auto& method : instrument_proto.enabled_methods()) { + apps[origin]->enabled_methods.push_back(method); + } } std::move(callback).Run(std::move(apps));
diff --git a/content/browser/payments/payment_app_info_fetcher.cc b/content/browser/payments/payment_app_info_fetcher.cc index f4d68e87..cc23276 100644 --- a/content/browser/payments/payment_app_info_fetcher.cc +++ b/content/browser/payments/payment_app_info_fetcher.cc
@@ -20,7 +20,9 @@ // TODO(gogerald): Choose appropriate icon size dynamically on different // platforms. -const int kPaymentAppIdealIconSize = 64; +// Here we choose a large ideal icon size to be big enough for all platforms. +// Note that we only scale down for this icon size but not scale up. +const int kPaymentAppIdealIconSize = 0xFFFF; const int kPaymentAppMinimumIconSize = 0; } // namespace
diff --git a/content/browser/payments/payment_app_provider_impl_unittest.cc b/content/browser/payments/payment_app_provider_impl_unittest.cc index beeaa902..a174e45 100644 --- a/content/browser/payments/payment_app_provider_impl_unittest.cc +++ b/content/browser/payments/payment_app_provider_impl_unittest.cc
@@ -120,19 +120,27 @@ GURL("https://bobpay.com/b"), GURL("https://bobpay.com/b/script.js")); PaymentHandlerStatus status; - SetPaymentInstrument(manager1, "test_key1", PaymentInstrument::New(), + PaymentInstrumentPtr instrument_1 = PaymentInstrument::New(); + instrument_1->enabled_methods.push_back("hellopay"); + SetPaymentInstrument(manager1, "test_key1", std::move(instrument_1), base::Bind(&SetPaymentInstrumentCallback, &status)); - SetPaymentInstrument(manager2, "test_key2", PaymentInstrument::New(), + + PaymentInstrumentPtr instrument_2 = PaymentInstrument::New(); + instrument_2->enabled_methods.push_back("hellopay"); + SetPaymentInstrument(manager2, "test_key2", std::move(instrument_2), base::Bind(&SetPaymentInstrumentCallback, &status)); - SetPaymentInstrument(manager2, "test_key3", PaymentInstrument::New(), + + PaymentInstrumentPtr instrument_3 = PaymentInstrument::New(); + instrument_3->enabled_methods.push_back("bobpay"); + SetPaymentInstrument(manager2, "test_key3", std::move(instrument_3), base::Bind(&SetPaymentInstrumentCallback, &status)); PaymentAppProvider::PaymentApps apps; GetAllPaymentApps(base::Bind(&GetAllPaymentAppsCallback, &apps)); ASSERT_EQ(2U, apps.size()); - ASSERT_EQ(1U, apps[GURL("https://hellopay.com/")]->instruments.size()); - ASSERT_EQ(2U, apps[GURL("https://bobpay.com/")]->instruments.size()); + ASSERT_EQ(1U, apps[GURL("https://hellopay.com/")]->enabled_methods.size()); + ASSERT_EQ(2U, apps[GURL("https://bobpay.com/")]->enabled_methods.size()); } } // namespace content
diff --git a/content/browser/pointer_lock_browsertest.cc b/content/browser/pointer_lock_browsertest.cc index da32306d..8129447 100644 --- a/content/browser/pointer_lock_browsertest.cc +++ b/content/browser/pointer_lock_browsertest.cc
@@ -346,6 +346,7 @@ wheel_event.SetPositionInWidget(10, 11); wheel_event.delta_x = -12; wheel_event.delta_y = -13; + wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; router->RouteMouseWheelEvent(root_view, &wheel_event, ui::LatencyInfo()); // Make sure that the renderer handled the input event.
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index 6e363825..0cd9667 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -51,8 +51,8 @@ #include "components/viz/service/display_embedder/compositor_overlay_candidate_validator_android.h" #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" +#include "content/browser/browser_main_loop.h" #include "content/browser/compositor/surface_utils.h" -#include "content/browser/gpu/browser_gpu_channel_host_factory.h" #include "content/browser/gpu/browser_gpu_memory_buffer_manager.h" #include "content/browser/gpu/compositor_util.h" #include "content/browser/renderer_host/render_widget_host_impl.h" @@ -411,9 +411,11 @@ gpu::SharedMemoryLimits shared_memory_limits, ContextProviderCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel( - base::Bind(&CreateContextProviderAfterGpuChannelEstablished, handle, - attributes, shared_memory_limits, callback)); + BrowserMainLoop::GetInstance() + ->gpu_channel_establish_factory() + ->EstablishGpuChannel( + base::Bind(&CreateContextProviderAfterGpuChannelEstablished, handle, + attributes, shared_memory_limits, callback)); } // static @@ -687,8 +689,10 @@ this, &CompositorImpl::OnGpuChannelTimeout); DCHECK(surface_handle_ != gpu::kNullSurfaceHandle); - BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel(base::Bind( - &CompositorImpl::OnGpuChannelEstablished, weak_factory_.GetWeakPtr())); + BrowserMainLoop::GetInstance() + ->gpu_channel_establish_factory() + ->EstablishGpuChannel(base::Bind(&CompositorImpl::OnGpuChannelEstablished, + weak_factory_.GetWeakPtr())); } void CompositorImpl::OnGpuChannelTimeout() {
diff --git a/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc b/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc index 1402f94..62e4295 100644 --- a/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc +++ b/content/browser/renderer_host/input/render_widget_host_latency_tracker.cc
@@ -11,11 +11,11 @@ #include "base/metrics/histogram_macros.h" #include "build/build_config.h" #include "components/rappor/public/rappor_utils.h" -#include "components/ukm/public/ukm_entry_builder.h" #include "content/browser/renderer_host/render_widget_host_delegate.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/content_client.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" #include "ui/events/blink/web_input_event_traits.h" #include "ui/latency/latency_histogram_macros.h"
diff --git a/content/browser/renderer_host/input/render_widget_host_latency_tracker.h b/content/browser/renderer_host/input/render_widget_host_latency_tracker.h index 067be16..00af80a 100644 --- a/content/browser/renderer_host/input/render_widget_host_latency_tracker.h +++ b/content/browser/renderer_host/input/render_widget_host_latency_tracker.h
@@ -10,10 +10,10 @@ #include <vector> #include "base/macros.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/browser/renderer_host/event_with_latency_info.h" #include "content/common/content_export.h" #include "content/common/input/input_event_ack_state.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "ui/latency/latency_info.h" #include "ui/latency/latency_tracker.h"
diff --git a/content/browser/renderer_host/media/media_devices_dispatcher_host.cc b/content/browser/renderer_host/media/media_devices_dispatcher_host.cc index ece23f0..4fcd2db 100644 --- a/content/browser/renderer_host/media/media_devices_dispatcher_host.cc +++ b/content/browser/renderer_host/media/media_devices_dispatcher_host.cc
@@ -10,6 +10,7 @@ #include <vector> #include "base/bind_helpers.h" +#include "base/command_line.h" #include "base/memory/ptr_util.h" #include "content/browser/bad_message.h" #include "content/browser/media/media_devices_util.h" @@ -22,6 +23,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/common/media_stream_request.h" #include "media/audio/audio_system.h" +#include "media/base/media_switches.h" #include "media/base/video_facing.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "services/service_manager/public/cpp/interface_provider.h" @@ -498,17 +500,21 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_GT(pending_audio_input_capabilities_requests_.size(), 0U); DCHECK(current_audio_input_capabilities_.empty()); + DCHECK_EQ(num_pending_audio_input_parameters_, 0U); for (const auto& device_info : enumeration[MEDIA_DEVICE_TYPE_AUDIO_INPUT]) { ::mojom::AudioInputDeviceCapabilities capabilities( - device_info.device_id, media::AudioParameters()); + device_info.device_id, + media::AudioParameters::UnavailableDeviceParams()); if (device_info.device_id == default_device_id) current_audio_input_capabilities_.insert( current_audio_input_capabilities_.begin(), std::move(capabilities)); else current_audio_input_capabilities_.push_back(std::move(capabilities)); } - // No devices, no need to read audio parameters. - if (current_audio_input_capabilities_.empty()) { + // No devices or fake devices, no need to read audio parameters. + if (current_audio_input_capabilities_.empty() || + base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kUseFakeDeviceForMediaStream)) { FinalizeGetAudioInputCapabilities(); return; } @@ -531,9 +537,10 @@ DCHECK_GT(current_audio_input_capabilities_.size(), index); DCHECK_GT(num_pending_audio_input_parameters_, 0U); - current_audio_input_capabilities_[index].parameters = - parameters.IsValid() ? parameters - : media::AudioParameters::UnavailableDeviceParams(); + if (parameters.IsValid()) + current_audio_input_capabilities_[index].parameters = parameters; + + DCHECK(current_audio_input_capabilities_[index].parameters.IsValid()); if (--num_pending_audio_input_parameters_ == 0U) FinalizeGetAudioInputCapabilities(); } @@ -541,7 +548,7 @@ void MediaDevicesDispatcherHost::FinalizeGetAudioInputCapabilities() { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_GT(pending_audio_input_capabilities_requests_.size(), 0U); - DCHECK_EQ(0U, num_pending_audio_input_parameters_); + DCHECK_EQ(num_pending_audio_input_parameters_, 0U); for (auto& request : pending_audio_input_capabilities_requests_) { std::move(request.client_callback)
diff --git a/content/browser/renderer_host/media/media_stream_manager.cc b/content/browser/renderer_host/media/media_stream_manager.cc index 53fc48b..298e085e7 100644 --- a/content/browser/renderer_host/media/media_stream_manager.cc +++ b/content/browser/renderer_host/media/media_stream_manager.cc
@@ -55,6 +55,7 @@ #include "media/capture/video/video_capture_device_factory.h" #include "media/capture/video/video_capture_system_impl.h" #include "services/video_capture/public/cpp/constants.h" +#include "services/video_capture/public/uma/video_capture_service_event.h" #include "url/gurl.h" #include "url/origin.h" @@ -428,6 +429,8 @@ InProcessVideoCaptureProvider::CreateInstanceForNonDeviceCapture( std::move(device_task_runner))); } else { + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::BROWSER_USING_LEGACY_CAPTURE); video_capture_provider = InProcessVideoCaptureProvider::CreateInstance( base::MakeUnique<media::VideoCaptureSystemImpl>( media::VideoCaptureDeviceFactory::CreateFactory(
diff --git a/content/browser/renderer_host/media/service_video_capture_provider.cc b/content/browser/renderer_host/media/service_video_capture_provider.cc index 4d18201..2cd5701 100644 --- a/content/browser/renderer_host/media/service_video_capture_provider.cc +++ b/content/browser/renderer_host/media/service_video_capture_provider.cc
@@ -9,6 +9,7 @@ #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" #include "services/video_capture/public/interfaces/constants.mojom.h" +#include "services/video_capture/public/uma/video_capture_service_event.h" namespace content { @@ -21,12 +22,12 @@ ServiceVideoCaptureProvider::~ServiceVideoCaptureProvider() { DCHECK(sequence_checker_.CalledOnValidSequence()); + UninitializeInternal(ReasonForUninitialize::kShutdown); } void ServiceVideoCaptureProvider::Uninitialize() { DCHECK(sequence_checker_.CalledOnValidSequence()); - device_factory_.reset(); - device_factory_provider_.reset(); + UninitializeInternal(ReasonForUninitialize::kClientRequest); } void ServiceVideoCaptureProvider::GetDeviceInfosAsync( @@ -48,6 +49,15 @@ if (device_factory_provider_.is_bound()) return; + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::BROWSER_CONNECTING_TO_SERVICE); + if (time_of_last_uninitialize_ != base::TimeTicks()) { + video_capture::uma::LogDurationUntilReconnect(base::TimeTicks::Now() - + time_of_last_uninitialize_); + } + + time_of_last_connect_ = base::TimeTicks::Now(); + connector_->BindInterface(video_capture::mojom::kServiceName, &device_factory_provider_); device_factory_provider_->ConnectToDeviceFactory( @@ -63,7 +73,34 @@ // This may indicate that the video capture service has crashed. Uninitialize // here, so that a new connection will be established when clients try to // reconnect. - Uninitialize(); + UninitializeInternal(ReasonForUninitialize::kConnectionLost); +} + +void ServiceVideoCaptureProvider::UninitializeInternal( + ReasonForUninitialize reason) { + if (!device_factory_.is_bound()) { + return; + } + base::TimeDelta duration_since_last_connect(base::TimeTicks::Now() - + time_of_last_connect_); + switch (reason) { + case ReasonForUninitialize::kShutdown: + case ReasonForUninitialize::kClientRequest: + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::BROWSER_CLOSING_CONNECTION_TO_SERVICE); + video_capture::uma::LogDurationFromLastConnectToClosingConnection( + duration_since_last_connect); + break; + case ReasonForUninitialize::kConnectionLost: + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::BROWSER_LOST_CONNECTION_TO_SERVICE); + video_capture::uma::LogDurationFromLastConnectToConnectionLost( + duration_since_last_connect); + break; + } + device_factory_.reset(); + device_factory_provider_.reset(); + time_of_last_uninitialize_ = base::TimeTicks::Now(); } } // namespace content
diff --git a/content/browser/renderer_host/media/service_video_capture_provider.h b/content/browser/renderer_host/media/service_video_capture_provider.h index 49effdf..ecc3a23c 100644 --- a/content/browser/renderer_host/media/service_video_capture_provider.h +++ b/content/browser/renderer_host/media/service_video_capture_provider.h
@@ -32,8 +32,15 @@ std::unique_ptr<VideoCaptureDeviceLauncher> CreateDeviceLauncher() override; private: + enum class ReasonForUninitialize { + kShutdown, + kClientRequest, + kConnectionLost + }; + void LazyConnectToService(); void OnLostConnectionToDeviceFactory(); + void UninitializeInternal(ReasonForUninitialize reason); std::unique_ptr<service_manager::Connector> connector_; // We must hold on to |device_factory_provider_| because it holds the @@ -41,6 +48,9 @@ video_capture::mojom::DeviceFactoryProviderPtr device_factory_provider_; video_capture::mojom::DeviceFactoryPtr device_factory_; base::SequenceChecker sequence_checker_; + + base::TimeTicks time_of_last_connect_; + base::TimeTicks time_of_last_uninitialize_; }; } // namespace content
diff --git a/content/browser/renderer_host/media/video_capture_controller.cc b/content/browser/renderer_host/media/video_capture_controller.cc index 0f00727b..3dcb7a4b 100644 --- a/content/browser/renderer_host/media/video_capture_controller.cc +++ b/content/browser/renderer_host/media/video_capture_controller.cc
@@ -447,6 +447,8 @@ } } UMA_HISTOGRAM_COUNTS("Media.VideoCapture.FrameRate", frame_rate); + UMA_HISTOGRAM_TIMES("Media.VideoCapture.DelayUntilFirstFrame", + base::TimeTicks::Now() - time_of_start_request_); OnLog("First frame received at VideoCaptureController"); has_received_frames_ = true; } @@ -530,6 +532,7 @@ VideoCaptureDeviceLaunchObserver* observer, base::OnceClosure done_cb) { DCHECK_CURRENTLY_ON(BrowserThread::IO); + time_of_start_request_ = base::TimeTicks::Now(); device_launch_observer_ = observer; device_launcher_->LaunchDeviceAsync( device_id_, stream_type_, params, GetWeakPtrForIOThread(),
diff --git a/content/browser/renderer_host/media/video_capture_controller.h b/content/browser/renderer_host/media/video_capture_controller.h index 1ab04ceb..6f7cd6a 100644 --- a/content/browser/renderer_host/media/video_capture_controller.h +++ b/content/browser/renderer_host/media/video_capture_controller.h
@@ -241,6 +241,7 @@ // True if the controller has received a video frame from the device. bool has_received_frames_; + base::TimeTicks time_of_start_request_; base::Optional<media::VideoCaptureFormat> video_capture_format_;
diff --git a/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc b/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc index c94fe4c..697000895 100644 --- a/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc +++ b/content/browser/renderer_host/media/video_capture_gpu_jpeg_decoder.cc
@@ -15,10 +15,11 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "build/build_config.h" -#include "content/browser/gpu/browser_gpu_channel_host_factory.h" +#include "content/browser/browser_main_loop.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" +#include "gpu/ipc/client/gpu_channel_host.h" #include "media/base/media_switches.h" #include "media/base/video_frame.h" #include "media/gpu/ipc/client/gpu_jpeg_decode_accelerator_host.h" @@ -250,11 +251,12 @@ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, base::WeakPtr<VideoCaptureGpuJpegDecoder> weak_this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(BrowserGpuChannelHostFactory::instance()); - BrowserGpuChannelHostFactory::instance()->EstablishGpuChannel( - base::Bind(&VideoCaptureGpuJpegDecoder::GpuChannelEstablishedOnUIThread, - task_runner, weak_this)); + BrowserMainLoop::GetInstance() + ->gpu_channel_establish_factory() + ->EstablishGpuChannel(base::Bind( + &VideoCaptureGpuJpegDecoder::GpuChannelEstablishedOnUIThread, + task_runner, weak_this)); } // static @@ -279,7 +281,7 @@ } else if (gpu_channel_host->gpu_info().jpeg_decode_accelerator_supported) { gpu_channel_host_ = std::move(gpu_channel_host); scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = - BrowserGpuChannelHostFactory::instance()->GetIOThreadTaskRunner(); + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO); int32_t route_id = gpu_channel_host_->GenerateRouteID(); std::unique_ptr<media::GpuJpegDecodeAcceleratorHost> decoder(
diff --git a/content/browser/renderer_host/overscroll_controller.cc b/content/browser/renderer_host/overscroll_controller.cc index c5e978d4..d72d729 100644 --- a/content/browser/renderer_host/overscroll_controller.cc +++ b/content/browser/renderer_host/overscroll_controller.cc
@@ -4,6 +4,8 @@ #include "content/browser/renderer_host/overscroll_controller.h" +#include <algorithm> + #include "base/command_line.h" #include "base/logging.h" #include "content/browser/renderer_host/overscroll_controller_delegate.h" @@ -13,6 +15,8 @@ using blink::WebInputEvent; +namespace content { + namespace { bool IsScrollEndEffectEnabled() { @@ -27,9 +31,12 @@ return gesture.source_device == blink::kWebGestureDeviceTouchpad; } -} // namespace +float ClampAbsoluteValue(float value, float max_abs) { + DCHECK_LT(0.f, max_abs); + return std::max(-max_abs, std::min(value, max_abs)); +} -namespace content { +} // namespace OverscrollController::OverscrollController() {} @@ -348,17 +355,37 @@ overscroll_delta_x_ += delta_x; overscroll_delta_y_ += delta_y; - float horiz_threshold = GetOverscrollConfig( + const float horiz_threshold = GetOverscrollConfig( is_touchpad ? OVERSCROLL_CONFIG_HORIZ_THRESHOLD_START_TOUCHPAD : OVERSCROLL_CONFIG_HORIZ_THRESHOLD_START_TOUCHSCREEN); - float vert_threshold = GetOverscrollConfig( - OVERSCROLL_CONFIG_VERT_THRESHOLD_START); + const float vert_threshold = + GetOverscrollConfig(OVERSCROLL_CONFIG_VERT_THRESHOLD_START); if (fabs(overscroll_delta_x_) <= horiz_threshold && fabs(overscroll_delta_y_) <= vert_threshold) { SetOverscrollMode(OVERSCROLL_NONE, OverscrollSource::NONE); return true; } + if (delegate_) { + base::Optional<float> cap = delegate_->GetMaxOverscrollDelta(); + if (cap) { + switch (overscroll_mode_) { + case OVERSCROLL_WEST: + case OVERSCROLL_EAST: + overscroll_delta_x_ = ClampAbsoluteValue( + overscroll_delta_x_, cap.value() + horiz_threshold); + break; + case OVERSCROLL_NORTH: + case OVERSCROLL_SOUTH: + overscroll_delta_y_ = ClampAbsoluteValue( + overscroll_delta_y_, cap.value() + vert_threshold); + break; + case OVERSCROLL_NONE: + break; + } + } + } + // Compute the current overscroll direction. If the direction is different // from the current direction, then always switch to no-overscroll mode first // to make sure that subsequent scroll events go through to the page first.
diff --git a/content/browser/renderer_host/overscroll_controller_delegate.h b/content/browser/renderer_host/overscroll_controller_delegate.h index e2f8a8f..74c3ff4 100644 --- a/content/browser/renderer_host/overscroll_controller_delegate.h +++ b/content/browser/renderer_host/overscroll_controller_delegate.h
@@ -7,6 +7,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/optional.h" #include "content/browser/renderer_host/overscroll_controller.h" #include "content/common/content_export.h" #include "ui/gfx/geometry/size.h" @@ -14,7 +15,8 @@ namespace content { // The delegate receives overscroll gesture updates from the controller and -// should perform appropriate actions. +// should perform appropriate actions. The delegate can optionally cap the +// overscroll deltas maintained and reported by the controller. class CONTENT_EXPORT OverscrollControllerDelegate { public: OverscrollControllerDelegate() {} @@ -34,14 +36,18 @@ // This is called when the overscroll completes. virtual void OnOverscrollComplete(OverscrollMode overscroll_mode) = 0; - // This is called when the direction of the overscroll changes. - // When a new overscroll is started (i.e. when |new_mode| is not - // equal to OVERSCROLL_NONE), |source| will be set to the device that - // triggered the overscroll gesture. + // This is called when the direction of the overscroll changes. When a new + // overscroll is started (i.e. when |new_mode| is not equal to + // OVERSCROLL_NONE), |source| will be set to the device that triggered the + // overscroll gesture. virtual void OnOverscrollModeChange(OverscrollMode old_mode, OverscrollMode new_mode, OverscrollSource source) = 0; + // Returns the optional maximum amount allowed for the absolute value of + // overscroll delta corresponding to the current overscroll mode. + virtual base::Optional<float> GetMaxOverscrollDelta() const = 0; + private: DISALLOW_COPY_AND_ASSIGN(OverscrollControllerDelegate); };
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index e799662..d14f4113 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -139,7 +139,6 @@ #include "content/common/content_switches_internal.h" #include "content/common/frame_messages.h" #include "content/common/in_process_child_thread_params.h" -#include "content/common/network_service.mojom.h" #include "content/common/render_process_messages.h" #include "content/common/resource_messages.h" #include "content/common/service_manager/child_connection.h" @@ -164,6 +163,7 @@ #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/mojo_channel_switches.h" +#include "content/public/common/network_service.mojom.h" #include "content/public/common/process_type.h" #include "content/public/common/resource_type.h" #include "content/public/common/result_codes.h"
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 96e664d..94a0d1f7 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -35,9 +35,9 @@ #include "content/common/renderer.mojom.h" #include "content/common/renderer_host.mojom.h" #include "content/common/storage_partition_service.mojom.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/service_manager_connection.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_platform_file.h" #include "media/media_features.h"
diff --git a/content/browser/renderer_host/render_widget_host_delegate.h b/content/browser/renderer_host/render_widget_host_delegate.h index 86bcb17..8b98a64a 100644 --- a/content/browser/renderer_host/render_widget_host_delegate.h +++ b/content/browser/renderer_host/render_widget_host_delegate.h
@@ -10,10 +10,10 @@ #include <vector> #include "build/build_config.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/common/content_export.h" #include "content/common/drag_event_source_info.h" #include "content/public/common/drop_data.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/WebKit/public/platform/WebDisplayMode.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" #include "third_party/WebKit/public/platform/WebInputEvent.h"
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 364819d1..2c426e7 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -557,8 +557,7 @@ void RenderWidgetHostViewAura::Hide() { window_->Hide(); - // TODO(wjmaclean): can host_ ever be null? - if (host_ && !host_->is_hidden()) { + if (!host_->is_hidden()) { host_->WasHidden(); if (delegated_frame_host_) delegated_frame_host_->WasHidden(); @@ -769,7 +768,7 @@ ui::OnScreenKeyboardDisplayManager* osk_display_manager = ui::OnScreenKeyboardDisplayManager::GetInstance(); DCHECK(osk_display_manager); - if (editable && host_ && host_->GetView() && host_->delegate()) { + if (editable && host_->GetView() && host_->delegate()) { keyboard_observer_.reset(new WinScreenKeyboardObserver( host_, location_dips_screen, device_scale_factor_, window_)); virtual_keyboard_requested_ = @@ -1229,9 +1228,8 @@ } // Ignore character messages for VKEY_RETURN sent on CTRL+M. crbug.com/315547 - // TODO(wjmaclean): can host_ ever be null? - if (host_ && (event_handler_->accept_return_character() || - event.GetCharacter() != ui::VKEY_RETURN)) { + if (event_handler_->accept_return_character() || + event.GetCharacter() != ui::VKEY_RETURN) { // Send a blink::WebInputEvent::Char event to |host_|. ForwardKeyboardEventWithLatencyInfo( NativeWebKeyboardEvent(event, event.GetCharacter()), *event.latency(), @@ -1404,10 +1402,6 @@ } void RenderWidgetHostViewAura::OnInputMethodChanged() { - // TODO(wjmaclean): can host_ ever be null? - if (!host_) - return; - // TODO(suzhe): implement the newly added “locale” property of HTML DOM // TextEvent. }
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index 8f29608d..72315fe 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -146,6 +146,8 @@ ~TestOverscrollDelegate() override {} + void set_delta_cap(float delta_cap) { delta_cap_ = delta_cap; } + OverscrollMode current_mode() const { return current_mode_; } OverscrollMode completed_mode() const { return completed_mode_; } float delta_x() const { return delta_x_; } @@ -189,7 +191,12 @@ delta_x_ = delta_y_ = 0.f; } + base::Optional<float> GetMaxOverscrollDelta() const override { + return delta_cap_; + } + RenderWidgetHostView* view_; + base::Optional<float> delta_cap_; OverscrollMode current_mode_; OverscrollMode completed_mode_; float delta_x_; @@ -1008,17 +1015,15 @@ } void SimulateWheelEventPossiblyIncludingPhase( - bool ignore_phase, float dX, float dY, int modifiers, bool precise, WebMouseWheelEvent::Phase phase) { - if (ignore_phase) { - SimulateWheelEvent(dX, dY, modifiers, precise); - } else { + if (wheel_scroll_latching_enabled_) SimulateWheelEventWithPhase(dX, dY, modifiers, precise, phase); - } + else + SimulateWheelEvent(dX, dY, modifiers, precise); } void SimulateWheelEventWithLatencyInfo(float dX, @@ -3845,11 +3850,9 @@ // Simulate wheel events. SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -5, 0, 0, false, - WebMouseWheelEvent::kPhaseBegan); // sent directly + -5, 0, 0, false, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -60, 1, 0, false, - WebMouseWheelEvent::kPhaseChanged); // enqueued + -60, 1, 0, false, WebMouseWheelEvent::kPhaseChanged); // enqueued EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); EXPECT_EQ(OverscrollSource::NONE, overscroll_source()); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); @@ -3914,22 +3917,20 @@ // Simulate wheel events. SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -5, 0, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + -5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -1, 1, 0, true, - WebMouseWheelEvent::kPhaseChanged); // enqueued + -1, 1, 0, true, WebMouseWheelEvent::kPhaseChanged); // enqueued SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -10, -3, 0, true, + -10, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -15, -1, 0, true, + -15, -1, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -30, -3, 0, true, + -30, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -20, 6, 1, true, + -20, 6, 1, true, WebMouseWheelEvent::kPhaseChanged); // enqueued, different modifiers EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); EXPECT_EQ(OverscrollSource::NONE, overscroll_source()); @@ -4013,22 +4014,20 @@ // Simulate wheel events. SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -5, 0, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + -5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -1, -1, 0, true, - WebMouseWheelEvent::kPhaseChanged); // enqueued + -1, -1, 0, true, WebMouseWheelEvent::kPhaseChanged); // enqueued SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -10, -3, 0, true, + -10, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -15, -1, 0, true, + -15, -1, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -30, -3, 0, true, + -30, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -20, 6, 1, true, + -20, 6, 1, true, WebMouseWheelEvent::kPhaseChanged); // enqueued, different modifiers EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); @@ -4110,8 +4109,7 @@ // Send a wheel event. ACK the event as not processed. This should not // initiate an overscroll gesture since it doesn't cross the threshold yet. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 10, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(10, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); SendInputEventACK(WebInputEvent::kMouseWheel, @@ -4128,8 +4126,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Scroll some more so as to not overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 10, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(10, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4149,8 +4146,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Scroll some more to initiate an overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 40, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(40, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4173,8 +4169,7 @@ EXPECT_EQ(0.f, overscroll_delegate()->delta_y()); // Scroll in the reverse direction enough to abort the overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, -20, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(-20, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); SendInputEventACK(WebInputEvent::kMouseWheel, @@ -4190,8 +4185,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Continue to scroll in the reverse direction. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, -20, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(-20, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { @@ -4213,8 +4207,7 @@ // Continue to scroll in the reverse direction enough to initiate overscroll // in that direction. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, -55, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(-55, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4264,8 +4257,7 @@ // Send a wheel event. ACK the event as not processed. This should not // initiate an overscroll gesture since it doesn't cross the threshold yet. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 10, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(10, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); SendInputEventACK(WebInputEvent::kMouseWheel, @@ -4282,8 +4274,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Scroll some more so as to not overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 20, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(20, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4301,8 +4292,7 @@ sink_->ClearMessages(); // Scroll some more to initiate an overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 30, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(30, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4359,8 +4349,7 @@ // Send a wheel event. ACK the event as not processed. This should not // initiate an overscroll gesture since it doesn't cross the threshold yet. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 10, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(10, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); SendInputEventACK(WebInputEvent::kMouseWheel, @@ -4377,8 +4366,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Scroll some more so as to not overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 20, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(20, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4398,8 +4386,7 @@ EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); // Scroll some more to initiate an overscroll. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 30, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(30, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4552,6 +4539,66 @@ EXPECT_EQ(1U, sink_->message_count()); } +// Tests that when a cap is set for overscroll delta, extra overscroll delta is +// ignored. +TEST_F(RenderWidgetHostViewAuraOverscrollTest, OverscrollDeltaCap) { + SetUpOverscrollEnvironment(); + + // Set overscroll cap and start scrolling. + overscroll_delegate()->set_delta_cap(50); + SimulateGestureEvent(WebInputEvent::kGestureScrollBegin, + blink::kWebGestureDeviceTouchscreen); + SendScrollBeginAckIfNeeded(INPUT_EVENT_ACK_STATE_CONSUMED); + EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); + EXPECT_EQ(OverscrollSource::NONE, overscroll_source()); + EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); + EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); + + // Scroll enough to initiate the overscrolling. + SimulateGestureScrollUpdateEvent(55, -5, 0); + SendInputEventACK(WebInputEvent::kGestureScrollUpdate, + INPUT_EVENT_ACK_STATE_NOT_CONSUMED); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode()); + EXPECT_EQ(OverscrollSource::TOUCHSCREEN, overscroll_source()); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode()); + EXPECT_EQ(55.f, overscroll_delta_x()); + EXPECT_EQ(-5.f, overscroll_delta_y()); + EXPECT_EQ(5.f, overscroll_delegate()->delta_x()); + EXPECT_EQ(-5.f, overscroll_delegate()->delta_y()); + EXPECT_EQ(2U, GetSentMessageCountAndResetSink()); + + // Scroll beyond overscroll cap. Overscroll delta should not surpass the cap. + SimulateGestureScrollUpdateEvent(75, -5, 0); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode()); + EXPECT_EQ(OverscrollSource::TOUCHSCREEN, overscroll_source()); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode()); + EXPECT_EQ(100.f, overscroll_delta_x()); + EXPECT_EQ(-10.f, overscroll_delta_y()); + EXPECT_EQ(50.f, overscroll_delegate()->delta_x()); + EXPECT_EQ(-10.f, overscroll_delegate()->delta_y()); + EXPECT_EQ(0U, sink_->message_count()); + + // Scroll back a bit. Since the extra scroll after cap in previous step is + // ignored, scrolling back should immediately reduce overscroll delta. + SimulateGestureScrollUpdateEvent(-10, -5, 0); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_mode()); + EXPECT_EQ(OverscrollSource::TOUCHSCREEN, overscroll_source()); + EXPECT_EQ(OVERSCROLL_EAST, overscroll_delegate()->current_mode()); + EXPECT_EQ(90.f, overscroll_delta_x()); + EXPECT_EQ(-15.f, overscroll_delta_y()); + EXPECT_EQ(40.f, overscroll_delegate()->delta_x()); + EXPECT_EQ(-15.f, overscroll_delegate()->delta_y()); + EXPECT_EQ(0U, sink_->message_count()); + + // End overscrolling. + SimulateGestureEvent(WebInputEvent::kGestureScrollEnd, + blink::kWebGestureDeviceTouchscreen); + EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); + EXPECT_EQ(OverscrollSource::NONE, overscroll_source()); + EXPECT_EQ(OVERSCROLL_NONE, overscroll_delegate()->current_mode()); + EXPECT_EQ(1U, sink_->message_count()); +} + // Tests that if the page is scrolled because of a scroll-gesture, then that // particular scroll sequence never generates overscroll if the scroll direction // is horizontal. @@ -4939,8 +4986,7 @@ SetUpOverscrollEnvironment(); // Send wheel event and receive ack as not consumed. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 125, - -5, 0, true, + SimulateWheelEventPossiblyIncludingPhase(125, -5, 0, true, WebMouseWheelEvent::kPhaseBegan); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); SendInputEventACK(WebInputEvent::kMouseWheel, @@ -4960,8 +5006,7 @@ // controller will not consume the event, because it is not triggering // gesture-nav. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, - -260, 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(-260, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ == kAsyncWheelEvents) { ExpectGestureScrollUpdateAfterNonBlockingMouseWheelACK(false); @@ -4984,8 +5029,7 @@ EXPECT_EQ(OverscrollSource::TOUCHPAD, overscroll_source()); EXPECT_EQ(OVERSCROLL_WEST, overscroll_delegate()->current_mode()); - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, -20, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(-20, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); EXPECT_EQ(1U, GetSentMessageCountAndResetSink()); if (wheel_scrolling_mode_ != kAsyncWheelEvents) { @@ -5023,19 +5067,17 @@ SetUpOverscrollEnvironment(); SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, 5, 0, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + 5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -1, 0, 0, true, - WebMouseWheelEvent::kPhaseChanged); // enqueued + -1, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); // enqueued SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -10, -3, 0, true, + -10, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -15, -1, 0, true, + -15, -1, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -30, -3, 0, true, + -30, -3, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); @@ -5151,16 +5193,14 @@ SetUpOverscrollEnvironment(); SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, 0, 5, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + 0, 5, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, 0, 30, 0, true, - WebMouseWheelEvent::kPhaseChanged); // enqueued + 0, 30, 0, true, WebMouseWheelEvent::kPhaseChanged); // enqueued SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, 0, 40, 0, true, + 0, 40, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, 0, 10, 0, true, + 0, 10, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event EXPECT_EQ(OVERSCROLL_NONE, overscroll_mode()); EXPECT_EQ(OverscrollSource::NONE, overscroll_source()); @@ -5227,13 +5267,11 @@ EXPECT_EQ(2U, GetSentMessageCountAndResetSink()); SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -5, 0, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + -5, 0, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -60, 0, 0, true, - WebMouseWheelEvent::kPhaseChanged); // enqueued + -60, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); // enqueued SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -100, 0, 0, true, + -100, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); // coalesced into previous event EXPECT_TRUE(ScrollStateIsUnknown()); @@ -5561,8 +5599,7 @@ SetUpOverscrollEnvironment(); // Wheel event scroll ending with mouse move. SimulateWheelEventPossiblyIncludingPhase( - !wheel_scroll_latching_enabled_, -30, -10, 0, true, - WebMouseWheelEvent::kPhaseBegan); // sent directly + -30, -10, 0, true, WebMouseWheelEvent::kPhaseBegan); // sent directly SendInputEventACK(WebInputEvent::kMouseWheel, INPUT_EVENT_ACK_STATE_NOT_CONSUMED); SendScrollBeginAckIfNeeded(INPUT_EVENT_ACK_STATE_CONSUMED); @@ -5593,8 +5630,7 @@ EXPECT_EQ(0.f, overscroll_delta_y()); // Wheel event scroll ending with a fling. - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 5, - 0, 0, true, + SimulateWheelEventPossiblyIncludingPhase(5, 0, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ != kAsyncWheelEvents) { SendInputEventACK(WebInputEvent::kMouseWheel, @@ -5602,8 +5638,7 @@ } SendInputEventACK(WebInputEvent::kGestureScrollUpdate, INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - SimulateWheelEventPossiblyIncludingPhase(!wheel_scroll_latching_enabled_, 10, - -5, 0, true, + SimulateWheelEventPossiblyIncludingPhase(10, -5, 0, true, WebMouseWheelEvent::kPhaseChanged); if (wheel_scrolling_mode_ != kAsyncWheelEvents) { SendInputEventACK(WebInputEvent::kMouseWheel,
diff --git a/content/browser/service_manager/service_manager_context.cc b/content/browser/service_manager/service_manager_context.cc index b0056bb..91b296e 100644 --- a/content/browser/service_manager/service_manager_context.cc +++ b/content/browser/service_manager/service_manager_context.cc
@@ -35,6 +35,7 @@ #include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" #include "media/mojo/features.h" +#include "media/mojo/interfaces/constants.mojom.h" #include "mojo/edk/embedder/embedder.h" #include "mojo/edk/embedder/incoming_broker_client_invitation.h" #include "services/catalog/manifest_provider.h" @@ -371,9 +372,8 @@ // TODO(xhwang): This is only used for test/experiment for now so it's okay // to run it in an unsandboxed utility process. Fix CDM loading so that we can // run it in the sandboxed utility process. See http://crbug.com/510604 - // TODO(xhwang): Replace the service name "media" with a constant string. - unsandboxed_services.insert( - std::make_pair("media", base::ASCIIToUTF16("Media Service"))); + unsandboxed_services.insert(std::make_pair( + media::mojom::kMediaServiceName, base::ASCIIToUTF16("Media Service"))); #endif for (const auto& service : unsandboxed_services) { @@ -384,7 +384,8 @@ #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) packaged_services_connection_->AddServiceRequestHandler( - "media", base::Bind(&StartServiceInGpuProcess, "media")); + media::mojom::kMediaServiceName, + base::Bind(&StartServiceInGpuProcess, media::mojom::kMediaServiceName)); #endif packaged_services_connection_->AddServiceRequestHandler(
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc index 73a21d70..f0a400e 100644 --- a/content/browser/service_worker/embedded_worker_instance.cc +++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -21,7 +21,6 @@ #include "content/common/service_worker/embedded_worker_settings.h" #include "content/common/service_worker/embedded_worker_start_params.h" #include "content/common/service_worker/service_worker_types.h" -#include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_process_host.h" @@ -109,10 +108,8 @@ // This could be called on the UI thread if |client_| still be valid when the // message loop on the UI thread gets destructed. // TODO(shimazu): Remove this after https://crbug.com/604762 is fixed - if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - DCHECK(ServiceWorkerUtils::IsMojoForServiceWorkerEnabled()); + if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) return; - } instance->Detach(); }
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index 17cb6c4..8709cf2a 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -22,6 +22,8 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" #include "base/test/scoped_feature_list.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" @@ -2657,7 +2659,7 @@ blob_data_handle_ = std::move(blob_data_handle); blob_reader_ = blob_data_handle_->CreateReader( file_system_context_, - BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE).get()); + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}).get()); const storage::BlobReader::Status status = blob_reader_->CalculateSize( base::Bind(&self::OnBlobReaderCalculateSizeCallback, this, result, continuation));
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.h b/content/browser/service_worker/service_worker_fetch_dispatcher.h index 47bc334..fa2a126 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.h +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.h
@@ -18,9 +18,9 @@ #include "content/common/service_worker/service_worker_event_dispatcher.mojom.h" #include "content/common/service_worker/service_worker_status_code.h" #include "content/common/service_worker/service_worker_types.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/log/net_log_with_source.h"
diff --git a/content/browser/service_worker/service_worker_url_loader_job.h b/content/browser/service_worker/service_worker_url_loader_job.h index df84f4e2..86037a2 100644 --- a/content/browser/service_worker/service_worker_url_loader_job.h +++ b/content/browser/service_worker/service_worker_url_loader_job.h
@@ -13,7 +13,7 @@ #include "content/browser/service_worker/service_worker_url_job_wrapper.h" #include "content/common/service_worker/service_worker_status_code.h" #include "content/common/service_worker/service_worker_types.h" -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/public/cpp/system/data_pipe.h" #include "third_party/WebKit/public/platform/modules/serviceworker/service_worker_stream_handle.mojom.h"
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index d71e30b..24a2536 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -5692,10 +5692,16 @@ SendMouseWheel(pos); - // This time only the wheel handler fires, since it prevent defaults on - // even numbered scrolls. + // If async_wheel_events is disabled, this time only the wheel handler + // fires, since even numbered scrolls are prevent-defaulted. If it is + // enabled, then this wheel event will be sent non-blockingly and won't be + // cancellable. EXPECT_TRUE(msg_queue.WaitForMessage(&reply)); EXPECT_EQ("\"wheel: 2\"", reply); + if (base::FeatureList::IsEnabled(features::kAsyncWheelEvents)) { + EXPECT_TRUE(msg_queue.WaitForMessage(&reply)); + EXPECT_EQ("\"scroll: 2\"", reply); + } SendMouseWheel(pos); @@ -5908,14 +5914,9 @@ } // namespace anonymous -// Flaky under TSan. https://crbug.com/592320 -#if defined(THREAD_SANITIZER) -#define MAYBE_SubframeGestureEventRouting DISABLED_SubframeGestureEventRouting -#else -#define MAYBE_SubframeGestureEventRouting SubframeGestureEventRouting -#endif +// https://crbug.com/592320 IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, - MAYBE_SubframeGestureEventRouting) { + DISABLED_SubframeGestureEventRouting) { GURL main_url(embedded_test_server()->GetURL( "/frame_tree/page_with_positioned_nested_frames.html")); EXPECT_TRUE(NavigateToURL(shell(), main_url));
diff --git a/content/browser/storage_partition_impl.h b/content/browser/storage_partition_impl.h index 9a50b97..c5798a2 100644 --- a/content/browser/storage_partition_impl.h +++ b/content/browser/storage_partition_impl.h
@@ -30,9 +30,9 @@ #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/url_loader_factory_getter.h" #include "content/common/content_export.h" -#include "content/common/network_service.mojom.h" #include "content/common/storage_partition_service.mojom.h" #include "content/public/browser/storage_partition.h" +#include "content/public/common/network_service.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "net/cookies/cookie_store.h" #include "storage/browser/quota/special_storage_policy.h"
diff --git a/content/browser/url_loader_factory_getter.cc b/content/browser/url_loader_factory_getter.cc index d5013516..67cd6bac 100644 --- a/content/browser/url_loader_factory_getter.cc +++ b/content/browser/url_loader_factory_getter.cc
@@ -6,7 +6,7 @@ #include "base/bind.h" #include "content/browser/storage_partition_impl.h" -#include "content/common/network_service.mojom.h" +#include "content/public/common/network_service.mojom.h" namespace content {
diff --git a/content/browser/url_loader_factory_getter.h b/content/browser/url_loader_factory_getter.h index 1ea7281..12864590 100644 --- a/content/browser/url_loader_factory_getter.h +++ b/content/browser/url_loader_factory_getter.h
@@ -8,8 +8,8 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/browser_thread.h" +#include "content/public/common/url_loader_factory.mojom.h" namespace content {
diff --git a/content/browser/utility_process_host_impl.cc b/content/browser/utility_process_host_impl.cc index 7aa297db..f6c4e30 100644 --- a/content/browser/utility_process_host_impl.cc +++ b/content/browser/utility_process_host_impl.cc
@@ -11,17 +11,9 @@ #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/files/file_path.h" -#include "base/lazy_instance.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" -#include "base/message_loop/message_loop.h" -#include "base/process/process_handle.h" -#include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/strings/utf_string_conversions.h" -#include "base/synchronization/lock.h" -#include "base/synchronization/waitable_event.h" -#include "build/build_config.h" #include "components/network_session_configurator/common/network_switches.h" #include "content/browser/browser_child_process_host_impl.h" #include "content/browser/renderer_host/render_process_host_impl.h" @@ -29,19 +21,16 @@ #include "content/common/child_process_host_impl.h" #include "content/common/in_process_child_thread_params.h" #include "content/common/service_manager/child_connection.h" -#include "content/common/utility_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/utility_process_host_client.h" #include "content/public/common/content_switches.h" -#include "content/public/common/mojo_channel_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/sandbox_type.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" #include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" #include "media/base/media_switches.h" -#include "mojo/edk/embedder/embedder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "ui/base/ui_base_switches.h" @@ -146,7 +135,6 @@ const scoped_refptr<base::SequencedTaskRunner>& client_task_runner) : client_(client), client_task_runner_(client_task_runner), - is_batch_mode_(false), no_sandbox_(false), run_elevated_(false), #if defined(OS_LINUX) @@ -163,8 +151,6 @@ UtilityProcessHostImpl::~UtilityProcessHostImpl() { DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (is_batch_mode_) - EndBatchMode(); } base::WeakPtr<UtilityProcessHost> UtilityProcessHostImpl::AsWeakPtr() { @@ -178,19 +164,6 @@ return process_->Send(message); } -bool UtilityProcessHostImpl::StartBatchMode() { - CHECK(!is_batch_mode_); - is_batch_mode_ = StartProcess(); - Send(new UtilityMsg_BatchMode_Started()); - return is_batch_mode_; -} - -void UtilityProcessHostImpl::EndBatchMode() { - CHECK(is_batch_mode_); - is_batch_mode_ = false; - Send(new UtilityMsg_BatchMode_Finished()); -} - void UtilityProcessHostImpl::SetExposedDir(const base::FilePath& dir) { exposed_dir_ = dir; } @@ -211,12 +184,10 @@ } #if defined(OS_POSIX) - void UtilityProcessHostImpl::SetEnv(const base::EnvironmentMap& env) { env_ = env; } - -#endif // OS_POSIX +#endif bool UtilityProcessHostImpl::Start() { return StartProcess(); @@ -236,11 +207,8 @@ bool UtilityProcessHostImpl::StartProcess() { if (started_) return true; + started_ = true; - - if (is_batch_mode_) - return true; - process_->SetName(name_); process_->GetHost()->CreateChannelMojo();
diff --git a/content/browser/utility_process_host_impl.h b/content/browser/utility_process_host_impl.h index 76dc35507..517fb3c 100644 --- a/content/browser/utility_process_host_impl.h +++ b/content/browser/utility_process_host_impl.h
@@ -7,10 +7,7 @@ #include <memory> #include <string> -#include <vector> -#include "base/compiler_specific.h" -#include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" @@ -19,6 +16,7 @@ #include "content/public/browser/utility_process_host.h" namespace base { +class FilePath; class SequencedTaskRunner; class Thread; } @@ -42,11 +40,9 @@ const scoped_refptr<base::SequencedTaskRunner>& client_task_runner); ~UtilityProcessHostImpl() override; - // UtilityProcessHost implementation: + // UtilityProcessHost: base::WeakPtr<UtilityProcessHost> AsWeakPtr() override; bool Send(IPC::Message* message) override; - bool StartBatchMode() override; - void EndBatchMode() override; void SetExposedDir(const base::FilePath& dir) override; void DisableSandbox() override; #if defined(OS_WIN) @@ -64,8 +60,7 @@ void set_child_flags(int flags) { child_flags_ = flags; } private: - // Starts a process if necessary. Returns true if it succeeded or a process - // has already been started via StartBatchMode(). + // Starts the child process if needed, returns true on success. bool StartProcess(); // BrowserChildProcessHost: @@ -81,35 +76,37 @@ base::WeakPtr<UtilityProcessHostImpl> host, int error_code); - // A pointer to our client interface, who will be informed of progress. + // Pointer to our client interface used for progress notifications. scoped_refptr<UtilityProcessHostClient> client_; - scoped_refptr<base::SequencedTaskRunner> client_task_runner_; - // True when running in batch mode, i.e., StartBatchMode() has been called - // and the utility process will run until EndBatchMode(). - bool is_batch_mode_; + // Task runner used for posting progess notifications to |client_|. + scoped_refptr<base::SequencedTaskRunner> client_task_runner_; + + // Directory opened through the child process sandbox if needed. base::FilePath exposed_dir_; - // Whether to pass switches::kNoSandbox to the child. + // Whether to launch the child process with switches::kNoSandbox. bool no_sandbox_; - // Whether to launch the process with elevated privileges. + // Whether to launch the child process with elevated privileges. bool run_elevated_; - // Flags defined in ChildProcessHost with which to start the process. + // ChildProcessHost flags to use when starting the child process. int child_flags_; + // Map of environment variables to values. base::EnvironmentMap env_; + // True if StartProcess() has been called. bool started_; - // A user-visible name identifying this process. Used to indentify this - // process in the task manager. + // The process name used to identify the process in task manager. base::string16 name_; + // Child process host implementation. std::unique_ptr<BrowserChildProcessHostImpl> process_; - // Used in single-process mode instead of process_. + // Used in single-process mode instead of |process_|. std::unique_ptr<base::Thread> in_process_thread_; // Used to vend weak pointers, and should always be declared last.
diff --git a/content/browser/web_contents/aura/gesture_nav_simple.cc b/content/browser/web_contents/aura/gesture_nav_simple.cc index 4c1e1bd4..4375307 100644 --- a/content/browser/web_contents/aura/gesture_nav_simple.cc +++ b/content/browser/web_contents/aura/gesture_nav_simple.cc
@@ -426,4 +426,10 @@ parent->StackAtTop(affordance_->root_layer()); } +base::Optional<float> GestureNavSimple::GetMaxOverscrollDelta() const { + if (affordance_) + return completion_threshold_; + return base::nullopt; +} + } // namespace content
diff --git a/content/browser/web_contents/aura/gesture_nav_simple.h b/content/browser/web_contents/aura/gesture_nav_simple.h index 0cb9f80..70b474f 100644 --- a/content/browser/web_contents/aura/gesture_nav_simple.h +++ b/content/browser/web_contents/aura/gesture_nav_simple.h
@@ -38,6 +38,7 @@ void OnOverscrollModeChange(OverscrollMode old_mode, OverscrollMode new_mode, OverscrollSource source) override; + base::Optional<float> GetMaxOverscrollDelta() const override; WebContentsImpl* web_contents_; std::unique_ptr<Affordance> affordance_;
diff --git a/content/browser/web_contents/aura/overscroll_window_animation.cc b/content/browser/web_contents/aura/overscroll_window_animation.cc index 6aaef30..8ed86377 100644 --- a/content/browser/web_contents/aura/overscroll_window_animation.cc +++ b/content/browser/web_contents/aura/overscroll_window_animation.cc
@@ -137,6 +137,10 @@ shadow_.reset(new ShadowLayerDelegate(GetFrontLayer())); } +base::Optional<float> OverscrollWindowAnimation::GetMaxOverscrollDelta() const { + return base::nullopt; +} + void OverscrollWindowAnimation::OnOverscrollComplete( OverscrollMode overscroll_mode) { if (!is_active())
diff --git a/content/browser/web_contents/aura/overscroll_window_animation.h b/content/browser/web_contents/aura/overscroll_window_animation.h index f11c7db..1f72bb89 100644 --- a/content/browser/web_contents/aura/overscroll_window_animation.h +++ b/content/browser/web_contents/aura/overscroll_window_animation.h
@@ -91,6 +91,7 @@ void OnOverscrollModeChange(OverscrollMode old_mode, OverscrollMode new_mode, OverscrollSource source) override; + base::Optional<float> GetMaxOverscrollDelta() const override; private: // Cancels the slide, animating the front and back window to their original
diff --git a/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc b/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc index 4dafb29..b94a12e 100644 --- a/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc +++ b/content/browser/web_contents/aura/overscroll_window_delegate_unittest.cc
@@ -108,6 +108,10 @@ overscroll_started_ = true; } + base::Optional<float> GetMaxOverscrollDelta() const override { + return base::nullopt; + } + // Window in which the overscroll window delegate is installed. std::unique_ptr<aura::Window> window_;
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 3d1ed20..3be78992 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -35,7 +35,6 @@ #include "build/build_config.h" #include "components/mime_util/mime_util.h" #include "components/rappor/public/rappor_utils.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/url_formatter/url_formatter.h" #include "content/browser/accessibility/browser_accessibility_state_impl.h" #include "content/browser/bad_message.h" @@ -131,6 +130,7 @@ #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #include "ppapi/features/features.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/WebKit/public/platform/WebSecurityStyle.h" #include "third_party/WebKit/public/web/WebSandboxFlags.h"
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index a2315c3..12b4c25 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -20,7 +20,6 @@ #include "base/process/process.h" #include "base/values.h" #include "build/build_config.h" -#include "components/ukm/public/ukm_recorder.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/navigation_controller_delegate.h" @@ -49,6 +48,7 @@ #include "net/base/load_states.h" #include "net/http/http_response_headers.h" #include "ppapi/features/features.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/WebKit/public/platform/WebDragOperation.h" #include "ui/base/page_transition_types.h" #include "ui/gfx/geometry/rect_f.h"
diff --git a/content/browser/web_contents/web_contents_view_aura.cc b/content/browser/web_contents/web_contents_view_aura.cc index c1f01fe0..00bd67b 100644 --- a/content/browser/web_contents/web_contents_view_aura.cc +++ b/content/browser/web_contents/web_contents_view_aura.cc
@@ -1081,6 +1081,10 @@ completed_overscroll_gesture_ = OVERSCROLL_NONE; } +base::Optional<float> WebContentsViewAura::GetMaxOverscrollDelta() const { + return navigation_overlay_->relay_delegate()->GetMaxOverscrollDelta(); +} + //////////////////////////////////////////////////////////////////////////////// // WebContentsViewAura, aura::WindowDelegate implementation:
diff --git a/content/browser/web_contents/web_contents_view_aura.h b/content/browser/web_contents/web_contents_view_aura.h index 8c27edc..e00556e 100644 --- a/content/browser/web_contents/web_contents_view_aura.h +++ b/content/browser/web_contents/web_contents_view_aura.h
@@ -160,6 +160,7 @@ void OnOverscrollModeChange(OverscrollMode old_mode, OverscrollMode new_mode, OverscrollSource source) override; + base::Optional<float> GetMaxOverscrollDelta() const override; // Overridden from aura::WindowDelegate: gfx::Size GetMinimumSize() const override;
diff --git a/content/browser/webrtc/webrtc_getusermedia_browsertest.cc b/content/browser/webrtc/webrtc_getusermedia_browsertest.cc index 3550c0c2..8f8acbf 100644 --- a/content/browser/webrtc/webrtc_getusermedia_browsertest.cc +++ b/content/browser/webrtc/webrtc_getusermedia_browsertest.cc
@@ -800,6 +800,29 @@ MediaStreamManager::GenerateStreamTestCallback()); } +IN_PROC_BROWSER_TEST_F(WebRtcGetUserMediaBrowserTest, GetAudioSettingsDefault) { + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url(embedded_test_server()->GetURL("/media/getusermedia.html")); + NavigateToURL(shell(), url); + ExecuteJavascriptAndWaitForOk("getAudioSettingsDefault()"); +} + +IN_PROC_BROWSER_TEST_F(WebRtcGetUserMediaBrowserTest, + GetAudioSettingsNoEchoCancellation) { + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url(embedded_test_server()->GetURL("/media/getusermedia.html")); + NavigateToURL(shell(), url); + ExecuteJavascriptAndWaitForOk("getAudioSettingsNoEchoCancellation()"); +} + +IN_PROC_BROWSER_TEST_F(WebRtcGetUserMediaBrowserTest, + GetAudioSettingsDeviceId) { + ASSERT_TRUE(embedded_test_server()->Start()); + GURL url(embedded_test_server()->GetURL("/media/getusermedia.html")); + NavigateToURL(shell(), url); + ExecuteJavascriptAndWaitForOk("getAudioSettingsDeviceId()"); +} + // TODO(guidou): Remove this test. http://crbug.com/706408 class WebRtcGetUserMediaOldConstraintsBrowserTest : public WebRtcContentBrowserTestBase {
diff --git a/content/browser/webui/network_error_url_loader.h b/content/browser/webui/network_error_url_loader.h index 076a6682..b4e1532 100644 --- a/content/browser/webui/network_error_url_loader.h +++ b/content/browser/webui/network_error_url_loader.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_BROWSER_WEBUI_NETWORK_ERROR_URL_LOADER_H_ #define CONTENT_BROWSER_WEBUI_NETWORK_ERROR_URL_LOADER_H_ -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" namespace content {
diff --git a/content/browser/webui/web_ui_url_loader_factory.cc b/content/browser/webui/web_ui_url_loader_factory.cc index 3e5ad0a..99bc1b30 100644 --- a/content/browser/webui/web_ui_url_loader_factory.cc +++ b/content/browser/webui/web_ui_url_loader_factory.cc
@@ -22,11 +22,11 @@ #include "content/browser/webui/network_error_url_loader.h" #include "content/browser/webui/url_data_manager_backend.h" #include "content/browser/webui/url_data_source_impl.h" -#include "content/common/network_service.mojom.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/network_service.mojom.h" #include "content/public/common/url_constants.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "third_party/zlib/google/compression_utils.h"
diff --git a/content/browser/webui/web_ui_url_loader_factory.h b/content/browser/webui/web_ui_url_loader_factory.h index b52d653..733e8e3 100644 --- a/content/browser/webui/web_ui_url_loader_factory.h +++ b/content/browser/webui/web_ui_url_loader_factory.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_H_ #define CONTENT_BROWSER_WEBUI_WEB_UI_URL_LOADER_FACTORY_H_ -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" namespace content { class FrameTreeNode;
diff --git a/content/child/blink_platform_impl.cc b/content/child/blink_platform_impl.cc index 305d39bb..7c54ab0 100644 --- a/content/child/blink_platform_impl.cc +++ b/content/child/blink_platform_impl.cc
@@ -577,6 +577,10 @@ {"colorSuggestionPicker.css", IDR_COLOR_SUGGESTION_PICKER_CSS, ui::SCALE_FACTOR_NONE, true}, #endif + {"input_alert.svg", IDR_VALIDATION_BUBBLE_ICON, ui::SCALE_FACTOR_NONE, + true}, + {"validation_bubble.css", IDR_VALIDATION_BUBBLE_CSS, ui::SCALE_FACTOR_NONE, + true}, {"placeholderIcon", IDR_PLACEHOLDER_ICON, ui::SCALE_FACTOR_100P, false}, };
diff --git a/content/child/resource_dispatcher.cc b/content/child/resource_dispatcher.cc index 790f652..4d724c1 100644 --- a/content/child/resource_dispatcher.cc +++ b/content/child/resource_dispatcher.cc
@@ -31,12 +31,12 @@ #include "content/common/inter_process_time_ticks_converter.h" #include "content/common/navigation_params.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/common/throttling_url_loader.h" #include "content/public/child/fixed_received_data.h" #include "content/public/child/request_peer.h" #include "content/public/child/resource_dispatcher_delegate.h" #include "content/public/common/resource_request.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "content/public/common/resource_type.h" #include "net/base/net_errors.h"
diff --git a/content/child/resource_dispatcher.h b/content/child/resource_dispatcher.h index 091bf39..fc7aa465 100644 --- a/content/child/resource_dispatcher.h +++ b/content/child/resource_dispatcher.h
@@ -22,8 +22,8 @@ #include "base/single_thread_task_runner.h" #include "base/time/time.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" #include "content/public/common/resource_type.h" +#include "content/public/common/url_loader.mojom.h" #include "content/public/common/url_loader_throttle.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sender.h"
diff --git a/content/child/resource_dispatcher_unittest.cc b/content/child/resource_dispatcher_unittest.cc index f7a8c9e..e42b0e15 100644 --- a/content/child/resource_dispatcher_unittest.cc +++ b/content/child/resource_dispatcher_unittest.cc
@@ -24,7 +24,6 @@ #include "content/child/test_request_peer.h" #include "content/common/appcache_interfaces.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/child/fixed_received_data.h" #include "content/public/child/request_peer.h" #include "content/public/child/resource_dispatcher_delegate.h" @@ -32,6 +31,7 @@ #include "content/public/common/request_context_frame_type.h" #include "content/public/common/resource_request.h" #include "content/public/common/resource_request_body.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "content/public/common/service_worker_modes.h" #include "net/base/net_errors.h"
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index 42c9901..bfff5707 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -334,6 +334,9 @@ WebRuntimeFeatures::EnableServiceWorkerNavigationPreload( base::FeatureList::IsEnabled(features::kServiceWorkerNavigationPreload)); + WebRuntimeFeatures::EnableServiceWorkerScriptStreaming( + base::FeatureList::IsEnabled(features::kServiceWorkerScriptStreaming)); + WebRuntimeFeatures::EnableOffMainThreadFetch( base::FeatureList::IsEnabled(features::kOffMainThreadFetch));
diff --git a/content/child/url_loader_client_impl.h b/content/child/url_loader_client_impl.h index 872c678..16af56c 100644 --- a/content/child/url_loader_client_impl.h +++ b/content/child/url_loader_client_impl.h
@@ -11,7 +11,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" #include "ipc/ipc_message.h" #include "mojo/public/cpp/system/data_pipe.h"
diff --git a/content/child/url_loader_client_impl_unittest.cc b/content/child/url_loader_client_impl_unittest.cc index 3ae14d5..f290cdb 100644 --- a/content/child/url_loader_client_impl_unittest.cc +++ b/content/child/url_loader_client_impl_unittest.cc
@@ -10,7 +10,7 @@ #include "base/run_loop.h" #include "content/child/resource_dispatcher.h" #include "content/child/test_request_peer.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "ipc/ipc_sender.h" #include "mojo/public/cpp/bindings/associated_interface_ptr_info.h" #include "mojo/public/cpp/bindings/binding.h"
diff --git a/content/child/url_response_body_consumer.cc b/content/child/url_response_body_consumer.cc index bce3d4e4..2766bf7 100644 --- a/content/child/url_response_body_consumer.cc +++ b/content/child/url_response_body_consumer.cc
@@ -11,8 +11,8 @@ #include "content/child/resource_dispatcher.h" #include "content/child/site_isolation_stats_gatherer.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/child/request_peer.h" +#include "content/public/common/resource_request_completion_status.h" namespace content {
diff --git a/content/child/url_response_body_consumer.h b/content/child/url_response_body_consumer.h index efa55dc..ecbbf0db 100644 --- a/content/child/url_response_body_consumer.h +++ b/content/child/url_response_body_consumer.h
@@ -16,7 +16,7 @@ #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/simple_watcher.h"
diff --git a/content/child/url_response_body_consumer_unittest.cc b/content/child/url_response_body_consumer_unittest.cc index be98a8e..f29fb2d3 100644 --- a/content/child/url_response_body_consumer_unittest.cc +++ b/content/child/url_response_body_consumer_unittest.cc
@@ -14,10 +14,10 @@ #include "content/child/request_extra_data.h" #include "content/child/resource_dispatcher.h" #include "content/common/resource_messages.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/child/request_peer.h" #include "content/public/common/request_context_frame_type.h" #include "content/public/common/resource_request.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/service_worker_modes.h" #include "net/base/request_priority.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/content/child/web_url_loader_impl.cc b/content/child/web_url_loader_impl.cc index 0c6e896..0da42fd 100644 --- a/content/child/web_url_loader_impl.cc +++ b/content/child/web_url_loader_impl.cc
@@ -36,7 +36,6 @@ #include "content/child/weburlresponse_extradata_impl.h" #include "content/common/resource_messages.h" #include "content/common/service_worker/service_worker_types.h" -#include "content/common/url_loader.mojom.h" #include "content/public/child/fixed_received_data.h" #include "content/public/child/request_peer.h" #include "content/public/common/browser_side_navigation_policy.h" @@ -44,6 +43,7 @@ #include "content/public/common/resource_request.h" #include "content/public/common/resource_request_body.h" #include "content/public/common/service_worker_modes.h" +#include "content/public/common/url_loader.mojom.h" #include "net/base/data_url.h" #include "net/base/filename_util.h" #include "net/base/net_errors.h"
diff --git a/content/child/web_url_loader_impl.h b/content/child/web_url_loader_impl.h index 4fc8700..3678fa8 100644 --- a/content/child/web_url_loader_impl.h +++ b/content/child/web_url_loader_impl.h
@@ -9,8 +9,8 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "content/common/content_export.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/common/resource_response.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/url_request/redirect_info.h" #include "third_party/WebKit/public/platform/WebURLLoader.h"
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index e9efee7..f871bb4 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -20,7 +20,10 @@ buildflag_header("features") { header = "features.h" - flags = [ "USE_EXTERNAL_POPUP_MENU=$use_external_popup_menu" ] + flags = [ + "USE_EXTERNAL_POPUP_MENU=$use_external_popup_menu", + "ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND=$allow_critical_memory_pressure_handling_in_foreground", + ] } source_set("common") { @@ -229,7 +232,6 @@ "media/video_capture.h", "message_port.cc", "message_port.h", - "mutable_network_traffic_annotation_tag_struct_traits.h", "navigation_gesture.h", "navigation_params.cc", "navigation_params.h", @@ -278,8 +280,6 @@ "resize_params.h", "resource_messages.cc", "resource_messages.h", - "resource_request_completion_status.cc", - "resource_request_completion_status.h", "sandbox_init_mac.cc", "sandbox_init_mac.h", "sandbox_init_win.cc", @@ -346,7 +346,6 @@ "url_schemes.cc", "url_schemes.h", "user_agent.cc", - "utility_messages.h", "view_message_enums.h", "view_messages.h", "worker_messages.h", @@ -379,6 +378,7 @@ "//components/tracing:startup_tracing", "//content:resources", "//content/app/resources", + "//content/public/common:interfaces", "//content/public/common:service_names", "//device/base/synchronization", "//device/bluetooth", @@ -445,7 +445,10 @@ libs = [] ldflags = [] - allow_circular_includes_from = [ ":mojo_bindings" ] + allow_circular_includes_from = [ + ":mojo_bindings", + "//content/public/common:interfaces", + ] if (is_android && use_seccomp_bpf) { set_sources_assignment_filter([]) @@ -608,9 +611,7 @@ "media/media_devices.mojom", "media/renderer_audio_output_stream_factory.mojom", "memory_coordinator.mojom", - "mutable_network_traffic_annotation_tag.mojom", "native_types.mojom", - "network_service.mojom", "push_messaging.mojom", "render_frame_message_filter.mojom", "render_message_filter.mojom", @@ -624,8 +625,6 @@ "service_worker/service_worker_provider_interfaces.mojom", "service_worker/service_worker_types.mojom", "storage_partition_service.mojom", - "url_loader.mojom", - "url_loader_factory.mojom", "video_capture.mojom", "worker_url_loader_factory_provider.mojom", ]
diff --git a/content/common/content_message_generator.h b/content/common/content_message_generator.h index 2e2108ec..a86a6ac 100644 --- a/content/common/content_message_generator.h +++ b/content/common/content_message_generator.h
@@ -38,7 +38,6 @@ #include "content/common/service_worker/service_worker_messages.h" #include "content/common/speech_recognition_messages.h" #include "content/common/text_input_client_messages.h" -#include "content/common/utility_messages.h" #include "content/common/view_messages.h" #include "content/common/worker_messages.h" #include "media/media_features.h"
diff --git a/content/common/features.gni b/content/common/features.gni index c43056a..b1bcb83 100644 --- a/content/common/features.gni +++ b/content/common/features.gni
@@ -2,7 +2,13 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromecast_build.gni") + declare_args() { # Whether or not to use external popup menu. use_external_popup_menu = is_android || is_mac + + # Whether to perform critical memory pressure handling when in foreground (if + # false, critical memory pressure is treated like moderate pressure in foreground). + allow_critical_memory_pressure_handling_in_foreground = is_chromecast }
diff --git a/content/common/renderer_host.mojom b/content/common/renderer_host.mojom index b2a271a..8269deae 100644 --- a/content/common/renderer_host.mojom +++ b/content/common/renderer_host.mojom
@@ -4,7 +4,7 @@ module content.mojom; -import "content/common/url_loader_factory.mojom"; +import "content/public/common/url_loader_factory.mojom"; // The primordial interface implemented by a render process host. This should be // used for implementing renderer-to-browser messages.
diff --git a/content/common/resource_messages.h b/content/common/resource_messages.h index 31a5453b..0fe7c8438 100644 --- a/content/common/resource_messages.h +++ b/content/common/resource_messages.h
@@ -14,10 +14,10 @@ #include "base/process/process.h" #include "content/common/content_param_traits_macros.h" #include "content/common/navigation_params.h" -#include "content/common/resource_request_completion_status.h" #include "content/public/common/common_param_traits.h" #include "content/public/common/resource_request.h" #include "content/public/common/resource_request_body.h" +#include "content/public/common/resource_request_completion_status.h" #include "content/public/common/resource_response.h" #include "content/public/common/service_worker_modes.h" #include "ipc/ipc_message_macros.h"
diff --git a/content/common/service_worker/service_worker_event_dispatcher.mojom b/content/common/service_worker/service_worker_event_dispatcher.mojom index 93832a5..34a174c 100644 --- a/content/common/service_worker/service_worker_event_dispatcher.mojom +++ b/content/common/service_worker/service_worker_event_dispatcher.mojom
@@ -4,7 +4,7 @@ module content.mojom; -import "content/common/url_loader.mojom"; +import "content/public/common/url_loader.mojom"; import "mojo/common/string16.mojom"; import "mojo/common/time.mojom"; import "third_party/WebKit/public/platform/modules/background_sync/background_sync.mojom";
diff --git a/content/common/service_worker/service_worker_utils.cc b/content/common/service_worker/service_worker_utils.cc index 0c87998..9ad5aaf 100644 --- a/content/common/service_worker/service_worker_utils.cc +++ b/content/common/service_worker/service_worker_utils.cc
@@ -7,6 +7,7 @@ #include <string> #include "base/command_line.h" +#include "base/feature_list.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "content/public/common/browser_side_navigation_policy.h" @@ -142,8 +143,8 @@ } // static -bool ServiceWorkerUtils::IsMojoForServiceWorkerEnabled() { - return true; +bool ServiceWorkerUtils::IsScriptStreamingEnabled() { + return base::FeatureList::IsEnabled(features::kServiceWorkerScriptStreaming); } bool LongestScopeMatcher::MatchLongest(const GURL& scope) {
diff --git a/content/common/service_worker/service_worker_utils.h b/content/common/service_worker/service_worker_utils.h index 9e665423..3ffbd62 100644 --- a/content/common/service_worker/service_worker_utils.h +++ b/content/common/service_worker/service_worker_utils.h
@@ -43,7 +43,7 @@ const GURL& script_url, std::string* error_message); - static bool IsMojoForServiceWorkerEnabled(); + static bool IsScriptStreamingEnabled(); // Returns true if all members of |urls| have the same origin, and // OriginCanAccessServiceWorkers is true for this origin.
diff --git a/content/common/throttling_url_loader.h b/content/common/throttling_url_loader.h index e9f85dc..bb15aefe 100644 --- a/content/common/throttling_url_loader.h +++ b/content/common/throttling_url_loader.h
@@ -12,8 +12,8 @@ #include "base/threading/thread_task_runner_handle.h" #include "content/common/content_export.h" #include "content/common/possibly_associated_interface_ptr.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/common/url_loader_throttle.h" #include "mojo/public/cpp/bindings/binding.h"
diff --git a/content/common/throttling_url_loader_unittest.cc b/content/common/throttling_url_loader_unittest.cc index 3068e9ae..ac3a1fc 100644 --- a/content/common/throttling_url_loader_unittest.cc +++ b/content/common/throttling_url_loader_unittest.cc
@@ -7,8 +7,8 @@ #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" -#include "content/common/url_loader.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/common/url_loader_throttle.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/content/common/typemaps.gni b/content/common/typemaps.gni index 95068be3..b65fe78 100644 --- a/content/common/typemaps.gni +++ b/content/common/typemaps.gni
@@ -6,19 +6,12 @@ "//content/common/background_fetch/background_fetch_types.typemap", "//content/common/native_types.typemap", "//content/common/media/media_devices.typemap", - "//content/common/mutable_network_traffic_annotation_tag.typemap", "//content/common/push_messaging.typemap", "//content/common/service_worker/embedded_worker.typemap", "//content/common/service_worker/service_worker_event_dispatcher.typemap", "//content/common/service_worker/service_worker_fetch_request.typemap", "//content/common/service_worker/service_worker_provider.typemap", "//content/common/service_worker/service_worker_types.typemap", - "//content/common/ssl_info.typemap", - "//content/common/url_loader_status.typemap", - "//content/common/url_request.typemap", - "//content/common/url_request_redirect_info.typemap", - "//content/common/url_response_head.typemap", - "//content/common/url_sync_load_result.typemap", "//content/common/web_preferences.typemap", "//content/common/media/media_session.typemap", ]
diff --git a/content/common/url_request_struct_traits.h b/content/common/url_request_struct_traits.h index 3aecba8..0326632 100644 --- a/content/common/url_request_struct_traits.h +++ b/content/common/url_request_struct_traits.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_COMMON_URL_REQUEST_STRUCT_TRAITS_H_ #define CONTENT_COMMON_URL_REQUEST_STRUCT_TRAITS_H_ -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/enum_traits.h" #include "net/base/request_priority.h"
diff --git a/content/common/utility_messages.h b/content/common/utility_messages.h deleted file mode 100644 index 6a43e5a..0000000 --- a/content/common/utility_messages.h +++ /dev/null
@@ -1,22 +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. - -// Multiply-included message file, so no include guard. - -#include "content/common/content_export.h" -#include "ipc/ipc_message_macros.h" - -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT CONTENT_EXPORT -#define IPC_MESSAGE_START UtilityMsgStart - -//------------------------------------------------------------------------------ -// Utility process messages: -// These are messages from the browser to the utility process. - -// Tells the utility process that it's running in batch mode. -IPC_MESSAGE_CONTROL0(UtilityMsg_BatchMode_Started) - -// Tells the utility process that it can shutdown. -IPC_MESSAGE_CONTROL0(UtilityMsg_BatchMode_Finished)
diff --git a/content/common/worker_url_loader_factory_provider.mojom b/content/common/worker_url_loader_factory_provider.mojom index 6590e4f..71a4956 100644 --- a/content/common/worker_url_loader_factory_provider.mojom +++ b/content/common/worker_url_loader_factory_provider.mojom
@@ -4,7 +4,7 @@ module content.mojom; -import "url_loader_factory.mojom"; +import "content/public/common/url_loader_factory.mojom"; // A renderer-side interface that is returned by CreateWorkerFetchContext for // the browser to notify the renderer process when there's a controller change.
diff --git a/content/network/DEPS b/content/network/DEPS index 935a07d..ac2ce4d 100644 --- a/content/network/DEPS +++ b/content/network/DEPS
@@ -4,16 +4,16 @@ "-content", "+content/common/content_export.h", "+content/common/net_adapters.h", - "+content/common/network_service.mojom.h", - "+content/common/url_loader.mojom.h", - "+content/common/url_loader_factory.mojom.h", "+content/network", "+content/public/common/content_client.h", "+content/public/common/content_switches.h", + "+content/public/common/network_service.mojom.h", "+content/public/common/referrer.h", "+content/public/common/resource_request.h", "+content/public/common/resource_response.h", "+content/public/common/url_constants.h", + "+content/public/common/url_loader.mojom.h", + "+content/public/common/url_loader_factory.mojom.h", "+services/service_manager/public", ]
diff --git a/content/network/cache_url_loader.h b/content/network/cache_url_loader.h index a4e1521..28d9d4b 100644 --- a/content/network/cache_url_loader.h +++ b/content/network/cache_url_loader.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_NETWORK_CACHE_URL_LOADER_H_ #define CONTENT_NETWORK_CACHE_URL_LOADER_H_ -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" namespace net { class URLRequestContext;
diff --git a/content/network/network_context.h b/content/network/network_context.h index b6b5332f..278923f 100644 --- a/content/network/network_context.h +++ b/content/network/network_context.h
@@ -12,8 +12,8 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "content/common/network_service.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/network_service.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/strong_binding_set.h"
diff --git a/content/network/network_service.h b/content/network/network_service.h index c945b9ad..703ffc2 100644 --- a/content/network/network_service.h +++ b/content/network/network_service.h
@@ -9,7 +9,7 @@ #include "base/macros.h" #include "content/common/content_export.h" -#include "content/common/network_service.mojom.h" +#include "content/public/common/network_service.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h"
diff --git a/content/network/network_service_unittest.cc b/content/network/network_service_unittest.cc index 398808c6..29aa109 100644 --- a/content/network/network_service_unittest.cc +++ b/content/network/network_service_unittest.cc
@@ -7,9 +7,9 @@ #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" -#include "content/common/network_service.mojom.h" #include "content/network/network_context.h" #include "content/network/network_service.h" +#include "content/public/common/network_service.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace content {
diff --git a/content/network/network_service_url_loader_factory_impl.h b/content/network/network_service_url_loader_factory_impl.h index 1c22d25b..8518717 100644 --- a/content/network/network_service_url_loader_factory_impl.h +++ b/content/network/network_service_url_loader_factory_impl.h
@@ -6,7 +6,7 @@ #define CONTENT_NETWORK_NETWORK_SERVICE_URL_LOADER_FACTORY_IMPL_H_ #include "base/macros.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/traffic_annotation/network_traffic_annotation.h" namespace content {
diff --git a/content/network/url_loader_impl.cc b/content/network/url_loader_impl.cc index 6ecf2b73..5b86d6e 100644 --- a/content/network/url_loader_impl.cc +++ b/content/network/url_loader_impl.cc
@@ -8,10 +8,10 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "content/common/net_adapters.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/network/network_context.h" #include "content/public/common/referrer.h" #include "content/public/common/resource_response.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/base/elements_upload_data_stream.h" #include "net/base/load_flags.h" #include "net/base/upload_bytes_element_reader.h"
diff --git a/content/network/url_loader_impl.h b/content/network/url_loader_impl.h index b23f2f6d..df0211b 100644 --- a/content/network/url_loader_impl.h +++ b/content/network/url_loader_impl.h
@@ -11,7 +11,7 @@ #include "base/memory/weak_ptr.h" #include "content/common/content_export.h" -#include "content/common/url_loader.mojom.h" +#include "content/public/common/url_loader.mojom.h" #include "mojo/public/cpp/bindings/associated_binding.h" #include "mojo/public/cpp/system/simple_watcher.h" #include "net/traffic_annotation/network_traffic_annotation.h"
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index dd60b833..e9a3dfe 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -36,7 +36,6 @@ "//base:base_java", "//device/bluetooth:java", "//device/gamepad:java", - "//device/generic_sensor:java", "//device/power_save_blocker:java", "//device/sensors:java", "//device/usb:java",
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index ba02145..3997515 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -250,8 +250,6 @@ "storage_partition.h", "stored_payment_app.cc", "stored_payment_app.h", - "stored_payment_instrument.cc", - "stored_payment_instrument.h", "stream_handle.h", "stream_info.cc", "stream_info.h",
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index 529f49fa..516fde2 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc
@@ -390,6 +390,13 @@ return base::GenerateGUID(); } +bool ContentBrowserClient::BindAssociatedInterfaceRequestFromFrame( + RenderFrameHost* render_frame_host, + const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle* handle) { + return false; +} + ControllerPresentationServiceDelegate* ContentBrowserClient::GetControllerPresentationServiceDelegate( WebContents* web_contents) {
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index 571f993..122447d 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -67,6 +67,10 @@ class CdmFactory; } +namespace mojo { +class ScopedInterfaceEndpointHandle; +} + namespace service_manager { class Service; struct BindSourceInfo; @@ -656,6 +660,14 @@ const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) {} + // Content was unable to bind a request for this associated interface, so the + // embedder should try. Returns true if the |handle| was actually taken and + // bound; false otherwise. + virtual bool BindAssociatedInterfaceRequestFromFrame( + RenderFrameHost* render_frame_host, + const std::string& interface_name, + mojo::ScopedInterfaceEndpointHandle* handle); + // (Currently called only from GPUProcessHost, move somewhere more central). // Called when a request to bind |interface_name| on |interface_pipe| is // received from |source_info.identity|. If the request is bound,
diff --git a/content/public/browser/security_style_explanation.h b/content/public/browser/security_style_explanation.h index 18db638..e2d51b9f 100644 --- a/content/public/browser/security_style_explanation.h +++ b/content/public/browser/security_style_explanation.h
@@ -8,6 +8,7 @@ #include <string> #include "content/common/content_export.h" +#include "third_party/WebKit/public/platform/WebMixedContentContextType.h" namespace content { @@ -20,17 +21,33 @@ CONTENT_EXPORT SecurityStyleExplanation(){}; CONTENT_EXPORT SecurityStyleExplanation(const std::string& summary, const std::string& description) - : summary(summary), description(description), has_certificate(false) {} - CONTENT_EXPORT SecurityStyleExplanation(const std::string& summary, - const std::string& description, - bool has_certificate) - : summary(summary), description(description), - has_certificate(has_certificate) {} + : summary(summary), + description(description), + has_certificate(false), + mixed_content_type( + blink::WebMixedContentContextType::kNotMixedContent) {} + CONTENT_EXPORT SecurityStyleExplanation( + const std::string& summary, + const std::string& description, + bool has_certificate, + blink::WebMixedContentContextType mixed_content_type) + : summary(summary), + description(description), + has_certificate(has_certificate), + mixed_content_type(mixed_content_type) {} CONTENT_EXPORT ~SecurityStyleExplanation() {} std::string summary; std::string description; + // |has_certificate| indicates that this explanation has an associated + // certificate. UI surfaces can use this to add a button/link for viewing the + // certificate of the current page. bool has_certificate; + // |mixed_content_type| indicates that the explanation describes a particular + // type of mixed content. A value of kNotMixedContent means that the + // explanation does not relate to mixed content. UI surfaces can use this to + // customize the display of mixed content explanations. + blink::WebMixedContentContextType mixed_content_type; }; } // namespace content
diff --git a/content/public/browser/stored_payment_app.h b/content/public/browser/stored_payment_app.h index 4b298c0..e6951285 100644 --- a/content/public/browser/stored_payment_app.h +++ b/content/public/browser/stored_payment_app.h
@@ -10,7 +10,6 @@ #include <vector> #include "content/common/content_export.h" -#include "content/public/browser/stored_payment_instrument.h" #include "third_party/skia/include/core/SkBitmap.h" #include "url/origin.h" @@ -33,8 +32,8 @@ // Decoded icon for this payment app. std::unique_ptr<SkBitmap> icon; - // A list of one or more payment instruments in this payment app. - std::vector<std::unique_ptr<StoredPaymentInstrument>> instruments; + // A list of one or more enabled payment methods in this payment app. + std::vector<std::string> enabled_methods; }; } // namespace content
diff --git a/content/public/browser/stored_payment_instrument.cc b/content/public/browser/stored_payment_instrument.cc deleted file mode 100644 index 915e80f..0000000 --- a/content/public/browser/stored_payment_instrument.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/public/browser/stored_payment_instrument.h" - -namespace content { - -StoredPaymentInstrument::StoredPaymentInstrument() = default; - -StoredPaymentInstrument::~StoredPaymentInstrument() = default; - -} // namespace content
diff --git a/content/public/browser/stored_payment_instrument.h b/content/public/browser/stored_payment_instrument.h deleted file mode 100644 index 68600162..0000000 --- a/content/public/browser/stored_payment_instrument.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_PUBLIC_BROWSER_STORED_PAYMENT_INSTRUMENT_H_ -#define CONTENT_PUBLIC_BROWSER_STORED_PAYMENT_INSTRUMENT_H_ - -#include <stdint.h> -#include <string> -#include <vector> - -#include "content/common/content_export.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "url/gurl.h" - -namespace content { - -// This class represents the stored payment instrument in UA. -struct CONTENT_EXPORT StoredPaymentInstrument { - StoredPaymentInstrument(); - ~StoredPaymentInstrument(); - - // Id of this payment instrument. This key will be passed to the payment - // handler to indicate the instrument selected by the user. - std::string instrument_key; - - // Origin of the payment app provider that provides this payment instrument. - GURL origin; - - // Label for this payment instrument. - std::string name; - - // Decoded icon for this payment instrument. - std::unique_ptr<SkBitmap> icon; - - // A list of one or more payment method identifiers of the payment methods - // supported by this payment instrument. - std::vector<std::string> enabled_methods; -}; - -} // namespace content - -#endif // CONTENT_PUBLIC_BROWSER_STORED_PAYMENT_INSTRUMENT_H_
diff --git a/content/public/browser/utility_process_host.h b/content/public/browser/utility_process_host.h index 5a404dbe..fc1b97d 100644 --- a/content/public/browser/utility_process_host.h +++ b/content/public/browser/utility_process_host.h
@@ -52,13 +52,6 @@ virtual base::WeakPtr<UtilityProcessHost> AsWeakPtr() = 0; - // Starts utility process in batch mode. Caller must call EndBatchMode() - // to finish the utility process. - virtual bool StartBatchMode() = 0; - - // Ends the utility process. Must be called after StartBatchMode(). - virtual void EndBatchMode() = 0; - // Allows a directory to be opened through the sandbox, in case it's needed by // the operation. virtual void SetExposedDir(const base::FilePath& dir) = 0;
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn index 0e20d7f5..2ce68b81d 100644 --- a/content/public/common/BUILD.gn +++ b/content/public/common/BUILD.gn
@@ -170,6 +170,7 @@ "mhtml_generation_params.h", "mojo_channel_switches.cc", "mojo_channel_switches.h", + "mutable_network_traffic_annotation_tag_struct_traits.h", "notification_resources.cc", "notification_resources.h", "origin_trial_policy.cc", @@ -208,6 +209,8 @@ "resource_request.h", "resource_request_body.cc", "resource_request_body.h", + "resource_request_completion_status.cc", + "resource_request_completion_status.h", "resource_response.cc", "resource_response.h", "resource_response_info.cc", @@ -259,9 +262,9 @@ public_configs = [ "//v8:external_startup_data" ] public_deps = [ + ":interfaces", ":service_names", "//content/common", - "//content/public/common:interfaces", "//ipc", "//mojo/edk/system", "//mojo/public/cpp/bindings", @@ -304,6 +307,7 @@ # //content/common needs to include public headers. allow_circular_includes_from = [ + ":interfaces", "//content/common", "//content/common:mojo_bindings", ] @@ -341,10 +345,31 @@ } mojom("interfaces") { + # Must depend on //content/public/common/ instead, for component build. + visibility = [ + ":common_sources", + "//content/common/*", + ] + sources = [ + "mutable_network_traffic_annotation_tag.mojom", + "network_service.mojom", "network_service_test.mojom", + "url_loader.mojom", + "url_loader_factory.mojom", "window_container_type.mojom", ] + + public_deps = [ + "//mojo/common:common_custom_types", + "//url/mojo:url_mojom_gurl", + "//url/mojo:url_mojom_origin", + ] + + component_output_prefix = "content_public_common_mojo_bindings" + export_class_attribute = "CONTENT_EXPORT" + export_define = "CONTENT_IMPLEMENTATION=1" + export_header = "content/common/content_export.h" } mojom("service_names") {
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 1d752f1..49e3a66 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -249,6 +249,10 @@ const base::Feature kServiceWorkerNavigationPreload{ "ServiceWorkerNavigationPreload", base::FEATURE_ENABLED_BY_DEFAULT}; +// Streaming installed scripts on starting service workers. +const base::Feature kServiceWorkerScriptStreaming{ + "ServiceWorkerScriptStreaming", base::FEATURE_DISABLED_BY_DEFAULT}; + // http://tc39.github.io/ecmascript_sharedmem/shmem.html const base::Feature kSharedArrayBuffer{"SharedArrayBuffer", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 76d9d903..8f3eb65 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -67,6 +67,7 @@ kRequireSecureOriginsForPepperMediaRequests; CONTENT_EXPORT extern const base::Feature kScrollAnchoring; CONTENT_EXPORT extern const base::Feature kServiceWorkerNavigationPreload; +CONTENT_EXPORT extern const base::Feature kServiceWorkerScriptStreaming; CONTENT_EXPORT extern const base::Feature kSharedArrayBuffer; CONTENT_EXPORT extern const base::Feature kSkipCompositingSmallScrollers; CONTENT_EXPORT extern const base::Feature kSlimmingPaintInvalidation;
diff --git a/content/common/mutable_network_traffic_annotation_tag.mojom b/content/public/common/mutable_network_traffic_annotation_tag.mojom similarity index 100% rename from content/common/mutable_network_traffic_annotation_tag.mojom rename to content/public/common/mutable_network_traffic_annotation_tag.mojom
diff --git a/content/common/mutable_network_traffic_annotation_tag.typemap b/content/public/common/mutable_network_traffic_annotation_tag.typemap similarity index 63% rename from content/common/mutable_network_traffic_annotation_tag.typemap rename to content/public/common/mutable_network_traffic_annotation_tag.typemap index dd9917d..986566b1 100644 --- a/content/common/mutable_network_traffic_annotation_tag.typemap +++ b/content/public/common/mutable_network_traffic_annotation_tag.typemap
@@ -2,8 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/mutable_network_traffic_annotation_tag.mojom" -traits_headers = [ "//content/common/mutable_network_traffic_annotation_tag_struct_traits.h" ] +mojom = "//content/public/common/mutable_network_traffic_annotation_tag.mojom" +traits_headers = [ "//content/public/common/mutable_network_traffic_annotation_tag_struct_traits.h" ] deps = [ "//net:traffic_annotation", ]
diff --git a/content/common/mutable_network_traffic_annotation_tag_struct_traits.h b/content/public/common/mutable_network_traffic_annotation_tag_struct_traits.h similarity index 72% rename from content/common/mutable_network_traffic_annotation_tag_struct_traits.h rename to content/public/common/mutable_network_traffic_annotation_tag_struct_traits.h index 55f9207..d17df8b 100644 --- a/content/common/mutable_network_traffic_annotation_tag_struct_traits.h +++ b/content/public/common/mutable_network_traffic_annotation_tag_struct_traits.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_ -#define CONTENT_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_ +#ifndef CONTENT_PUBLIC_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_ +#define CONTENT_PUBLIC_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_ -#include "content/common/mutable_network_traffic_annotation_tag.mojom.h" +#include "content/public/common/mutable_network_traffic_annotation_tag.mojom.h" #include "mojo/common/common_custom_types_struct_traits.h" #include "net/traffic_annotation/network_traffic_annotation.h" @@ -28,4 +28,4 @@ } // namespace mojo -#endif // CONTENT_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_ +#endif // CONTENT_PUBLIC_COMMON_MUTABLE_NETWORK_TRAFFIC_ANNOTATION_PARAM_TRAITS_H_
diff --git a/content/common/network_service.mojom b/content/public/common/network_service.mojom similarity index 100% rename from content/common/network_service.mojom rename to content/public/common/network_service.mojom
diff --git a/content/common/resource_request_completion_status.cc b/content/public/common/resource_request_completion_status.cc similarity index 91% rename from content/common/resource_request_completion_status.cc rename to content/public/common/resource_request_completion_status.cc index 3720d24f..2056851 100644 --- a/content/common/resource_request_completion_status.cc +++ b/content/public/common/resource_request_completion_status.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/common/resource_request_completion_status.h" +#include "content/public/common/resource_request_completion_status.h" #include "net/base/net_errors.h"
diff --git a/content/common/resource_request_completion_status.h b/content/public/common/resource_request_completion_status.h similarity index 86% rename from content/common/resource_request_completion_status.h rename to content/public/common/resource_request_completion_status.h index 073704e2..2a50977 100644 --- a/content/common/resource_request_completion_status.h +++ b/content/public/common/resource_request_completion_status.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_ -#define CONTENT_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_ +#ifndef CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_ +#define CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_ #include <stdint.h> #include <string> @@ -46,4 +46,4 @@ } // namespace content -#endif // CONTENT_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_ +#endif // CONTENT_PUBLIC_COMMON_RESOURCE_REQUEST_COMPLETION_STATUS_H_
diff --git a/content/public/common/service_worker_modes.typemap b/content/public/common/service_worker_modes.typemap new file mode 100644 index 0000000..bf6d5651 --- /dev/null +++ b/content/public/common/service_worker_modes.typemap
@@ -0,0 +1,11 @@ +# 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. + +mojom = "//content/public/common/service_worker_modes.mojom" +public_headers = [ "//content/public/common/service_worker_modes.h" ] +type_mappings = [ + "blink.mojom.FetchCredentialsMode=::content::FetchCredentialsMode", + "blink.mojom.FetchRedirectMode=::content::FetchRedirectMode", + "blink.mojom.FetchRequestMode=::content::FetchRequestMode", +]
diff --git a/content/common/ssl_info.typemap b/content/public/common/ssl_info.typemap similarity index 87% rename from content/common/ssl_info.typemap rename to content/public/common/ssl_info.typemap index 6e4ee34..e598fc72 100644 --- a/content/common/ssl_info.typemap +++ b/content/public/common/ssl_info.typemap
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader.mojom" +mojom = "//content/public/common/url_loader.mojom" public_headers = [ "//net/ssl/ssl_info.h" ] traits_headers = [ "//content/common/resource_messages.h" ] deps = [
diff --git a/content/public/common/typemaps.gni b/content/public/common/typemaps.gni index 2f87ff66..a9cff966 100644 --- a/content/public/common/typemaps.gni +++ b/content/public/common/typemaps.gni
@@ -4,6 +4,13 @@ typemaps = [ "//content/public/common/manifest.typemap", + "//content/public/common/mutable_network_traffic_annotation_tag.typemap", "//content/public/common/referrer.typemap", "//content/public/common/resource_type.typemap", + "//content/public/common/ssl_info.typemap", + "//content/public/common/url_loader_status.typemap", + "//content/public/common/url_request.typemap", + "//content/public/common/url_request_redirect_info.typemap", + "//content/public/common/url_response_head.typemap", + "//content/public/common/url_sync_load_result.typemap", ]
diff --git a/content/common/url_loader.mojom b/content/public/common/url_loader.mojom similarity index 100% rename from content/common/url_loader.mojom rename to content/public/common/url_loader.mojom
diff --git a/content/common/url_loader_factory.mojom b/content/public/common/url_loader_factory.mojom similarity index 100% rename from content/common/url_loader_factory.mojom rename to content/public/common/url_loader_factory.mojom
diff --git a/content/common/url_loader_status.typemap b/content/public/common/url_loader_status.typemap similarity index 74% rename from content/common/url_loader_status.typemap rename to content/public/common/url_loader_status.typemap index 66e57b63..28c8bd7e 100644 --- a/content/common/url_loader_status.typemap +++ b/content/public/common/url_loader_status.typemap
@@ -2,8 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader.mojom" -public_headers = [ "//content/common/resource_request_completion_status.h" ] +mojom = "//content/public/common/url_loader.mojom" +public_headers = + [ "//content/public/common/resource_request_completion_status.h" ] traits_headers = [ "//content/common/resource_messages.h" ] deps = [ "//content:export",
diff --git a/content/common/url_request.typemap b/content/public/common/url_request.typemap similarity index 91% rename from content/common/url_request.typemap rename to content/public/common/url_request.typemap index 6a727e1..d910b2a 100644 --- a/content/common/url_request.typemap +++ b/content/public/common/url_request.typemap
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader.mojom" +mojom = "//content/public/common/url_loader.mojom" public_headers = [ "//content/public/common/resource_request.h" ] traits_headers = [ "//content/common/resource_messages.h",
diff --git a/content/common/url_request_redirect_info.typemap b/content/public/common/url_request_redirect_info.typemap similarity index 88% rename from content/common/url_request_redirect_info.typemap rename to content/public/common/url_request_redirect_info.typemap index fcec85b..cf98da5b 100644 --- a/content/common/url_request_redirect_info.typemap +++ b/content/public/common/url_request_redirect_info.typemap
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader.mojom" +mojom = "//content/public/common/url_loader.mojom" public_headers = [ "//net/url_request/redirect_info.h" ] traits_headers = [ "//content/common/resource_messages.h" ] deps = [
diff --git a/content/common/url_response_head.typemap b/content/public/common/url_response_head.typemap similarity index 89% rename from content/common/url_response_head.typemap rename to content/public/common/url_response_head.typemap index 2918562..e67bc9c4 100644 --- a/content/common/url_response_head.typemap +++ b/content/public/common/url_response_head.typemap
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader.mojom" +mojom = "//content/public/common/url_loader.mojom" public_headers = [ "//content/public/common/resource_response.h" ] traits_headers = [ "//content/common/resource_messages.h" ] deps = [
diff --git a/content/common/url_sync_load_result.typemap b/content/public/common/url_sync_load_result.typemap similarity index 85% rename from content/common/url_sync_load_result.typemap rename to content/public/common/url_sync_load_result.typemap index a8d96175..4fd35f5 100644 --- a/content/common/url_sync_load_result.typemap +++ b/content/public/common/url_sync_load_result.typemap
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -mojom = "//content/common/url_loader_factory.mojom" +mojom = "//content/public/common/url_loader_factory.mojom" public_headers = [ "//content/public/common/resource_response.h" ] traits_headers = [ "//content/common/resource_messages.h" ] type_mappings = [ "content.mojom.URLSyncLoadResult=content::SyncLoadResult" ]
diff --git a/content/public/test/layouttest_support.h b/content/public/test/layouttest_support.h index 0d8962b..ba60629 100644 --- a/content/public/test/layouttest_support.h +++ b/content/public/test/layouttest_support.h
@@ -33,7 +33,7 @@ } namespace gfx { -class ICCProfile; +class ColorSpace; } namespace test_runner { @@ -144,13 +144,13 @@ test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base, const blink::WebInputEvent& event); -// Get the ICC profile for a given name string. This is not in the ICCProfile +// Get the color space for a given name string. This is not in the ColorSpace // class to avoid bloating the shipping build. -gfx::ICCProfile GetTestingICCProfile(const std::string& name); +gfx::ColorSpace GetTestingColorSpace(const std::string& name); -// Set the device color profile associated with the profile |name|. -void SetDeviceColorProfile( - RenderView* render_view, const gfx::ICCProfile& icc_profile); +// Set the device color space. +void SetDeviceColorSpace(RenderView* render_view, + const gfx::ColorSpace& color_space); // Sets the scan duration to 0. void SetTestBluetoothScanDuration();
diff --git a/content/public/utility/utility_thread.h b/content/public/utility/utility_thread.h index c76efda..49aa8a6 100644 --- a/content/public/utility/utility_thread.h +++ b/content/public/utility/utility_thread.h
@@ -18,7 +18,7 @@ UtilityThread(); ~UtilityThread() override; - // Releases the process if we are not (or no longer) in batch mode. + // Releases the process. TODO(noel): rename this routine and update callers. virtual void ReleaseProcessIfNeeded() = 0; // Initializes blink if it hasn't already been initialized.
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index a5add9a..b42c495a 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -441,7 +441,6 @@ "//components/discardable_memory/client", "//components/metrics", "//components/metrics:single_sample_metrics", - "//components/ukm/public", "//components/url_formatter", "//components/variations", "//components/viz/client", @@ -486,6 +485,7 @@ "//sandbox", "//services/device/public/interfaces", "//services/device/public/interfaces:constants", + "//services/metrics/public/cpp:metrics_cpp", "//services/service_manager/public/cpp", "//services/service_manager/public/interfaces", "//services/ui/public/cpp/gpu",
diff --git a/content/renderer/DEPS b/content/renderer/DEPS index 54e6e7b..93126e8 100644 --- a/content/renderer/DEPS +++ b/content/renderer/DEPS
@@ -6,7 +6,6 @@ "+components/metrics:single_sample_metrics", "+components/payments", "+components/scheduler", - "+components/ukm/public", "+components/url_formatter", "+components/variations", "+components/viz/client",
diff --git a/content/renderer/media/media_stream_audio_track.cc b/content/renderer/media/media_stream_audio_track.cc index 15a42af7..3c167fb 100644 --- a/content/renderer/media/media_stream_audio_track.cc +++ b/content/renderer/media/media_stream_audio_track.cc
@@ -4,6 +4,8 @@ #include "content/renderer/media/media_stream_audio_track.h" +#include <vector> + #include "base/callback_helpers.h" #include "base/logging.h" #include "content/public/renderer/media_stream_audio_sink.h" @@ -141,10 +143,4 @@ } } -void MediaStreamAudioTrack::GetSettings( - blink::WebMediaStreamTrack::Settings& settings) { - // TODO(hta): Extract the real value. - settings.device_id = blink::WebString("audio device ID"); -} - } // namespace content
diff --git a/content/renderer/media/media_stream_audio_track.h b/content/renderer/media/media_stream_audio_track.h index c5e6cda..636e030a 100644 --- a/content/renderer/media/media_stream_audio_track.h +++ b/content/renderer/media/media_stream_audio_track.h
@@ -92,8 +92,6 @@ // delivered to the sinks instead of the content of |audio_bus|. void OnData(const media::AudioBus& audio_bus, base::TimeTicks reference_time); - void GetSettings(blink::WebMediaStreamTrack::Settings& settings) override; - private: // In debug builds, check that all methods that could cause object graph // or data flow changes are being called on the main thread.
diff --git a/content/renderer/media/media_stream_video_capturer_source.cc b/content/renderer/media/media_stream_video_capturer_source.cc index f4d0568..583eba3 100644 --- a/content/renderer/media/media_stream_video_capturer_source.cc +++ b/content/renderer/media/media_stream_video_capturer_source.cc
@@ -197,21 +197,7 @@ device_info().session_id, device_info().device.type, is_secure)); } -void MediaStreamVideoCapturerSource::GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) { - source_->GetCurrentSupportedFormats( - max_requested_width, - max_requested_height, - max_requested_frame_rate, - callback); -} - void MediaStreamVideoCapturerSource::StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) { is_capture_starting_ = true; source_->StartCapture( @@ -225,7 +211,7 @@ } base::Optional<media::VideoCaptureFormat> -MediaStreamVideoCapturerSource::GetCurrentFormatImpl() const { +MediaStreamVideoCapturerSource::GetCurrentFormat() const { return base::Optional<media::VideoCaptureFormat>( capture_params_.requested_format); }
diff --git a/content/renderer/media/media_stream_video_capturer_source.h b/content/renderer/media/media_stream_video_capturer_source.h index ee8abe2..f4fa6067 100644 --- a/content/renderer/media/media_stream_video_capturer_source.h +++ b/content/renderer/media/media_stream_video_capturer_source.h
@@ -48,18 +48,10 @@ void RequestRefreshFrame() override; void OnHasConsumers(bool has_consumers) override; void OnCapturingLinkSecured(bool is_secure) override; - void GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) override; void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) override; void StopSourceImpl() override; - base::Optional<media::VideoCaptureFormat> GetCurrentFormatImpl() - const override; + base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const override; // RenderFrameObserver implementation. void OnDestruct() final {}
diff --git a/content/renderer/media/media_stream_video_capturer_source_unittest.cc b/content/renderer/media/media_stream_video_capturer_source_unittest.cc index 11efe04..0735060 100644 --- a/content/renderer/media/media_stream_video_capturer_source_unittest.cc +++ b/content/renderer/media/media_stream_video_capturer_source_unittest.cc
@@ -33,35 +33,15 @@ class MockVideoCapturerSource : public media::VideoCapturerSource { public: - MockVideoCapturerSource() { - ON_CALL(*this, GetCurrentSupportedFormats(_, _, _, _)) - .WillByDefault(WithArgs<3>( - Invoke(this, &MockVideoCapturerSource::EnumerateDeviceFormats))); - } + MockVideoCapturerSource() {} MOCK_METHOD0(RequestRefreshFrame, void()); - MOCK_METHOD4(GetCurrentSupportedFormats, - void(int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback)); MOCK_METHOD0(GetPreferredFormats, media::VideoCaptureFormats()); MOCK_METHOD3(StartCapture, void(const media::VideoCaptureParams& params, const VideoCaptureDeliverFrameCB& new_frame_callback, const RunningCallback& running_callback)); MOCK_METHOD0(StopCapture, void()); - - void EnumerateDeviceFormats(const VideoCaptureDeviceFormatsCB& callback) { - media::VideoCaptureFormat kFormatSmall(gfx::Size(640, 480), 30.0, - media::PIXEL_FORMAT_I420); - media::VideoCaptureFormat kFormatLarge(gfx::Size(1920, 1080), 30.0, - media::PIXEL_FORMAT_I420); - media::VideoCaptureFormats formats; - formats.push_back(kFormatSmall); - formats.push_back(kFormatLarge); - callback.Run(formats); - } }; class FakeMediaStreamVideoSink : public MediaStreamVideoSink {
diff --git a/content/renderer/media/media_stream_video_renderer_sink_unittest.cc b/content/renderer/media/media_stream_video_renderer_sink_unittest.cc index 6ced490..b65d93b 100644 --- a/content/renderer/media/media_stream_video_renderer_sink_unittest.cc +++ b/content/renderer/media/media_stream_video_renderer_sink_unittest.cc
@@ -40,7 +40,7 @@ public: MediaStreamVideoRendererSinkTest() : child_process_(new ChildProcess()), - mock_source_(new MockMediaStreamVideoSource(false)) { + mock_source_(new MockMediaStreamVideoSource()) { blink_source_.Initialize(blink::WebString::FromASCII("dummy_source_id"), blink::WebMediaStreamSource::kTypeVideo, blink::WebString::FromASCII("dummy_source_name"),
diff --git a/content/renderer/media/media_stream_video_source.cc b/content/renderer/media/media_stream_video_source.cc index 54852968b..203d632 100644 --- a/content/renderer/media/media_stream_video_source.cc +++ b/content/renderer/media/media_stream_video_source.cc
@@ -61,9 +61,7 @@ switch (state_) { case NEW: { state_ = STARTING; - blink::WebMediaConstraints ignored_constraints; StartSourceImpl( - media::VideoCaptureFormat() /* ignored */, ignored_constraints, base::Bind(&VideoTrackAdapter::DeliverFrameOnIO, track_adapter_)); break; } @@ -132,11 +130,6 @@ base::Optional<media::VideoCaptureFormat> MediaStreamVideoSource::GetCurrentFormat() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return GetCurrentFormatImpl(); -} - -base::Optional<media::VideoCaptureFormat> -MediaStreamVideoSource::GetCurrentFormatImpl() const { return base::Optional<media::VideoCaptureFormat>(); }
diff --git a/content/renderer/media/media_stream_video_source.h b/content/renderer/media/media_stream_video_source.h index c5f03c63..9fdc291 100644 --- a/content/renderer/media/media_stream_video_source.h +++ b/content/renderer/media/media_stream_video_source.h
@@ -37,13 +37,6 @@ // MediaStreaVideoSources such as local video capture, video sources received // on a PeerConnection or a source created in NaCl. // All methods calls will be done from the main render thread. -// -// When the first track is added to the source by calling AddTrack, the -// MediaStreamVideoSource implementation calls GetCurrentSupportedFormats. -// The source implementation must call OnSupportedFormats. -// MediaStreamVideoSource then match the constraints provided in AddTrack with -// the formats and call StartSourceImpl. The source implementation must call -// OnStartDone when the underlying source has been started or failed to start. class CONTENT_EXPORT MediaStreamVideoSource : public MediaStreamSource { public: enum { @@ -85,7 +78,8 @@ // Returns the task runner where video frames will be delivered on. base::SingleThreadTaskRunner* io_task_runner() const; - base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const; + // Implementations must return the capture format if available. + virtual base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const; base::WeakPtr<MediaStreamVideoSource> GetWeakPtr() { return weak_factory_.GetWeakPtr(); @@ -100,35 +94,11 @@ // Sets muted state and notifies it to all registered tracks. virtual void SetMutedState(bool state); - // An implementation must fetch the formats that can currently be used by - // the source and call OnSupportedFormats when done. - // |max_requested_height| and |max_requested_width| is the max height and - // width set as a mandatory constraint if set when calling - // MediaStreamVideoSource::AddTrack. If max height and max width is not set - // |max_requested_height| and |max_requested_width| are 0. - // TODO(guidou): Remove when the standard constraints code stabilizes. - // http://crbug.com/706408 - virtual void GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) = 0; - - // TODO(guidou): Rename to GetCurrentFormat. http://crbug.com/706804 - virtual base::Optional<media::VideoCaptureFormat> GetCurrentFormatImpl() - const; - - // An implementation must start capturing frames using the requested - // |format|. The fulfilled |constraints| are provided as additional context, - // and may be used to modify the behavior of the source. When the source has - // started or the source failed to start OnStartDone must be called. An - // implementation must call |frame_callback| on the IO thread with the + // An implementation must start capturing frames after this method is called. + // When the source has started or failed to start OnStartDone must be called. + // An implementation must call |frame_callback| on the IO thread with the // captured frames. - // TODO(guidou): Remove |format| and |constraints| parameters. - // http://crbug.com/706408 virtual void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) = 0; void OnStartDone(MediaStreamRequestResult result);
diff --git a/content/renderer/media/media_stream_video_track.cc b/content/renderer/media/media_stream_video_track.cc index 6dce6ab..0924b5b 100644 --- a/content/renderer/media/media_stream_video_track.cc +++ b/content/renderer/media/media_stream_video_track.cc
@@ -4,6 +4,7 @@ #include "content/renderer/media/media_stream_video_track.h" +#include <string> #include <utility> #include "base/bind.h" @@ -12,6 +13,7 @@ #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" +#include "build/build_config.h" #include "content/renderer/media/media_stream_constraints_util_video_device.h" #include "media/capture/video_capture_types.h" @@ -381,6 +383,19 @@ settings.facing_mode = blink::WebMediaStreamTrack::FacingMode::kNone; break; } +#if defined(OS_ANDROID) + // On Android, the facing mode is not available in the |video_facing| field, + // but is available as part of the label. + // TODO(guidou): Remove this code once the |video_facing| field is supported + // on Android. See http://crbug.com/672856. + if (source_->device_info().device.name.find("front") != std::string::npos) { + settings.facing_mode = blink::WebMediaStreamTrack::FacingMode::kUser; + } else if (source_->device_info().device.name.find("back") != + std::string::npos) { + settings.facing_mode = blink::WebMediaStreamTrack::FacingMode::kEnvironment; + } +#endif + const base::Optional<CameraCalibration> calibration = source_->device_info().device.camera_calibration; if (calibration) {
diff --git a/content/renderer/media/mock_media_stream_registry.cc b/content/renderer/media/mock_media_stream_registry.cc index 7f10526e..ff5ecdff 100644 --- a/content/renderer/media/mock_media_stream_registry.cc +++ b/content/renderer/media/mock_media_stream_registry.cc
@@ -66,8 +66,7 @@ blink_source.Initialize("mock video source id", blink::WebMediaStreamSource::kTypeVideo, "mock video source name", false /* remote */); - MockMediaStreamVideoSource* native_source = - new MockMediaStreamVideoSource(false /* manual get supported formats */); + MockMediaStreamVideoSource* native_source = new MockMediaStreamVideoSource(); blink_source.SetExtraData(native_source); blink::WebMediaStreamTrack blink_track; blink_track.Initialize(blink::WebString::FromUTF8(track_id), blink_source);
diff --git a/content/renderer/media/mock_media_stream_video_source.cc b/content/renderer/media/mock_media_stream_video_source.cc index 05070df..d134d46 100644 --- a/content/renderer/media/mock_media_stream_video_source.cc +++ b/content/renderer/media/mock_media_stream_video_source.cc
@@ -10,30 +10,21 @@ namespace content { -MockMediaStreamVideoSource::MockMediaStreamVideoSource( - bool manual_get_supported_formats) - : MockMediaStreamVideoSource(manual_get_supported_formats, false) {} +MockMediaStreamVideoSource::MockMediaStreamVideoSource() + : MockMediaStreamVideoSource(false) {} MockMediaStreamVideoSource::MockMediaStreamVideoSource( - bool manual_get_supported_formats, bool respond_to_request_refresh_frame) - : manual_get_supported_formats_(manual_get_supported_formats), - respond_to_request_refresh_frame_(respond_to_request_refresh_frame), + : respond_to_request_refresh_frame_(respond_to_request_refresh_frame), max_requested_height_(0), max_requested_width_(0), max_requested_frame_rate_(0.0), - attempted_to_start_(false) { - supported_formats_.push_back(media::VideoCaptureFormat( - gfx::Size(MediaStreamVideoSource::kDefaultWidth, - MediaStreamVideoSource::kDefaultHeight), - MediaStreamVideoSource::kDefaultFrameRate, media::PIXEL_FORMAT_I420)); -} + attempted_to_start_(false) {} MockMediaStreamVideoSource::MockMediaStreamVideoSource( const media::VideoCaptureFormat& format, bool respond_to_request_refresh_frame) : format_(format), - manual_get_supported_formats_(false), respond_to_request_refresh_frame_(respond_to_request_refresh_frame), max_requested_height_(format.frame_size.height()), max_requested_width_(format.frame_size.width()), @@ -54,11 +45,6 @@ OnStartDone(MEDIA_DEVICE_TRACK_START_FAILURE); } -void MockMediaStreamVideoSource::CompleteGetSupportedFormats() { - DCHECK(!formats_callback_.is_null()); - base::ResetAndReturn(&formats_callback_).Run(supported_formats_); -} - void MockMediaStreamVideoSource::RequestRefreshFrame() { DCHECK(!frame_callback_.is_null()); if (respond_to_request_refresh_frame_) { @@ -70,26 +56,7 @@ } } -void MockMediaStreamVideoSource::GetCurrentSupportedFormats( - int max_requested_height, - int max_requested_width, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) { - DCHECK(formats_callback_.is_null()); - max_requested_height_ = max_requested_height; - max_requested_width_ = max_requested_width; - max_requested_frame_rate_ = max_requested_frame_rate; - - if (manual_get_supported_formats_) { - formats_callback_ = callback; - return; - } - callback.Run(supported_formats_); -} - void MockMediaStreamVideoSource::StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) { DCHECK(frame_callback_.is_null()); attempted_to_start_ = true; @@ -100,7 +67,8 @@ } base::Optional<media::VideoCaptureFormat> -MockMediaStreamVideoSource::GetCurrentFormatImpl() const { +MockMediaStreamVideoSource::GetCurrentFormat() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return base::Optional<media::VideoCaptureFormat>(format_); }
diff --git a/content/renderer/media/mock_media_stream_video_source.h b/content/renderer/media/mock_media_stream_video_source.h index 7c4746e..0dac396 100644 --- a/content/renderer/media/mock_media_stream_video_source.h +++ b/content/renderer/media/mock_media_stream_video_source.h
@@ -14,9 +14,8 @@ class MockMediaStreamVideoSource : public MediaStreamVideoSource { public: - explicit MockMediaStreamVideoSource(bool manual_get_supported_formats); - MockMediaStreamVideoSource(bool manual_get_supported_formats, - bool respond_to_request_refresh_frame); + MockMediaStreamVideoSource(); + explicit MockMediaStreamVideoSource(bool respond_to_request_refresh_frame); MockMediaStreamVideoSource(const media::VideoCaptureFormat& format, bool respond_to_request_refresh_frame); virtual ~MockMediaStreamVideoSource(); @@ -33,10 +32,6 @@ // or FailToStartMockedSource has not been called. bool SourceHasAttemptedToStart() { return attempted_to_start_; } - void SetSupportedFormats(const media::VideoCaptureFormats& formats) { - supported_formats_ = formats; - } - // Delivers |frame| to all registered tracks on the IO thread. Its up to the // call to make sure MockMediaStreamVideoSource is not destroyed before the // frame has been delivered. @@ -59,29 +54,18 @@ protected: // Implements MediaStreamVideoSource. - void GetCurrentSupportedFormats( - int max_requested_height, - int max_requested_width, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) override; void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) override; void StopSourceImpl() override; - base::Optional<media::VideoCaptureFormat> GetCurrentFormatImpl() - const override; + base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const override; private: media::VideoCaptureFormat format_; - media::VideoCaptureFormats supported_formats_; - bool manual_get_supported_formats_; bool respond_to_request_refresh_frame_; int max_requested_height_; int max_requested_width_; double max_requested_frame_rate_; bool attempted_to_start_; - VideoCaptureDeviceFormatsCB formats_callback_; VideoCaptureDeliverFrameCB frame_callback_; DISALLOW_COPY_AND_ASSIGN(MockMediaStreamVideoSource);
diff --git a/content/renderer/media/pepper_to_video_track_adapter.cc b/content/renderer/media/pepper_to_video_track_adapter.cc index 104bd01..ca3b2db 100644 --- a/content/renderer/media/pepper_to_video_track_adapter.cc +++ b/content/renderer/media/pepper_to_video_track_adapter.cc
@@ -46,14 +46,7 @@ protected: // MediaStreamVideoSource implementation. - void GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) override; void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) override; void StopSourceImpl() override; @@ -116,22 +109,7 @@ DVLOG(3) << "PpFrameWriter dtor"; } -void PpFrameWriter::GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DVLOG(3) << "PpFrameWriter::GetCurrentSupportedFormats()"; - // Since the input is free to change the resolution at any point in time - // the supported formats are unknown. - media::VideoCaptureFormats formats; - callback.Run(formats); -} - void PpFrameWriter::StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!delegate_.get());
diff --git a/content/renderer/media/renderer_webaudiodevice_impl.cc b/content/renderer/media/renderer_webaudiodevice_impl.cc index 568052e5..ef941bec 100644 --- a/content/renderer/media/renderer_webaudiodevice_impl.cc +++ b/content/renderer/media/renderer_webaudiodevice_impl.cc
@@ -65,9 +65,12 @@ hardware_params.sample_rate(), 0); break; case media::AudioLatency::LATENCY_EXACT_MS: - return media::AudioLatency::GetExactBufferSize( - base::TimeDelta::FromSecondsD(latency_hint.Seconds()), - hardware_params.sample_rate(), hardware_params.frames_per_buffer()); + // TODO(andrew.macpherson@soundtrap.com): http://crbug.com/708917 + return std::min(4096, + media::AudioLatency::GetExactBufferSize( + base::TimeDelta::FromSecondsD(latency_hint.Seconds()), + hardware_params.sample_rate(), + hardware_params.frames_per_buffer())); break; default: NOTREACHED();
diff --git a/content/renderer/media/rtc_peer_connection_handler_unittest.cc b/content/renderer/media/rtc_peer_connection_handler_unittest.cc index 66d6be9..91cb0f5 100644 --- a/content/renderer/media/rtc_peer_connection_handler_unittest.cc +++ b/content/renderer/media/rtc_peer_connection_handler_unittest.cc
@@ -313,7 +313,7 @@ blink::WebString::FromUTF8("video_track"), false /* remote */); MockMediaStreamVideoSource* native_video_source = - new MockMediaStreamVideoSource(false); + new MockMediaStreamVideoSource(); video_source.SetExtraData(native_video_source); blink::WebVector<blink::WebMediaStreamTrack> audio_tracks(
diff --git a/content/renderer/media/user_media_client_impl.cc b/content/renderer/media/user_media_client_impl.cc index 8cdc27b0..be92c59 100644 --- a/content/renderer/media/user_media_client_impl.cc +++ b/content/renderer/media/user_media_client_impl.cc
@@ -232,6 +232,16 @@ source == kMediaStreamSourceScreen; } +void SurfaceHardwareEchoCancellationSetting( + blink::WebMediaStreamSource* source) { + MediaStreamAudioSource* source_impl = + static_cast<MediaStreamAudioSource*>(source->GetExtraData()); + media::AudioParameters params = source_impl->GetAudioParameters(); + if (params.IsValid() && + (params.effects() & media::AudioParameters::ECHO_CANCELLER)) + source->SetEchoCancellation(true); +} + static int g_next_request_id = 0; } // namespace @@ -968,18 +978,26 @@ &UserMediaClientImpl::OnAudioSourceStartedOnAudioThread, base::ThreadTaskRunnerHandle::Get(), weak_factory_.GetWeakPtr()); - MediaStreamAudioSource* const audio_source = - CreateAudioSource(device, constraints, source_ready); + bool has_sw_echo_cancellation = false; + MediaStreamAudioSource* const audio_source = CreateAudioSource( + device, constraints, source_ready, &has_sw_echo_cancellation); audio_source->SetStopCallback(base::Bind( &UserMediaClientImpl::OnLocalSourceStopped, weak_factory_.GetWeakPtr())); source.SetExtraData(audio_source); // Takes ownership. + // At this point it is known if software echo cancellation will be used, but + // final audio parameters for the source are not set yet, so it is not yet + // known if hardware echo cancellation will actually be used. That information + // is known and surfaced in CreateAudioTracks(), after the track is connected + // to the source. + source.SetEchoCancellation(has_sw_echo_cancellation); return source; } MediaStreamAudioSource* UserMediaClientImpl::CreateAudioSource( const StreamDeviceInfo& device, const blink::WebMediaConstraints& constraints, - const MediaStreamSource::ConstraintsCallback& source_ready) { + const MediaStreamSource::ConstraintsCallback& source_ready, + bool* has_sw_echo_cancellation) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(current_request_info_); // If the audio device is a loopback device (for screen capture), or if the @@ -993,6 +1011,7 @@ if (IsScreenCaptureMediaType(device.device.type) || !MediaStreamAudioProcessor::WouldModifyAudio( audio_processing_properties)) { + *has_sw_echo_cancellation = false; return new LocalMediaStreamAudioSource(RenderFrameObserver::routing_id(), device, source_ready); } @@ -1002,6 +1021,8 @@ ProcessedLocalAudioSource* source = new ProcessedLocalAudioSource( RenderFrameObserver::routing_id(), device, audio_processing_properties, source_ready, dependency_factory_); + *has_sw_echo_cancellation = + audio_processing_properties.enable_sw_echo_cancellation; return source; } @@ -1065,6 +1086,10 @@ overridden_audio_array[i], constraints, &is_pending); (*webkit_tracks)[i].Initialize(source); current_request_info_->StartAudioTrack((*webkit_tracks)[i], is_pending); + // At this point the source has started, and its audio parameters have been + // set. From the parameters, it is known if hardware echo cancellation is + // being used. If this is the case, let |source| know. + SurfaceHardwareEchoCancellationSetting(&source); } }
diff --git a/content/renderer/media/user_media_client_impl.h b/content/renderer/media/user_media_client_impl.h index ba4998d..8b3508f 100644 --- a/content/renderer/media/user_media_client_impl.h +++ b/content/renderer/media/user_media_client_impl.h
@@ -114,7 +114,8 @@ virtual MediaStreamAudioSource* CreateAudioSource( const StreamDeviceInfo& device, const blink::WebMediaConstraints& constraints, - const MediaStreamSource::ConstraintsCallback& source_ready); + const MediaStreamSource::ConstraintsCallback& source_ready, + bool* has_sw_echo_cancellation); virtual MediaStreamVideoSource* CreateVideoSource( const StreamDeviceInfo& device, const MediaStreamSource::SourceStoppedCallback& stop_callback);
diff --git a/content/renderer/media/user_media_client_impl_unittest.cc b/content/renderer/media/user_media_client_impl_unittest.cc index b5505f0..6c79f60 100644 --- a/content/renderer/media/user_media_client_impl_unittest.cc +++ b/content/renderer/media/user_media_client_impl_unittest.cc
@@ -98,11 +98,10 @@ class MockMediaStreamVideoCapturerSource : public MockMediaStreamVideoSource { public: - MockMediaStreamVideoCapturerSource( - const StreamDeviceInfo& device, - const SourceStoppedCallback& stop_callback, - PeerConnectionDependencyFactory* factory) - : MockMediaStreamVideoSource(false) { + MockMediaStreamVideoCapturerSource(const StreamDeviceInfo& device, + const SourceStoppedCallback& stop_callback, + PeerConnectionDependencyFactory* factory) + : MockMediaStreamVideoSource() { SetDeviceInfo(device); SetStopCallback(stop_callback); } @@ -284,7 +283,8 @@ MediaStreamAudioSource* CreateAudioSource( const StreamDeviceInfo& device, const blink::WebMediaConstraints& constraints, - const MediaStreamSource::ConstraintsCallback& source_ready) override { + const MediaStreamSource::ConstraintsCallback& source_ready, + bool* has_sw_echo_cancellation) override { MediaStreamAudioSource* source; if (create_source_that_fails_) { class FailedAtLifeAudioSource : public MediaStreamAudioSource { @@ -310,6 +310,7 @@ source_ready, source)); } + *has_sw_echo_cancellation = false; return source; }
diff --git a/content/renderer/media/webrtc/media_stream_remote_video_source.cc b/content/renderer/media/webrtc/media_stream_remote_video_source.cc index bf34d04..bfadcb9f 100644 --- a/content/renderer/media/webrtc/media_stream_remote_video_source.cc +++ b/content/renderer/media/webrtc/media_stream_remote_video_source.cc
@@ -186,21 +186,7 @@ StopSourceImpl(); } -void MediaStreamRemoteVideoSource::GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - media::VideoCaptureFormats formats; - // Since the remote end is free to change the resolution at any point in time - // the supported formats are unknown. - callback.Run(formats); -} - void MediaStreamRemoteVideoSource::StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!delegate_.get());
diff --git a/content/renderer/media/webrtc/media_stream_remote_video_source.h b/content/renderer/media/webrtc/media_stream_remote_video_source.h index b3d50cd..0355ae8 100644 --- a/content/renderer/media/webrtc/media_stream_remote_video_source.h +++ b/content/renderer/media/webrtc/media_stream_remote_video_source.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_RENDERER_MEDIA_WEBRTC_MEDIA_STREAM_REMOTE_VIDEO_SOURCE_H_ #define CONTENT_RENDERER_MEDIA_WEBRTC_MEDIA_STREAM_REMOTE_VIDEO_SOURCE_H_ +#include <memory> + #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" @@ -24,7 +26,8 @@ class CONTENT_EXPORT MediaStreamRemoteVideoSource : public MediaStreamVideoSource { public: - MediaStreamRemoteVideoSource(std::unique_ptr<TrackObserver> observer); + explicit MediaStreamRemoteVideoSource( + std::unique_ptr<TrackObserver> observer); ~MediaStreamRemoteVideoSource() override; // Should be called when the remote video track this source originates from is @@ -34,15 +37,7 @@ protected: // Implements MediaStreamVideoSource. - void GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) override; - void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) override; void StopSourceImpl() override;
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc b/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc index db43fcdd..4ecec10 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter_map_unittest.cc
@@ -5,6 +5,7 @@ #include "content/renderer/media/webrtc/webrtc_media_stream_adapter_map.h" #include <memory> +#include <string> #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" @@ -50,8 +51,7 @@ video_source.Initialize("video_source", blink::WebMediaStreamSource::kTypeVideo, "video_source", false /* remote */); - MediaStreamVideoSource* native_source = - new MockMediaStreamVideoSource(false); + MediaStreamVideoSource* native_source = new MockMediaStreamVideoSource(); video_source.SetExtraData(native_source); web_video_tracks[0] = MediaStreamVideoTrack::CreateVideoTrack( native_source, MediaStreamVideoSource::ConstraintsCallback(), true);
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc b/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc index 1d4204eb..6c26895c3 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc +++ b/content/renderer/media/webrtc/webrtc_media_stream_adapter_unittest.cc
@@ -83,8 +83,7 @@ blink::WebMediaStreamSource video_source; video_source.Initialize("video", blink::WebMediaStreamSource::kTypeVideo, "video", false /* remote */); - MediaStreamVideoSource* native_source = - new MockMediaStreamVideoSource(false); + MediaStreamVideoSource* native_source = new MockMediaStreamVideoSource(); video_source.SetExtraData(native_source); video_track_vector[0] = MediaStreamVideoTrack::CreateVideoTrack( native_source, MediaStreamVideoSource::ConstraintsCallback(), true);
diff --git a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc index 2a14cc4..247b3096 100644 --- a/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc +++ b/content/renderer/media/webrtc/webrtc_media_stream_track_adapter_unittest.cc
@@ -65,8 +65,7 @@ blink::WebMediaStreamSource::kTypeVideo, blink::WebString::FromUTF8("local_video_track"), false); - MockMediaStreamVideoSource* video_source = - new MockMediaStreamVideoSource(true); + MockMediaStreamVideoSource* video_source = new MockMediaStreamVideoSource(); // Takes ownership of |video_source|. web_source.SetExtraData(video_source);
diff --git a/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc b/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc index 76a214b..c3af903 100644 --- a/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc +++ b/content/renderer/media_capture_from_element/canvas_capture_handler_unittest.cc
@@ -74,12 +74,6 @@ DoOnDeliverFrame(video_frame, estimated_capture_time); } - MOCK_METHOD1(DoOnVideoCaptureDeviceFormats, - void(const media::VideoCaptureFormats&)); - void OnVideoCaptureDeviceFormats(const media::VideoCaptureFormats& formats) { - DoOnVideoCaptureDeviceFormats(formats); - } - MOCK_METHOD1(DoOnRunning, void(bool)); void OnRunning(bool state) { DoOnRunning(state); } @@ -174,16 +168,7 @@ media::VideoCapturerSource* source = GetVideoCapturerSource(ms_source); EXPECT_TRUE(source != nullptr); - media::VideoCaptureFormats formats; - EXPECT_CALL(*this, DoOnVideoCaptureDeviceFormats(_)) - .Times(1) - .WillOnce(SaveArg<0>(&formats)); - source->GetCurrentSupportedFormats( - media::limits::kMaxCanvas /* max_requesteed_width */, - media::limits::kMaxCanvas /* max_requesteed_height */, - media::limits::kMaxFramesPerSecond /* max_requested_frame_rate */, - base::Bind(&CanvasCaptureHandlerTest::OnVideoCaptureDeviceFormats, - base::Unretained(this))); + media::VideoCaptureFormats formats = source->GetPreferredFormats(); ASSERT_EQ(2u, formats.size()); EXPECT_EQ(kTestCanvasCaptureWidth, formats[0].frame_size.width()); EXPECT_EQ(kTestCanvasCaptureHeight, formats[0].frame_size.height());
diff --git a/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc b/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc index 8f2ffa07..95e73fd 100644 --- a/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc +++ b/content/renderer/media_capture_from_element/html_video_element_capturer_source_unittest.cc
@@ -99,12 +99,6 @@ DoOnDeliverFrame(video_frame, estimated_capture_time); } - MOCK_METHOD1(DoOnVideoCaptureDeviceFormats, - void(const media::VideoCaptureFormats&)); - void OnVideoCaptureDeviceFormats(const media::VideoCaptureFormats& formats) { - DoOnVideoCaptureDeviceFormats(formats); - } - MOCK_METHOD1(DoOnRunning, void(bool)); void OnRunning(bool state) { DoOnRunning(state); } @@ -126,18 +120,8 @@ // frames. TEST_F(HTMLVideoElementCapturerSourceTest, GetFormatsAndStartAndStop) { InSequence s; - media::VideoCaptureFormats formats; - EXPECT_CALL(*this, DoOnVideoCaptureDeviceFormats(_)) - .Times(1) - .WillOnce(SaveArg<0>(&formats)); - - html_video_capturer_->GetCurrentSupportedFormats( - media::limits::kMaxCanvas /* max_requesteed_width */, - media::limits::kMaxCanvas /* max_requesteed_height */, - media::limits::kMaxFramesPerSecond /* max_requested_frame_rate */, - base::Bind( - &HTMLVideoElementCapturerSourceTest::OnVideoCaptureDeviceFormats, - base::Unretained(this))); + media::VideoCaptureFormats formats = + html_video_capturer_->GetPreferredFormats(); ASSERT_EQ(1u, formats.size()); EXPECT_EQ(web_media_player_->NaturalSize().width, formats[0].frame_size.width());
diff --git a/content/renderer/media_recorder/video_track_recorder_unittest.cc b/content/renderer/media_recorder/video_track_recorder_unittest.cc index 287127c..572c216 100644 --- a/content/renderer/media_recorder/video_track_recorder_unittest.cc +++ b/content/renderer/media_recorder/video_track_recorder_unittest.cc
@@ -61,8 +61,7 @@ : public TestWithParam< testing::tuple<VideoTrackRecorder::CodecId, gfx::Size, bool>> { public: - VideoTrackRecorderTest() - : mock_source_(new MockMediaStreamVideoSource(false)) { + VideoTrackRecorderTest() : mock_source_(new MockMediaStreamVideoSource()) { const blink::WebString webkit_track_id( blink::WebString::FromASCII("dummy")); blink_source_.Initialize(webkit_track_id,
diff --git a/content/renderer/pepper/pepper_media_stream_video_track_host.cc b/content/renderer/pepper/pepper_media_stream_video_track_host.cc index 4924a98..b486a17 100644 --- a/content/renderer/pepper/pepper_media_stream_video_track_host.cc +++ b/content/renderer/pepper/pepper_media_stream_video_track_host.cc
@@ -414,23 +414,7 @@ ~VideoSource() final { StopSourceImpl(); } - void GetCurrentSupportedFormats( - int max_requested_width, int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) final { - media::VideoCaptureFormats formats; - if (host_) { - formats.push_back(media::VideoCaptureFormat( - host_->plugin_frame_size_, - kDefaultOutputFrameRate, - ToPixelFormat(host_->plugin_frame_format_))); - } - callback.Run(formats); - } - void StartSourceImpl( - const media::VideoCaptureFormat& format, - const blink::WebMediaConstraints& constraints, const VideoCaptureDeliverFrameCB& frame_callback) final { if (host_) { host_->frame_deliverer_ = @@ -444,8 +428,7 @@ } private: - base::Optional<media::VideoCaptureFormat> GetCurrentFormatImpl() - const override { + base::Optional<media::VideoCaptureFormat> GetCurrentFormat() const override { if (host_) { return base::Optional<media::VideoCaptureFormat>( media::VideoCaptureFormat(
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 71fd95c..7683fb5 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -37,7 +37,6 @@ #include "content/common/host_zoom.mojom.h" #include "content/common/renderer.mojom.h" #include "content/common/unique_name_helper.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/common/console_message_level.h" #include "content/public/common/javascript_dialog_type.h" #include "content/public/common/previews_state.h" @@ -45,6 +44,7 @@ #include "content/public/common/renderer_preferences.h" #include "content/public/common/request_context_type.h" #include "content/public/common/stop_find_action.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/renderer/render_frame.h" #include "content/renderer/frame_blame_context.h" #include "content/renderer/media/media_factory.h"
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 8cf0aef8..6ae346c 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -2517,11 +2517,13 @@ v8::MemoryPressureLevel v8_memory_pressure_level = static_cast<v8::MemoryPressureLevel>(memory_pressure_level); +#if !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND) // In order to reduce performance impact, translate critical level to - // moderate level for foregroud renderer. + // moderate level for foreground renderer. if (!RendererIsHidden() && v8_memory_pressure_level == v8::MemoryPressureLevel::kCritical) v8_memory_pressure_level = v8::MemoryPressureLevel::kModerate; +#endif // !BUILDFLAG(ALLOW_CRITICAL_MEMORY_PRESSURE_HANDLING_IN_FOREGROUND) blink::MainThreadIsolate()->MemoryPressureNotification( v8_memory_pressure_level);
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index a05e2740..e653a59 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -42,7 +42,7 @@ #include "content/common/renderer.mojom.h" #include "content/common/renderer_host.mojom.h" #include "content/common/storage_partition_service.mojom.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/public/renderer/render_thread.h" #include "content/renderer/gpu/compositor_dependencies.h" #include "content/renderer/layout_test_dependencies.h"
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 0ef0f67..d0f55d4 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -2467,11 +2467,11 @@ OnResize(params); } -void RenderViewImpl::SetDeviceColorProfileForTesting( - const gfx::ICCProfile& icc_profile) { +void RenderViewImpl::SetDeviceColorSpaceForTesting( + const gfx::ColorSpace& color_space) { ResizeParams params; params.screen_info = screen_info_; - params.screen_info.color_space = icc_profile.GetColorSpace(); + params.screen_info.color_space = color_space; params.new_size = size(); params.visible_viewport_size = visible_viewport_size_; params.physical_backing_size = physical_backing_size_;
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 91eb6de..452aa15 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -86,7 +86,7 @@ } // namespace blink namespace gfx { -class ICCProfile; +class ColorSpace; } namespace content { @@ -233,7 +233,7 @@ void SetDeviceScaleFactorForTesting(float factor); // Change the device ICC color profile while running a layout test. - void SetDeviceColorProfileForTesting(const gfx::ICCProfile& icc_profile); + void SetDeviceColorSpaceForTesting(const gfx::ColorSpace& color_space); // Used to force the size of a window when running layout tests. void ForceResizeForTesting(const gfx::Size& new_size);
diff --git a/content/renderer/renderer_blink_platform_impl.h b/content/renderer/renderer_blink_platform_impl.h index 3ea9374..c5614a1 100644 --- a/content/renderer/renderer_blink_platform_impl.h +++ b/content/renderer/renderer_blink_platform_impl.h
@@ -20,7 +20,7 @@ #include "content/child/blink_platform_impl.h" #include "content/common/content_export.h" #include "content/common/possibly_associated_interface_ptr.h" -#include "content/common/url_loader_factory.mojom.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "content/renderer/origin_trials/web_trial_token_validator_impl.h" #include "content/renderer/top_level_blame_context.h" #include "content/renderer/webpublicsuffixlist_impl.h"
diff --git a/content/renderer/service_worker/embedded_worker_instance_client_impl.cc b/content/renderer/service_worker/embedded_worker_instance_client_impl.cc index c2b8dcd..d513426 100644 --- a/content/renderer/service_worker/embedded_worker_instance_client_impl.cc +++ b/content/renderer/service_worker/embedded_worker_instance_client_impl.cc
@@ -10,6 +10,7 @@ #include "base/strings/utf_string_conversions.h" #include "content/child/scoped_child_process_reference.h" #include "content/common/service_worker/embedded_worker_messages.h" +#include "content/common/service_worker/service_worker_utils.h" #include "content/public/common/content_client.h" #include "content/renderer/service_worker/embedded_worker_devtools_agent.h" #include "content/renderer/service_worker/service_worker_context_client.h" @@ -110,8 +111,9 @@ EmbeddedWorkerInstanceClientImpl::StartWorkerContext( const EmbeddedWorkerStartParams& params, std::unique_ptr<ServiceWorkerContextClient> context_client) { - std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManager> manager = - WebServiceWorkerInstalledScriptsManagerImpl::Create(); + std::unique_ptr<blink::WebServiceWorkerInstalledScriptsManager> manager; + if (ServiceWorkerUtils::IsScriptStreamingEnabled()) + manager = WebServiceWorkerInstalledScriptsManagerImpl::Create(); auto wrapper = base::MakeUnique<WorkerWrapper>( blink::WebEmbeddedWorker::Create(std::move(context_client),
diff --git a/content/shell/BUILD.gn b/content/shell/BUILD.gn index 785bd7a..e161d9c 100644 --- a/content/shell/BUILD.gn +++ b/content/shell/BUILD.gn
@@ -231,7 +231,7 @@ "//content/app/resources", "//content/app/strings", "//content/gpu", - "//content/public/common:interfaces", + "//content/public/common", "//content/public/common:service_names", "//content/shell/test_runner:test_runner", "//content/test:content_test_mojo_bindings", @@ -297,7 +297,10 @@ ] } if (mojo_media_host == "browser") { - deps += [ "//media/mojo/services" ] + deps += [ + "//media/mojo/interfaces:constants", + "//media/mojo/services", + ] } if (is_win) {
diff --git a/content/shell/android/BUILD.gn b/content/shell/android/BUILD.gn index 2c140859..b6fd7b6 100644 --- a/content/shell/android/BUILD.gn +++ b/content/shell/android/BUILD.gn
@@ -41,7 +41,6 @@ if (is_component_build) { deps += [ "//device/gamepad", - "//device/generic_sensor", "//device/sensors", "//media/midi", ] @@ -277,7 +276,6 @@ if (is_component_build) { deps += [ "//device/gamepad", - "//device/generic_sensor", "//device/sensors", "//media/midi", ]
diff --git a/content/shell/browser/shell_content_browser_client.cc b/content/shell/browser/shell_content_browser_client.cc index 62fb2b6..21c02e6 100644 --- a/content/shell/browser/shell_content_browser_client.cc +++ b/content/shell/browser/shell_content_browser_client.cc
@@ -70,6 +70,7 @@ #endif #if BUILDFLAG(ENABLE_MOJO_MEDIA_IN_BROWSER_PROCESS) +#include "media/mojo/interfaces/constants.mojom.h" // nogncheck #include "media/mojo/services/media_service_factory.h" // nogncheck #endif @@ -238,7 +239,7 @@ { service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(&media::CreateMediaServiceForTesting); - services->insert(std::make_pair("media", info)); + services->insert(std::make_pair(media::mojom::kMediaServiceName, info)); } #endif }
diff --git a/content/shell/browser/shell_web_contents_view_delegate_android.cc b/content/shell/browser/shell_web_contents_view_delegate_android.cc index 63dd182..37ea944e 100644 --- a/content/shell/browser/shell_web_contents_view_delegate_android.cc +++ b/content/shell/browser/shell_web_contents_view_delegate_android.cc
@@ -5,7 +5,6 @@ #include "content/shell/browser/shell_web_contents_view_delegate.h" #include "base/command_line.h" -#include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents.h" #include "content/public/common/context_menu_params.h" #include "content/shell/browser/shell_web_contents_view_delegate_creator.h"
diff --git a/content/shell/renderer/layout_test/blink_test_runner.cc b/content/shell/renderer/layout_test/blink_test_runner.cc index 18ed153..4a6ef125 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.cc +++ b/content/shell/renderer/layout_test/blink_test_runner.cc
@@ -536,8 +536,8 @@ return content::IsUseZoomForDSFEnabled(); } -void BlinkTestRunner::SetDeviceColorProfile(const std::string& name) { - content::SetDeviceColorProfile(render_view(), GetTestingICCProfile(name)); +void BlinkTestRunner::SetDeviceColorSpace(const std::string& name) { + content::SetDeviceColorSpace(render_view(), GetTestingColorSpace(name)); } void BlinkTestRunner::SetBluetoothFakeAdapter(const std::string& adapter_name,
diff --git a/content/shell/renderer/layout_test/blink_test_runner.h b/content/shell/renderer/layout_test/blink_test_runner.h index ee74488..c3b497aa 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.h +++ b/content/shell/renderer/layout_test/blink_test_runner.h
@@ -104,7 +104,7 @@ void SimulateWebNotificationClose(const std::string& title, bool by_user) override; void SetDeviceScaleFactor(float factor) override; - void SetDeviceColorProfile(const std::string& name) override; + void SetDeviceColorSpace(const std::string& name) override; float GetWindowToViewportScale() override; std::unique_ptr<blink::WebInputEvent> TransformScreenToWidgetCoordinates( test_runner::WebWidgetTestProxyBase* web_widget_test_proxy_base,
diff --git a/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc b/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc index b275d6a..bf0ffca 100644 --- a/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc +++ b/content/shell/renderer/layout_test/layout_test_content_renderer_client.cc
@@ -217,9 +217,11 @@ media::AudioLatency::GetHighLatencyBufferSize(hw_sample_rate, 0); break; case blink::WebAudioLatencyHint::kCategoryExact: - buffer_size = media::AudioLatency::GetExactBufferSize( - base::TimeDelta::FromSecondsD(latency_hint.Seconds()), hw_sample_rate, - hw_buffer_size); + // TODO(andrew.macpherson@soundtrap.com): http://crbug.com/708917 + buffer_size = std::min( + 4096, media::AudioLatency::GetExactBufferSize( + base::TimeDelta::FromSecondsD(latency_hint.Seconds()), + hw_sample_rate, hw_buffer_size)); break; default: NOTREACHED();
diff --git a/content/shell/test_runner/mock_content_settings_client.cc b/content/shell/test_runner/mock_content_settings_client.cc index 031f217..4a048898 100644 --- a/content/shell/test_runner/mock_content_settings_client.cc +++ b/content/shell/test_runner/mock_content_settings_client.cc
@@ -50,10 +50,6 @@ return flags_->storage_allowed(); } -bool MockContentSettingsClient::AllowPlugins(bool enabled_per_settings) { - return enabled_per_settings && flags_->plugins_allowed(); -} - bool MockContentSettingsClient::AllowRunningInsecureContent( bool enabled_per_settings, const blink::WebSecurityOrigin& context,
diff --git a/content/shell/test_runner/mock_content_settings_client.h b/content/shell/test_runner/mock_content_settings_client.h index ab0bc2e..0155629 100644 --- a/content/shell/test_runner/mock_content_settings_client.h +++ b/content/shell/test_runner/mock_content_settings_client.h
@@ -28,7 +28,6 @@ bool AllowScriptFromSource(bool enabled_per_settings, const blink::WebURL& script_url) override; bool AllowStorage(bool local) override; - bool AllowPlugins(bool enabled_per_settings) override; bool AllowRunningInsecureContent(bool enabled_per_settings, const blink::WebSecurityOrigin& context, const blink::WebURL& url) override;
diff --git a/content/shell/test_runner/test_runner.cc b/content/shell/test_runner/test_runner.cc index 14d4915..3bc4160 100644 --- a/content/shell/test_runner/test_runner.cc +++ b/content/shell/test_runner/test_runner.cc
@@ -1667,7 +1667,7 @@ if (delegate_) { // Reset the default quota for each origin to 5MB delegate_->SetDatabaseQuota(5 * 1024 * 1024); - delegate_->SetDeviceColorProfile("reset"); + delegate_->SetDeviceColorSpace("reset"); delegate_->SetDeviceScaleFactor(GetDefaultDeviceScaleFactor()); delegate_->SetBlockThirdPartyCookies(true); delegate_->SetLocale(""); @@ -1791,9 +1791,14 @@ void TestRunner::ReplicateLayoutTestRuntimeFlagsChanges( const base::DictionaryValue& changed_values) { - if (test_is_running_) + if (test_is_running_) { layout_test_runtime_flags_.tracked_dictionary().ApplyUntrackedChanges( changed_values); + + bool allowed = layout_test_runtime_flags_.plugins_allowed(); + for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) + window->web_view()->GetSettings()->SetPluginsEnabled(allowed); + } } bool TestRunner::HasCustomTextDump(std::string* custom_text_dump) const { @@ -2548,6 +2553,10 @@ void TestRunner::SetPluginsAllowed(bool allowed) { layout_test_runtime_flags_.set_plugins_allowed(allowed); + + for (WebViewTestProxyBase* window : test_interfaces_->GetWindowList()) + window->web_view()->GetSettings()->SetPluginsEnabled(allowed); + OnLayoutTestRuntimeFlagsChanged(); }
diff --git a/content/shell/test_runner/test_runner_for_specific_view.cc b/content/shell/test_runner/test_runner_for_specific_view.cc index 2cd0214..71310091 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.cc +++ b/content/shell/test_runner/test_runner_for_specific_view.cc
@@ -391,7 +391,7 @@ void TestRunnerForSpecificView::SetColorProfile( const std::string& name, v8::Local<v8::Function> callback) { - delegate()->SetDeviceColorProfile(name); + delegate()->SetDeviceColorSpace(name); PostV8Callback(callback); }
diff --git a/content/shell/test_runner/web_test_delegate.h b/content/shell/test_runner/web_test_delegate.h index 1bd00de..58f0fb0 100644 --- a/content/shell/test_runner/web_test_delegate.h +++ b/content/shell/test_runner/web_test_delegate.h
@@ -181,8 +181,8 @@ // Returns whether or not the use-zoom-for-dsf flag is enabled. virtual bool IsUseZoomForDSFEnabled() = 0; - // Change the device color profile while running a layout test. - virtual void SetDeviceColorProfile(const std::string& name) = 0; + // Change the device color space while running a layout test. + virtual void SetDeviceColorSpace(const std::string& name) = 0; // Set the bluetooth adapter while running a layout test, uses Mojo to // communicate with the browser.
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index c44a09e..d82ed552 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -262,7 +262,7 @@ "//content/gpu", "//content/public/browser", "//content/public/child", - "//content/public/common:interfaces", + "//content/public/common", "//content/public/common:service_names", "//content/public/renderer", "//content/public/utility", @@ -350,9 +350,9 @@ deps += [ "//third_party/webrtc/api:libjingle_peerconnection", "//third_party/webrtc/api:rtc_stats_api", - "//third_party/webrtc/rtc_base:rtc_base_approved", "//third_party/webrtc/media:rtc_media_base", "//third_party/webrtc/modules/video_capture", + "//third_party/webrtc/rtc_base:rtc_base_approved", "//third_party/webrtc/stats:rtc_stats", "//third_party/webrtc_overrides:init_webrtc", ] @@ -778,7 +778,6 @@ "//content/shell:pak", "//content/test:test_support", "//device/base/synchronization", - "//device/generic_sensor", "//device/power_save_blocker", "//device/screen_orientation/public/interfaces", "//device/sensors", @@ -799,8 +798,10 @@ "//net:test_support", "//ppapi/features", "//services/catalog:lib", + "//services/device/public/cpp/generic_sensor", "//services/device/public/interfaces", "//services/device/public/interfaces:constants", + "//services/device/public/interfaces:generic_sensor", "//services/service_manager/public/cpp", "//services/ui/gpu/interfaces", "//services/ui/public/cpp/gpu", @@ -1508,7 +1509,6 @@ "//components/metrics/proto", "//components/rappor:test_support", "//components/ukm:test_support", - "//components/ukm/public/interfaces", "//components/viz/common", "//components/viz/host", "//components/viz/service", @@ -1562,6 +1562,7 @@ "//services/device/public/interfaces:constants", "//services/file:lib", "//services/file/public/interfaces", + "//services/metrics/public/interfaces", "//services/service_manager/public/cpp:service_test_support", "//services/video_capture/public/interfaces", "//skia", @@ -1699,10 +1700,10 @@ "//third_party/webrtc/api:rtc_stats_api", "//third_party/webrtc/api:video_frame_api", "//third_party/webrtc/api/video_codecs:video_codecs_api", - "//third_party/webrtc/rtc_base:rtc_base", "//third_party/webrtc/media:rtc_media", "//third_party/webrtc/modules/desktop_capture:primitives", "//third_party/webrtc/modules/video_capture", + "//third_party/webrtc/rtc_base:rtc_base", "//third_party/webrtc/stats:rtc_stats_test_utils", "//third_party/webrtc_overrides:init_webrtc", "//ui/shell_dialogs:shell_dialogs",
diff --git a/content/test/data/media/getusermedia.html b/content/test/data/media/getusermedia.html index e39912f..d03e49b0 100644 --- a/content/test/data/media/getusermedia.html +++ b/content/test/data/media/getusermedia.html
@@ -556,6 +556,62 @@ } var detectorInterval = setInterval(detectorFunction, 50); } + + function getAudioSettingsDefault() { + navigator.mediaDevices.getUserMedia({audio:true}) + .then(stream => { + assertEquals(stream.getAudioTracks().length, 1); + var settings = stream.getAudioTracks()[0].getSettings(); + assertEquals(settings.deviceId, 'default'); + assertTrue(settings.echoCancellation); + stream.getAudioTracks()[0].stop(); + reportTestSuccess(); + }) + .catch(_=>{ + failTest("getUserMedia failed") + }); + } + + function getAudioSettingsNoEchoCancellation() { + navigator.mediaDevices.getUserMedia({audio:{echoCancellation: false}}) + .then(stream => { + assertEquals(stream.getAudioTracks().length, 1); + var settings = stream.getAudioTracks()[0].getSettings(); + assertEquals(settings.deviceId, 'default'); + assertEquals(settings.echoCancellation, false); + stream.getAudioTracks()[0].stop(); + reportTestSuccess(); + }) + .catch(_=>{ + failTest("getUserMedia failed") + }); + } + + function getAudioSettingsDeviceId() { + navigator.mediaDevices.enumerateDevices() + .then(devices => { + var last_device_id; + for (var device, i = 0; device = devices[i]; ++i) { + if (device.kind != "audioinput") + continue; + last_device_id = device.deviceId; + } + navigator.mediaDevices.getUserMedia( + {audio:{deviceId: {exact: last_device_id}}}) + .then(stream => { + assertEquals(stream.getAudioTracks().length, 1); + var settings = stream.getAudioTracks()[0].getSettings(); + assertEquals(settings.deviceId, last_device_id); + assertNotEquals(settings.deviceId, 'default'); + assertTrue(settings.echoCancellation); + stream.getAudioTracks()[0].stop(); + reportTestSuccess(); + }) + }) + .catch(e => { + failTest("Unexpected error: " + e) + }); + } </script> </head> <body>
diff --git a/content/test/gpu/generate_buildbot_json.py b/content/test/gpu/generate_buildbot_json.py index 4cfc06a..19ec8b9 100755 --- a/content/test/gpu/generate_buildbot_json.py +++ b/content/test/gpu/generate_buildbot_json.py
@@ -25,6 +25,11 @@ GPU_FYI = 'gpu_fyi' OPTIONAL = 'optional' V8_FYI = 'v8_fyi' + # The Win ANGLE AMD tryserver is split off because there isn't + # enough capacity to run all the tests from chromium.gpu.fyi's Win + # AMD bot on a tryserver. It represents some of the tests on + # win_angle_rel_ng and is not a real machine on the waterfall. + WIN_ANGLE_AMD_TRYSERVER = 'win_angle_amd_tryserver' # The predicate functions receive a list of types as input and # determine whether the test should run on the given bot. @@ -32,22 +37,29 @@ @staticmethod def DEFAULT(x): # By default, tests run on the chromium.gpu and chromium.gpu.fyi - # waterfalls, but not on the optional tryservers or on the - # client.v8.fyi waterfall. - return Types.OPTIONAL not in x and Types.V8_FYI not in x + # waterfalls, but not on the optional tryservers, nor on the + # client.v8.fyi waterfall, nor on the Win ANGLE AMD tryserver. + return Types.OPTIONAL not in x and Types.V8_FYI not in x and \ + Types.WIN_ANGLE_AMD_TRYSERVER not in x @staticmethod def FYI_ONLY(x): # This predicate is more complex than desired because the optional - # tryservers are considered to be on the chromium.gpu.fyi - # waterfall. - return Types.GPU_FYI in x and Types.OPTIONAL not in x + # tryservers and the Win ANGLE AMD tryserver are considered to be + # on the chromium.gpu.fyi waterfall. + return Types.GPU_FYI in x and Types.OPTIONAL not in x and \ + Types.WIN_ANGLE_AMD_TRYSERVER not in x @staticmethod def FYI_AND_OPTIONAL(x): return Predicates.FYI_ONLY(x) or Types.OPTIONAL in x @staticmethod + def FYI_AND_OPTIONAL_AND_WIN_ANGLE_AMD(x): + return Predicates.FYI_ONLY(x) or Types.OPTIONAL in x or \ + Types.WIN_ANGLE_AMD_TRYSERVER in x + + @staticmethod def FYI_OPTIONAL_AND_V8(x): return Predicates.FYI_AND_OPTIONAL(x) or Types.V8_FYI in x @@ -797,6 +809,22 @@ 'os_type': 'linux', 'type': Types.OPTIONAL, }, + # This tryserver doesn't actually exist; it's a separate + # configuration from the Win AMD bot on this waterfall because we + # don't have enough tryserver capacity to run all the tests from + # that bot on win_angle_rel_ng. + 'Win7 ANGLE Tryserver (AMD)': { + 'swarming_dimensions': [ + { + 'gpu': '1002:6613', + 'os': 'Windows-2008ServerR2-SP1' + }, + ], + 'build_config': 'Release', + 'swarming': True, + 'os_type': 'win', + 'type': Types.WIN_ANGLE_AMD_TRYSERVER, + }, } } @@ -961,8 +989,9 @@ 'angle_deqp_gles2_d3d11_tests': { 'tester_configs': [ { - # Run this on the FYI waterfall and optional tryservers. - 'predicate': Predicates.FYI_AND_OPTIONAL, + # Run this on the FYI waterfall, optional tryservers, and Win + # ANGLE AMD tryserver. + 'predicate': Predicates.FYI_AND_OPTIONAL_AND_WIN_ANGLE_AMD, # Run only on the Win7 NVIDIA/AMD R7 240 32- and 64-bit bots (and # trybots) for the time being, at least until more capacity is # added. @@ -1257,7 +1286,7 @@ 'angle_end2end_tests': { 'tester_configs': [ { - 'predicate': Predicates.FYI_AND_OPTIONAL, + 'predicate': Predicates.FYI_AND_OPTIONAL_AND_WIN_ANGLE_AMD, }, ], 'disabled_tester_configs': [ @@ -1281,7 +1310,7 @@ 'angle_white_box_tests': { 'tester_configs': [ { - 'predicate': Predicates.FYI_AND_OPTIONAL, + 'predicate': Predicates.FYI_AND_OPTIONAL_AND_WIN_ANGLE_AMD, # There are only Windows white box tests for now. # Enable on more configs when there will be relevant tests. 'os_types': ['win'], @@ -1878,8 +1907,9 @@ 'webgl_conformance_d3d11_passthrough': { 'tester_configs': [ { - # Run this on the FYI waterfall and optional tryservers. - 'predicate': Predicates.FYI_AND_OPTIONAL, + # Run this on the FYI waterfall, optional tryservers, and Win + # ANGLE AMD tryserver. + 'predicate': Predicates.FYI_AND_OPTIONAL_AND_WIN_ANGLE_AMD, 'os_types': ['win'], 'disabled_instrumentation_types': ['tsan'], }
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index 39781d9..c9d4204 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -61,16 +61,6 @@ # TODO(zakerinasab): check / generate reference images. self.Fail('Pixel_Canvas2DUntagged', bug=713632) - # Failures on Haswell GPUs on macOS after upgrade to 10.12.4. - self.Fail('Pixel_OffscreenCanvas2DResizeOnWorker', - ['mac', ('intel', 0x0a2e)], bug=718183) - self.Fail('Pixel_OffscreenCanvasAccelerated2D', - ['mac', ('intel', 0x0a2e)], bug=718183) - self.Fail('Pixel_OffscreenCanvasAccelerated2DWorker', - ['mac', ('intel', 0x0a2e)], bug=718183) - self.Fail('Pixel_WebGLGreenTriangle_NonChromiumImage_NoAA_NoAlpha', - ['mac', ('intel', 0x0a2e)], bug=718183) - self.Flaky('Pixel_OffscreenCanvasTransferBeforeStyleResize', ['mac', 'linux', 'win', 'android'], bug=735228) self.Flaky('Pixel_OffscreenCanvasTransferAfterStyleResize',
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index dbadf1a..3548c8fb 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -531,16 +531,6 @@ ['mac', ('amd', 0x679e)], bug=659871) # Mac Intel - - # Regressions in 10.12.4 on Haswell GPUs. - self.Fail('deqp/functional/gles3/fbocolorbuffer/tex2d_00.html', - ['mac', ('intel', 0x0a2e)], bug=718194) - self.Fail('deqp/functional/gles3/fboinvalidate/format_00.html', - ['mac', ('intel', 0x0a2e)], bug=718194) - self.Fail('deqp/functional/gles3/framebufferblit/' + - 'default_framebuffer_05.html', - ['mac', ('intel', 0x0a2e)], bug=718194) - self.Fail('conformance2/rendering/framebuffer-texture-level1.html', ['mac', 'intel'], bug=680278) self.Fail('conformance2/textures/misc/angle-stuck-depth-textures.html',
diff --git a/content/test/layouttest_support.cc b/content/test/layouttest_support.cc index 3d11b82..f85add0 100644 --- a/content/test/layouttest_support.cc +++ b/content/test/layouttest_support.cc
@@ -499,25 +499,25 @@ return ui::TranslateAndScaleWebInputEvent(event, delta, scale); } -gfx::ICCProfile GetTestingICCProfile(const std::string& name) { +gfx::ColorSpace GetTestingColorSpace(const std::string& name) { if (name == "genericRGB") { - return gfx::ICCProfileForTestingGenericRGB(); + return gfx::ICCProfileForTestingGenericRGB().GetColorSpace(); } else if (name == "sRGB") { - return gfx::ICCProfileForTestingSRGB(); + return gfx::ColorSpace::CreateSRGB(); } else if (name == "test" || name == "colorSpin") { - return gfx::ICCProfileForTestingColorSpin(); + return gfx::ICCProfileForTestingColorSpin().GetColorSpace(); } else if (name == "adobeRGB") { - return gfx::ICCProfileForTestingAdobeRGB(); + return gfx::ICCProfileForTestingAdobeRGB().GetColorSpace(); } else if (name == "reset") { - return gfx::ICCProfileForLayoutTests(); + return gfx::ICCProfileForLayoutTests().GetColorSpace(); } - return gfx::ICCProfile(); + return gfx::ColorSpace(); } -void SetDeviceColorProfile( - RenderView* render_view, const gfx::ICCProfile& icc_profile) { - static_cast<RenderViewImpl*>(render_view)-> - SetDeviceColorProfileForTesting(icc_profile); +void SetDeviceColorSpace(RenderView* render_view, + const gfx::ColorSpace& color_space) { + static_cast<RenderViewImpl*>(render_view) + ->SetDeviceColorSpaceForTesting(color_space); } void SetTestBluetoothScanDuration() {
diff --git a/content/test/test_navigation_url_loader.cc b/content/test/test_navigation_url_loader.cc index 7ea49f2..6a7477d 100644 --- a/content/test/test_navigation_url_loader.cc +++ b/content/test/test_navigation_url_loader.cc
@@ -7,7 +7,6 @@ #include <utility> #include "content/browser/loader/navigation_url_loader_delegate.h" -#include "content/common/url_loader_factory.mojom.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/navigation_data.h" #include "content/public/browser/render_process_host.h" @@ -16,6 +15,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/resource_response.h" +#include "content/public/common/url_loader_factory.mojom.h" #include "net/url_request/redirect_info.h" namespace content {
diff --git a/content/utility/BUILD.gn b/content/utility/BUILD.gn index 0d8806d..1b92e38 100644 --- a/content/utility/BUILD.gn +++ b/content/utility/BUILD.gn
@@ -60,6 +60,7 @@ deps += [ "//media", "//media/mojo:features", + "//media/mojo/interfaces:constants", "//media/mojo/services", ] }
diff --git a/content/utility/utility_service_factory.cc b/content/utility/utility_service_factory.cc index 5678a1b..a4eedeed 100644 --- a/content/utility/utility_service_factory.cc +++ b/content/utility/utility_service_factory.cc
@@ -27,6 +27,7 @@ #include "base/memory/ptr_util.h" #include "media/cdm/cdm_adapter_factory.h" // nogncheck #include "media/mojo/features.h" // nogncheck +#include "media/mojo/interfaces/constants.mojom.h" // nogncheck #include "media/mojo/services/media_service.h" // nogncheck #include "media/mojo/services/mojo_cdm_allocator.h" // nogncheck #include "media/mojo/services/mojo_media_client.h" // nogncheck @@ -94,7 +95,7 @@ #if BUILDFLAG(ENABLE_PEPPER_CDMS) service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(&CreateMediaService); - services->insert(std::make_pair("media", info)); + services->insert(std::make_pair(media::mojom::kMediaServiceName, info)); #endif service_manager::EmbeddedServiceInfo shape_detection_info;
diff --git a/content/utility/utility_thread_impl.cc b/content/utility/utility_thread_impl.cc index ec50aba8..d7059fd 100644 --- a/content/utility/utility_thread_impl.cc +++ b/content/utility/utility_thread_impl.cc
@@ -4,30 +4,17 @@ #include "content/utility/utility_thread_impl.h" -#include <stddef.h> #include <utility> -#include "base/command_line.h" -#include "build/build_config.h" #include "content/child/blink_platform_impl.h" #include "content/child/child_process.h" -#include "content/common/child_process_messages.h" -#include "content/common/utility_messages.h" -#include "content/public/common/content_switches.h" #include "content/public/common/service_manager_connection.h" #include "content/public/common/simple_connection_filter.h" #include "content/public/utility/content_utility_client.h" #include "content/utility/utility_blink_platform_impl.h" #include "content/utility/utility_service_factory.h" #include "ipc/ipc_sync_channel.h" -#include "ppapi/features/features.h" #include "services/service_manager/public/cpp/binder_registry.h" -#include "third_party/WebKit/public/web/WebKit.h" - -#if defined(OS_POSIX) && BUILDFLAG(ENABLE_PLUGINS) -#include "base/files/file_path.h" -#include "content/common/plugin_list.h" -#endif namespace content { @@ -46,43 +33,41 @@ Init(); } -UtilityThreadImpl::~UtilityThreadImpl() { -} +UtilityThreadImpl::~UtilityThreadImpl() = default; void UtilityThreadImpl::Shutdown() { ChildThreadImpl::Shutdown(); } void UtilityThreadImpl::ReleaseProcessIfNeeded() { - if (batch_mode_) - return; - - if (IsInBrowserProcess()) { - // Close the channel to cause UtilityProcessHostImpl to be deleted. We need - // to take a different code path than the multi-process case because that - // depends on the child process going away to close the channel, but that - // can't happen when we're in single process mode. - channel()->Close(); - } else { + if (!IsInBrowserProcess()) { ChildProcess::current()->ReleaseProcess(); + return; } + + // Close the channel to cause the UtilityProcessHostImpl to be deleted. We + // need to take a different code path than the multi-process case because + // that case depends on the child process going away to close the channel, + // but that can't happen when we're in single process mode. + channel()->Close(); } void UtilityThreadImpl::EnsureBlinkInitialized() { - if (blink_platform_impl_ || IsInBrowserProcess()) { - // We can only initialize WebKit on one thread, and in single process mode - // we run the utility thread on separate thread. This means that if any code - // needs WebKit initialized in the utility process, they need to have - // another path to support single process mode. + if (blink_platform_impl_) return; - } + + // We can only initialize Blink on one thread, and in single process mode + // we run the utility thread on a separate thread. This means that if any + // code needs Blink initialized in the utility process, they need to have + // another path to support single process mode. + if (IsInBrowserProcess()) + return; blink_platform_impl_.reset(new UtilityBlinkPlatformImpl); blink::Platform::Initialize(blink_platform_impl_.get()); } void UtilityThreadImpl::Init() { - batch_mode_ = false; ChildProcess::current()->AddRefProcess(); auto registry = base::MakeUnique<service_manager::BinderRegistry>(); @@ -106,25 +91,7 @@ } bool UtilityThreadImpl::OnControlMessageReceived(const IPC::Message& msg) { - if (GetContentClient()->utility()->OnMessageReceived(msg)) - return true; - - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(UtilityThreadImpl, msg) - IPC_MESSAGE_HANDLER(UtilityMsg_BatchMode_Started, OnBatchModeStarted) - IPC_MESSAGE_HANDLER(UtilityMsg_BatchMode_Finished, OnBatchModeFinished) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void UtilityThreadImpl::OnBatchModeStarted() { - batch_mode_ = true; -} - -void UtilityThreadImpl::OnBatchModeFinished() { - batch_mode_ = false; - ReleaseProcessIfNeeded(); + return GetContentClient()->utility()->OnMessageReceived(msg); } void UtilityThreadImpl::BindServiceFactoryRequest(
diff --git a/content/utility/utility_thread_impl.h b/content/utility/utility_thread_impl.h index 6293e08e..9bfdc75 100644 --- a/content/utility/utility_thread_impl.h +++ b/content/utility/utility_thread_impl.h
@@ -6,14 +6,10 @@ #define CONTENT_UTILITY_UTILITY_THREAD_IMPL_H_ #include <memory> -#include <string> -#include <vector> #include "base/compiler_specific.h" #include "base/macros.h" -#include "build/build_config.h" #include "content/child/child_thread_impl.h" -#include "content/common/content_export.h" #include "content/public/utility/utility_thread.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/interfaces/service_factory.mojom.h" @@ -37,31 +33,27 @@ public ChildThreadImpl { public: UtilityThreadImpl(); - // Constructor that's used when running in single process mode. + // Constructor used when running in single process mode. explicit UtilityThreadImpl(const InProcessChildThreadParams& params); ~UtilityThreadImpl() override; void Shutdown() override; + // UtilityThread: void ReleaseProcessIfNeeded() override; void EnsureBlinkInitialized() override; private: void Init(); - // ChildThread implementation. + // ChildThread: bool OnControlMessageReceived(const IPC::Message& msg) override; - // IPC message handlers. - void OnBatchModeStarted(); - void OnBatchModeFinished(); - + // Binds requests to our |service factory_|. void BindServiceFactoryRequest( const service_manager::BindSourceInfo& source_info, service_manager::mojom::ServiceFactoryRequest request); - // True when we're running in batch mode. - bool batch_mode_; - + // blink::Platform implementation if needed. std::unique_ptr<UtilityBlinkPlatformImpl> blink_platform_impl_; // service_manager::mojom::ServiceFactory for service_manager::Service
diff --git a/device/BUILD.gn b/device/BUILD.gn index c1b88ee..6eac768 100644 --- a/device/BUILD.gn +++ b/device/BUILD.gn
@@ -67,7 +67,6 @@ "gamepad/gamepad_provider_unittest.cc", "gamepad/gamepad_service_unittest.cc", "gamepad/public/interfaces/gamepad_struct_traits_unittest.cc", - "generic_sensor/platform_sensor_and_provider_unittest_win.cc", "sensors/data_fetcher_shared_memory_base_unittest.cc", "sensors/sensor_manager_android_unittest.cc", "sensors/sensor_manager_chromeos_unittest.cc", @@ -87,7 +86,6 @@ "//device/gamepad/public/cpp:shared_with_blink", "//device/gamepad/public/interfaces", "//device/gamepad/public/interfaces:gamepad_struct_traits_test", - "//device/generic_sensor", "//device/geolocation:unittests", "//device/power_save_blocker", "//device/sensors", @@ -105,11 +103,6 @@ "//url", ] - if (!is_linux_without_udev) { - sources += - [ "generic_sensor/platform_sensor_and_provider_unittest_linux.cc" ] - } - # HID and Serial: # Android doesn't compile. # Linux, requires udev. @@ -246,12 +239,6 @@ "bluetooth/bluetooth_low_energy_win_fake.cc", "bluetooth/bluetooth_low_energy_win_fake.h", ] - - # Needed for "generic_sensor/platform_sensor_and_provider_unittest_win.cc" - libs = [ - "propsys.lib", - "sensorsapi.lib", - ] } if (enable_vr) {
diff --git a/device/generic_sensor/generic_sensor_export.h b/device/generic_sensor/generic_sensor_export.h deleted file mode 100644 index c019b0ca..0000000 --- a/device/generic_sensor/generic_sensor_export.h +++ /dev/null
@@ -1,29 +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 DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_EXPORT_H_ -#define DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(DEVICE_GENERIC_SENSOR_IMPLEMENTATION) -#define DEVICE_GENERIC_SENSOR_EXPORT __declspec(dllexport) -#else -#define DEVICE_GENERIC_SENSOR_EXPORT __declspec(dllimport) -#endif // defined(DEVICE_GENERIC_SENSOR_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(DEVICE_GENERIC_SENSOR_IMPLEMENTATION) -#define DEVICE_GENERIC_SENSOR_EXPORT __attribute__((visibility("default"))) -#else -#define DEVICE_GENERIC_SENSOR_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define DEVICE_GENERIC_SENSOR_EXPORT -#endif - -#endif // DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_EXPORT_H_
diff --git a/device/generic_sensor/public/cpp/generic_sensor_public_export.h b/device/generic_sensor/public/cpp/generic_sensor_public_export.h deleted file mode 100644 index fba05003..0000000 --- a/device/generic_sensor/public/cpp/generic_sensor_public_export.h +++ /dev/null
@@ -1,30 +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 DEVICE_GENERIC_SENSOR_PUBLIC_CPP_GENERIC_SENSOR_PUBLIC_EXPORT_H_ -#define DEVICE_GENERIC_SENSOR_PUBLIC_CPP_GENERIC_SENSOR_PUBLIC_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(DEVICE_GENERIC_SENSOR_PUBLIC_IMPLEMENTATION) -#define DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT __declspec(dllexport) -#else -#define DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT __declspec(dllimport) -#endif // defined(DEVICE_GENERIC_SENSOR_PUBLIC_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(DEVICE_GENERIC_SENSOR_PUBLIC_IMPLEMENTATION) -#define DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT \ - __attribute__((visibility("default"))) -#else -#define DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT -#endif - -#endif // DEVICE_GENERIC_SENSOR_PUBLIC_CPP_GENERIC_SENSOR_PUBLIC_EXPORT_H_
diff --git a/device/generic_sensor/public/interfaces/BUILD.gn b/device/generic_sensor/public/interfaces/BUILD.gn deleted file mode 100644 index 9ffc6b3..0000000 --- a/device/generic_sensor/public/interfaces/BUILD.gn +++ /dev/null
@@ -1,22 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//mojo/public/tools/bindings/mojom.gni") - -mojom("interfaces") { - visibility = [ "//device/generic_sensor/public/cpp" ] - visibility_blink = [ "//third_party/WebKit/Source/*" ] - component_output_prefix = "generic_sensor_public_interfaces" - export_class_attribute = "DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT" - export_define = "DEVICE_GENERIC_SENSOR_PUBLIC_IMPLEMENTATION=1" - export_header = - "device/generic_sensor/public/cpp/generic_sensor_public_export.h" - sources = [ - "sensor.mojom", - "sensor_provider.mojom", - ] - - # TODO(crbug.com/699569): Convert to use the new JS bindings. - use_new_js_bindings = false -}
diff --git a/device/generic_sensor/public/interfaces/OWNERS b/device/generic_sensor/public/interfaces/OWNERS deleted file mode 100644 index d39f2c5..0000000 --- a/device/generic_sensor/public/interfaces/OWNERS +++ /dev/null
@@ -1,5 +0,0 @@ -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS - -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS \ No newline at end of file
diff --git a/device/generic_sensor/public/interfaces/sensor.typemap b/device/generic_sensor/public/interfaces/sensor.typemap deleted file mode 100644 index 9360ca73..0000000 --- a/device/generic_sensor/public/interfaces/sensor.typemap +++ /dev/null
@@ -1,13 +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. - -mojom = "//device/generic_sensor/public/interfaces/sensor.mojom" -public_headers = - [ "//device/generic_sensor/public/cpp/platform_sensor_configuration.h" ] -traits_headers = [ "//device/generic_sensor/public/cpp/sensor_struct_traits.h" ] -sources = [ - "//device/generic_sensor/public/cpp/sensor_struct_traits.cc", -] -type_mappings = - [ "device.mojom.SensorConfiguration=device::PlatformSensorConfiguration" ]
diff --git a/docs/README.md b/docs/README.md index b4601df..d9f77bd 100644 --- a/docs/README.md +++ b/docs/README.md
@@ -294,6 +294,8 @@ used to automatically set proxy settings. * [Installing Chromium OS on VMWare](installation_at_vmware.md) - How to install Chromium OS on VMWare. +* [User Data Directory](user_data_dir.md) - How the user data and cache + directories are determined on all platforms. ### Probably Obsolete * [Old ChromeOS build instructions](old_chromeos_build_instructions.md)
diff --git a/docs/task_scheduler_migration.md b/docs/task_scheduler_migration.md index adca4c6..eb499ee 100644 --- a/docs/task_scheduler_migration.md +++ b/docs/task_scheduler_migration.md
@@ -59,6 +59,13 @@ if you have access to the TaskRunner instance (generic asserts discussed above are meant for anonymous methods that require static checks). +Note: Contrary to overheard belief: SequencedWorkerPool::PostTask() resulted in +an unsequenced (parallel) task. The SequencedWorkerPool allowed posting to +sequences but on its own was just a plain TaskRunner (despite having sequence in +its name...). base::PostTaskWithTraits() is thus the proper replacement if not +having explicit sequencing was intended, otherwise +base::CreateSequenceTaskRunnerWithTraits() is what you're looking for. + ## BrowserThreads All BrowserThreads but UI/IO are being migrated to TaskScheduler @@ -126,10 +133,6 @@ * Everything in a file/component needs to run on the same sequence but there isn't a clear place to own/access the common SequencedTaskRunner => base::Lazy(Sequenced|SingleThread|COMSTA)TaskRunner. -* Mojo isn't sequence-friendly yet ([coming soon](https://crbug.com/678155)). - Use base::CreateSingleThreadTaskRunnerWithTraits() instead of - base::CreateSequencedTaskRunnerWithTraits() for sequences that need to use - mojo constructs for now (tag with TODO against https://crbug.com/678155). * For anything else, ping [base/task_scheduler/OWNERS](https://cs.chromium.org/chromium/src/base/task_scheduler/OWNERS) or [scheduler-dev@chromium.org](https://groups.google.com/a/chromium.org/forum/#!forum/scheduler-dev), thanks!
diff --git a/docs/testing/web_platform_tests.md b/docs/testing/web_platform_tests.md index 949c7af..d3bc522 100644 --- a/docs/testing/web_platform_tests.md +++ b/docs/testing/web_platform_tests.md
@@ -149,9 +149,16 @@ An alternative is to write manual tests that are automated with scripts from [wpt_automation](../../third_party/WebKit/LayoutTests/external/wpt_automation). +Injection of JS in manual tests is determined by `loadAutomationScript` in +[testharnessreport.js](../../third_party/WebKit/LayoutTests/resources/testharnessreport.js). + Such tests still require case-by-case automation to run for other browser engines, but are more valuable than purely manual tests. +Manual tests that have no automation are still imported, but skipped in +[NeverFixTests](../../third_party/WebKit/LayoutTests/NeverFixTests); see +[issue 738489](https://crbug.com/738489). + *** note TODO(foolip): Figure out and document a more scalable test automation solution. ***
diff --git a/docs/user_data_dir.md b/docs/user_data_dir.md new file mode 100644 index 0000000..d1de148 --- /dev/null +++ b/docs/user_data_dir.md
@@ -0,0 +1,219 @@ +# User Data Directory + +[TOC] + +## Introduction + +The user data directory contains profile data such as history, bookmarks, and +cookies, as well as other per-installation local state. + +Each [profile](https://support.google.com/chrome/answer/2364824) is a +subdirectory (often `Default`) within the user data directory. + +## Current Location + +To determine the user data directory for a running Chrome instance: + +1. Navigate to `chrome://version` +2. Look for the `Profile Path` field. This gives the path to the profile + directory. +3. The user data directory is the parent of the profile directory. + +Example (Windows): + +* [Profile Path] `C:\Users\Alice\AppData\Local\Google\Chrome\User Data\Default` +* [User Data Dir] `C:\Users\Alice\AppData\Local\Google\Chrome\User Data` + +## Default Location + +The default location of the user data directory is computed by +[`chrome::GetDefaultUserDataDirectory`](https://cs.chromium.org/chromium/src/chrome/common/chrome_paths_internal.h?q=GetDefaultUserDataDirectory). + +Generally it varies by + +* OS platform, +* branding ([Chrome vs. Chromium](chromium_browser_vs_google_chrome.md), based + on `is_chrome_branded` in [GN + args](https://www.chromium.org/developers/gn-build-configuration)), and +* [release channel](https://www.chromium.org/getting-involved/dev-channel) + (stable / beta / dev / canary). + +### Windows + +The default location is in the local app data folder: + +* [Chrome] `%LOCALAPPDATA%\Google\Chrome\User Data` +* [Chrome Canary] `%LOCALAPPDATA%\Google\Chrome SxS\User Data` +* [Chromium] `%LOCALAPPDATA%\Chromium\User Data` + +(The canary channel suffix is determined using +[`InstallConstants::install_suffix`](https://cs.chromium.org/chromium/src/chrome/install_static/install_constants.h?q=install_suffix).) + +### Mac OS X + +The default location is in the `Application Support` folder: + +* [Chrome] `~/Library/Application Support/Google/Chrome` +* [Chrome Canary] `~/Library/Application Support/Google/Chrome Canary` +* [Chromium] `~/Library/Application Support/Chromium` + +(The canary channel suffix is determined using the `CrProductDirName` key in the +browser app's `Info.plist`.) + +### Linux + +The default location is in `~/.config`: + +* [Chrome Stable] `~/.config/google-chrome` +* [Chrome Beta] `~/.config/google-chrome-beta` +* [Chrome Dev] `~/.config/google-chrome-unstable` +* [Chromium] `~/.config/chromium` + +(The beta and dev channel suffixes are determined from `$CHROME_VERSION_EXTRA`, +which is passed by the [launch wrapper script](https://cs.chromium.org/chromium/src/chrome/installer/linux/common/wrapper?q=CHROME_VERSION_EXTRA).) + +The `~/.config` portion of the default location can be overridden by +`$CHROME_CONFIG_HOME` (since M61) or by `$XDG_CONFIG_HOME`. + +Note that `$XDG_CONFIG_HOME` affects all applications conforming to the +[XDG Base Directory Spec](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html), +while `$CHROME_CONFIG_HOME` is specific to Chrome and Chromium. + +### Chrome OS + +The default location is: `/home/chronos` + +### Android + +The default location comes from +[Context.getDir](https://developer.android.com/reference/android/content/Context.html#getDir%28java.lang.String,%20int%29) +and is specific to the app. + +Example: `/data/user/0/com.android.chrome/app_chrome` + +### iOS + +The default location is inside the application support directory in the app +sandbox. + +* [Chrome] `Library/Application Support/Google/Chrome` +* [Chromium] `Library/Application Support/Chromium` + +## Overriding the User Data Directory + +### Command Line + +On all platforms, the user data directory can be overridden by passing the +`--user-data-dir` command-line flag to the Chrome binary. + +Example: + +* [Windows] `chrome.exe --user-data-dir=c:\foo` +* [Linux] `google-chrome --user-data-dir=/path/to/foo` + +### Environment (Linux) + +On Linux, the user data directory can also be overridden with the +`$CHROME_USER_DATA_DIR` environment variable. + +The `--user-data-dir` flag takes precedence if both are present. + +### Chrome Remote Desktop sessions (Linux) + +A single Chrome instance cannot show windows on multiple X displays, and two +running Chrome instances cannot share the same user data directory. +Therefore, it's desirable for Chrome to have a separate user data directory +when running inside a [Chrome Remote +Desktop](https://support.google.com/chrome/answer/1649523) (CRD) virtual session +on a Linux host. + +By default, CRD achieves this by setting `$CHROME_USER_DATA_DIR` in the session. +Unfortunately this means that inside the session we don't get separate defaults +for different channels (Stable, Beta, Dev) or for Chrome vs. Chromium. This can +lead to profile version errors ("Your profile can not be used because it is from +a newer version of Google Chrome"). + +Since M61, this can be solved by setting `$CHROME_CONFIG_HOME` instead of +`$CHROME_USER_DATA_DIR`. Specifically, put the following in +`~/.chrome-remote-desktop-session`: + +``` +export CHROME_CONFIG_HOME="$HOME/.config/chrome-remote-desktop/chrome-config" +unset CHROME_USER_DATA_DIR +. /etc/chrome-remote-desktop-session +``` + +Then restart the host by running: `/etc/init.d/chrome-remote-desktop restart` + +### Writing an AppleScript wrapper (Mac OS X) + +On Mac OS X, you can create an application that runs Chrome with a custom +`--user-data-dir`: + +1. Open Applications > Utilities > Script Editor. + +2. Enter: + +``` +set chrome to "\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\"" +set userdatadir to "\"$HOME/Library/Application Support/Google/Chrome Alt\"" +do shell script chrome & " --user-data-dir=" & userdatadir & " > /dev/null 2>&1 &" +``` + +3. Modify as needed for your installation path, Chrome versus Chromium, and + desired user data directory. + +4. Save the script in your Applications directory with the file format + "Application". + +5. Close the Script Editor, find your newly created application, and run it. + This opens a Chrome instance pointing to your new profile. + +If you want, you can give this application the same icon as Chrome: + +1. Select the Google Chrome application and choose File > Get Info. +2. Select the icon at the top left of the info dialog. You will see a blue + highlight around the icon. +3. Press ⌘C to copy the icon. +4. Open the info dialog for the new application and select the icon in the + top left. +5. Press ⌘V to paste the copied icon. + +## User Cache Directory + +On Windows and ChromeOS, the user cache dir is the same as the profile dir. +(The profile dir is inside the user data dir.) + +On Mac OS X and iOS, the user cache dir is derived from the profile dir as +follows: + +1. If `Library/Application Support` is an ancestor of the profile dir, the user + cache dir is `Library/Caches` plus the relative path from `Application + Support` to the profile dir. +2. Otherwise, the user cache dir is the same as the profile dir. + +Example (Mac OS X): + +* [user data dir] `~/Library/Application Support/Google/Chrome` +* [profile dir] `~/Library/Application Support/Google/Chrome/Default` +* [user cache dir] `~/Library/Caches/Google/Chrome/Default` + +On Linux, the user cache dir is derived from the profile dir as follows: + +1. Determine the system config dir. This is `~/.config`, unless overridden by + `$XDG_CONFIG_HOME`. (This step ignores `$CHROME_CONFIG_HOME`.) +2. Determine the system cache dir. This is `~/.cache`, unless overridden by + `$XDG_CACHE_HOME`. +3. If the system config dir is an ancestor of the profile dir, the user cache + dir is the system cache dir plus the relative path from the system config + dir to the profile dir. +4. Otherwise, the user cache dir is the same as the profile dir. + +Example (Linux): + +* [user data dir] `~/.config/google-chrome` +* [profile dir] `~/.config/google-chrome/Default` +* [user cache dir] `~/.cache/google-chrome/Default` + +On Android, the user cache directory comes from +[Context.getCacheDir](https://developer.android.com/reference/android/content/Context.html#getCacheDir%28%29).
diff --git a/google_apis/gaia/oauth2_api_call_flow.cc b/google_apis/gaia/oauth2_api_call_flow.cc index e3d40f0e..3292888 100644 --- a/google_apis/gaia/oauth2_api_call_flow.cc +++ b/google_apis/gaia/oauth2_api_call_flow.cc
@@ -79,8 +79,14 @@ const std::string& access_token) { std::string body = CreateApiCallBody(); net::URLFetcher::RequestType request_type = GetRequestTypeForBody(body); - std::unique_ptr<URLFetcher> result = - net::URLFetcher::Create(0, CreateApiCallUrl(), request_type, this); + net::NetworkTrafficAnnotationTag traffic_annotation = + CompleteNetworkTrafficAnnotation("oauth2_api_call_flow", + GetNetworkTrafficAnnotationTag(), R"( + policy { + cookies_allowed: false + })"); + std::unique_ptr<URLFetcher> result = net::URLFetcher::Create( + 0, CreateApiCallUrl(), request_type, this, traffic_annotation); gaia::MarkURLFetcherAsGaia(result.get()); result->SetRequestContext(context);
diff --git a/google_apis/gaia/oauth2_api_call_flow.h b/google_apis/gaia/oauth2_api_call_flow.h index 846a907..34cbbdba 100644 --- a/google_apis/gaia/oauth2_api_call_flow.h +++ b/google_apis/gaia/oauth2_api_call_flow.h
@@ -9,6 +9,7 @@ #include <string> #include "base/macros.h" +#include "net/traffic_annotation/network_traffic_annotation.h" #include "net/url_request/url_fetcher.h" #include "net/url_request/url_fetcher_delegate.h" #include "url/gurl.h" @@ -55,6 +56,9 @@ // Called when the API call failed. virtual void ProcessApiCallFailure(const net::URLFetcher* source) = 0; + virtual net::PartialNetworkTrafficAnnotationTag + GetNetworkTrafficAnnotationTag() = 0; + private: enum State { INITIAL,
diff --git a/google_apis/gaia/oauth2_api_call_flow_unittest.cc b/google_apis/gaia/oauth2_api_call_flow_unittest.cc index 61a7042..c95a14a 100644 --- a/google_apis/gaia/oauth2_api_call_flow_unittest.cc +++ b/google_apis/gaia/oauth2_api_call_flow_unittest.cc
@@ -98,6 +98,10 @@ void (const std::string& access_token)); MOCK_METHOD1(ProcessMintAccessTokenFailure, void (const GoogleServiceAuthError& error)); + + net::PartialNetworkTrafficAnnotationTag GetNetworkTrafficAnnotationTag() { + return PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS; + } }; } // namespace
diff --git a/google_apis/gaia/oauth2_mint_token_flow.cc b/google_apis/gaia/oauth2_mint_token_flow.cc index 69c241ce..6ffed50 100644 --- a/google_apis/gaia/oauth2_mint_token_flow.cc +++ b/google_apis/gaia/oauth2_mint_token_flow.cc
@@ -279,3 +279,31 @@ return success; } + +net::PartialNetworkTrafficAnnotationTag +OAuth2MintTokenFlow::GetNetworkTrafficAnnotationTag() { + return net::DefinePartialNetworkTrafficAnnotation( + "oauth2_mint_token_flow", "oauth2_api_call_flow", R"( + semantics { + sender: "Chrome Identity API" + description: + "Requests a token from gaia allowing an app or extension to act as " + "the user when calling other google APIs." + trigger: "API call from the app/extension." + data: + "User's login token, the identity of a chrome app/extension, and a " + "list of oauth scopes requested by the app/extension." + destination: GOOGLE_OWNED_SERVICE + } + policy { + setting: + "This feature cannot be disabled by settings, however the request is " + "made only for signed-in users." + chrome_policy { + SigninAllowed { + policy_options {mode: MANDATORY} + SigninAllowed: false + } + } + })"); +}
diff --git a/google_apis/gaia/oauth2_mint_token_flow.h b/google_apis/gaia/oauth2_mint_token_flow.h index ff597cc..d1f3ca5 100644 --- a/google_apis/gaia/oauth2_mint_token_flow.h +++ b/google_apis/gaia/oauth2_mint_token_flow.h
@@ -109,6 +109,8 @@ void ProcessApiCallSuccess(const net::URLFetcher* source) override; void ProcessApiCallFailure(const net::URLFetcher* source) override; + net::PartialNetworkTrafficAnnotationTag GetNetworkTrafficAnnotationTag() + override; private: friend class OAuth2MintTokenFlowTest;
diff --git a/gpu/command_buffer/service/context_state.cc b/gpu/command_buffer/service/context_state.cc index 640901ab..3c71d38 100644 --- a/gpu/command_buffer/service/context_state.cc +++ b/gpu/command_buffer/service/context_state.cc
@@ -285,12 +285,10 @@ const ContextState* prev_state) const { if (!feature_info_->IsES3Capable()) return; - CHECK_LT(unit, sampler_units.size()); const scoped_refptr<Sampler>& cur_sampler = sampler_units[unit]; GLuint cur_id = cur_sampler ? cur_sampler->service_id() : 0; GLuint prev_id = 0; if (prev_state) { - CHECK_LT(unit, prev_state->sampler_units.size()); const scoped_refptr<Sampler>& prev_sampler = prev_state->sampler_units[unit]; prev_id = prev_sampler ? prev_sampler->service_id() : 0;
diff --git a/gpu/config/gpu_info.cc b/gpu/config/gpu_info.cc index 14e030b..4285645 100644 --- a/gpu/config/gpu_info.cc +++ b/gpu/config/gpu_info.cc
@@ -135,6 +135,7 @@ bool passthrough_cmd_decoder; bool supports_overlays; bool hdr; + bool can_support_threaded_texture_mailbox; CollectInfoResult basic_info_state; CollectInfoResult context_info_state; #if defined(OS_WIN) @@ -195,6 +196,8 @@ enumerator->AddBool("passthroughCmdDecoder", passthrough_cmd_decoder); enumerator->AddBool("supportsOverlays", supports_overlays); enumerator->AddBool("hdr", hdr); + enumerator->AddBool("canSupportThreadedTextureMailbox", + can_support_threaded_texture_mailbox); enumerator->AddInt("basicInfoState", basic_info_state); enumerator->AddInt("contextInfoState", context_info_state); #if defined(OS_WIN)
diff --git a/gpu/config/gpu_info.h b/gpu/config/gpu_info.h index a72cca6..abc1272 100644 --- a/gpu/config/gpu_info.h +++ b/gpu/config/gpu_info.h
@@ -226,6 +226,11 @@ // True if the current set of outputs supports HDR. bool hdr = false; + // True only on android when extensions for threaded mailbox sharing are + // present. Threaded mailbox sharing is used on Android only, so this check + // is only implemented on Android. + bool can_support_threaded_texture_mailbox = false; + // The state of whether the basic/context/DxDiagnostics info is collected and // if the collection fails or not. CollectInfoResult basic_info_state;
diff --git a/gpu/config/gpu_info_collector_android.cc b/gpu/config/gpu_info_collector_android.cc index e17a32ac..17ac9c8 100644 --- a/gpu/config/gpu_info_collector_android.cc +++ b/gpu/config/gpu_info_collector_android.cc
@@ -206,6 +206,8 @@ gpu_info->gl_extensions = reinterpret_cast<const char*>(glGetStringFn(GL_EXTENSIONS)); + std::string egl_extensions = eglQueryStringFn(temp_display, EGL_EXTENSIONS); + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kGpuTestingGLVendor)) { gpu_info->gl_vendor = @@ -235,6 +237,12 @@ reinterpret_cast<GLint*>(&gpu_info->gl_reset_notification_strategy)); } + gpu_info->can_support_threaded_texture_mailbox = + egl_extensions.find("EGL_KHR_fence_sync") != std::string::npos && + egl_extensions.find("EGL_KHR_image_base") != std::string::npos && + egl_extensions.find("EGL_KHR_gl_texture_2D_image") != std::string::npos && + gpu_info->gl_extensions.find("GL_OES_EGL_image") != std::string::npos; + std::string glsl_version_string; if (const char* glsl_version_cstring = reinterpret_cast<const char*>( glGetStringFn(GL_SHADING_LANGUAGE_VERSION)))
diff --git a/gpu/ipc/common/gpu_info.mojom b/gpu/ipc/common/gpu_info.mojom index c734ae7..7d8feda 100644 --- a/gpu/ipc/common/gpu_info.mojom +++ b/gpu/ipc/common/gpu_info.mojom
@@ -108,6 +108,7 @@ bool passthrough_cmd_decoder; bool supports_overlays; bool hdr; + bool can_support_threaded_texture_mailbox; CollectInfoResult basic_info_state; CollectInfoResult context_info_state; CollectInfoResult dx_diagnostics_info_state;
diff --git a/gpu/ipc/common/gpu_info_struct_traits.cc b/gpu/ipc/common/gpu_info_struct_traits.cc index a458d30..b5e56cf 100644 --- a/gpu/ipc/common/gpu_info_struct_traits.cc +++ b/gpu/ipc/common/gpu_info_struct_traits.cc
@@ -247,6 +247,8 @@ out->passthrough_cmd_decoder = data.passthrough_cmd_decoder(); out->supports_overlays = data.supports_overlays(); out->hdr = data.hdr(); + out->can_support_threaded_texture_mailbox = + data.can_support_threaded_texture_mailbox(); out->process_crash_count = data.process_crash_count(); out->jpeg_decode_accelerator_supported = data.jpeg_decode_accelerator_supported();
diff --git a/gpu/ipc/common/gpu_info_struct_traits.h b/gpu/ipc/common/gpu_info_struct_traits.h index 11a770f..1e6bee1d 100644 --- a/gpu/ipc/common/gpu_info_struct_traits.h +++ b/gpu/ipc/common/gpu_info_struct_traits.h
@@ -246,6 +246,10 @@ static bool hdr(const gpu::GPUInfo& input) { return input.hdr; } + static bool can_support_threaded_texture_mailbox(const gpu::GPUInfo& input) { + return input.can_support_threaded_texture_mailbox; + } + static gpu::CollectInfoResult basic_info_state(const gpu::GPUInfo& input) { return input.basic_info_state; }
diff --git a/infra/config/cq.cfg b/infra/config/cq.cfg index 4fd031ab..3b46ddb 100644 --- a/infra/config/cq.cfg +++ b/infra/config/cq.cfg
@@ -72,10 +72,11 @@ } buckets { name: "master.tryserver.chromium.mac" - builders { name: "ios-device" } - builders { name: "ios-device-xcode-clang" } + # https://crbug.com/739556 + # builders { name: "ios-device" } + # builders { name: "ios-device-xcode-clang" } builders { name: "ios-simulator" } - builders { name: "ios-simulator-xcode-clang" } + # builders { name: "ios-simulator-xcode-clang" } builders { name: "mac_chromium_compile_dbg_ng" } builders { name: "mac_chromium_rel_ng" } }
diff --git a/ios/build/bots/tests/common_tests.json b/ios/build/bots/tests/common_tests.json index d720305..f0e18794 100644 --- a/ios/build/bots/tests/common_tests.json +++ b/ios/build/bots/tests/common_tests.json
@@ -16,9 +16,6 @@ "app": "ios_net_unittests" }, { - "app": "ios_web_view_inttests" - }, - { "app": "net_unittests" }, {
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index b08fc31..21a0542 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -151,6 +151,7 @@ "//components/keyed_service/core", "//components/keyed_service/ios", "//components/metrics", + "//components/ntp_snippets", "//components/prefs", "//components/proxy_config", "//components/signin/core/browser", @@ -184,6 +185,7 @@ "//ios/chrome/browser/metrics", "//ios/chrome/browser/metrics:metrics_internal", "//ios/chrome/browser/net", + "//ios/chrome/browser/ntp_snippets", "//ios/chrome/browser/omaha", "//ios/chrome/browser/prefs", "//ios/chrome/browser/reading_list",
diff --git a/ios/chrome/app/DEPS b/ios/chrome/app/DEPS index d9f00c2..cb09f05 100644 --- a/ios/chrome/app/DEPS +++ b/ios/chrome/app/DEPS
@@ -12,6 +12,7 @@ "+components/handoff", "+components/history/core/browser", "+components/metrics", + "+components/ntp_snippets", "+components/prefs", "+components/reading_list/core", "+components/signin/core/browser",
diff --git a/ios/chrome/app/application_delegate/BUILD.gn b/ios/chrome/app/application_delegate/BUILD.gn index 4d492a21..3e4ce4b3 100644 --- a/ios/chrome/app/application_delegate/BUILD.gn +++ b/ios/chrome/app/application_delegate/BUILD.gn
@@ -102,6 +102,7 @@ "//ios/chrome/app", "//ios/chrome/app/safe_mode", "//ios/chrome/app/spotlight", + "//ios/chrome/app/startup", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/crash_report",
diff --git a/ios/chrome/app/application_delegate/app_state.mm b/ios/chrome/app/application_delegate/app_state.mm index 2f55716..d1bed69 100644 --- a/ios/chrome/app/application_delegate/app_state.mm +++ b/ios/chrome/app/application_delegate/app_state.mm
@@ -23,6 +23,7 @@ #import "ios/chrome/app/main_application_delegate.h" #import "ios/chrome/app/safe_mode/safe_mode_coordinator.h" #import "ios/chrome/app/safe_mode_crashing_modules_config.h" +#import "ios/chrome/app/startup/content_suggestions_scheduler_notifications.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_constants.h" @@ -308,6 +309,9 @@ currentBrowserState]; } + [ContentSuggestionsSchedulerNotifications + notifyForeground:currentBrowserState]; + // If the current browser state is not OTR, check for cookie loss. if (currentBrowserState && !currentBrowserState->IsOffTheRecord() && currentBrowserState->GetOriginalChromeBrowserState()
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 11fe858b..1d9a7d8 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -46,6 +46,7 @@ #include "ios/chrome/app/startup/background_upload_alert.h" #include "ios/chrome/app/startup/chrome_main_starter.h" #include "ios/chrome/app/startup/client_registration.h" +#import "ios/chrome/app/startup/content_suggestions_scheduler_notifications.h" #include "ios/chrome/app/startup/ios_chrome_main.h" #include "ios/chrome/app/startup/network_stack_setup.h" #include "ios/chrome/app/startup/provider_registration.h" @@ -712,6 +713,12 @@ [self scheduleStartupCleanupTasks]; [MetricsMediator logLaunchMetricsWithStartupInformation:self browserViewInformation:_browserViewWrangler]; + if (self.isColdStart) { + [ContentSuggestionsSchedulerNotifications + notifyColdStart:_mainBrowserState]; + [ContentSuggestionsSchedulerNotifications + notifyForeground:_mainBrowserState]; + } [self scheduleLowPriorityStartupTasks]; @@ -1426,6 +1433,7 @@ } break; case IDC_PRELOAD_VOICE_SEARCH: + case IDC_SHOW_MAIL_COMPOSER: [self.currentBVC chromeExecuteCommand:sender]; break; case IDC_VOICE_SEARCH: {
diff --git a/ios/chrome/app/startup/BUILD.gn b/ios/chrome/app/startup/BUILD.gn index 6a6c485..bbd7bea 100644 --- a/ios/chrome/app/startup/BUILD.gn +++ b/ios/chrome/app/startup/BUILD.gn
@@ -38,6 +38,8 @@ "background_upload_alert.mm", "client_registration.h", "client_registration.mm", + "content_suggestions_scheduler_notifications.h", + "content_suggestions_scheduler_notifications.mm", "network_stack_setup.h", "network_stack_setup.mm", "provider_registration.h", @@ -49,8 +51,11 @@ deps = [ ":startup_basic", "//base", + "//components/ntp_snippets", "//ios/chrome/browser", "//ios/chrome/browser:browser_internal", + "//ios/chrome/browser/browser_state", + "//ios/chrome/browser/ntp_snippets", "//ios/chrome/browser/web", "//ios/chrome/browser/web:web_internal", "//ios/net",
diff --git a/ios/chrome/app/startup/content_suggestions_scheduler_notifications.h b/ios/chrome/app/startup/content_suggestions_scheduler_notifications.h new file mode 100644 index 0000000..a6e5eb2 --- /dev/null +++ b/ios/chrome/app/startup/content_suggestions_scheduler_notifications.h
@@ -0,0 +1,25 @@ +// 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_CHROME_APP_STARTUP_CONTENT_SUGGESTIONS_SCHEDULER_NOTIFICATIONS_H_ +#define IOS_CHROME_APP_STARTUP_CONTENT_SUGGESTIONS_SCHEDULER_NOTIFICATIONS_H_ + +#import <Foundation/Foundation.h> + +namespace ios { +class ChromeBrowserState; +} + +// Notify the scheduler of the Content Suggestions services of the app lifecycle +// events. +@interface ContentSuggestionsSchedulerNotifications : NSObject + +// Notifies that the application is launching from cold state. ++ (void)notifyColdStart:(ios::ChromeBrowserState*)browserState; +// Notifies that the application has been foregrounded. ++ (void)notifyForeground:(ios::ChromeBrowserState*)browserState; + +@end + +#endif // IOS_CHROME_APP_STARTUP_CONTENT_SUGGESTIONS_SCHEDULER_NOTIFICATIONS_H_
diff --git a/ios/chrome/app/startup/content_suggestions_scheduler_notifications.mm b/ios/chrome/app/startup/content_suggestions_scheduler_notifications.mm new file mode 100644 index 0000000..d82c975 --- /dev/null +++ b/ios/chrome/app/startup/content_suggestions_scheduler_notifications.mm
@@ -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. + +#import "ios/chrome/app/startup/content_suggestions_scheduler_notifications.h" + +#include "components/ntp_snippets/content_suggestions_service.h" +#include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#include "ios/chrome/browser/experimental_flags.h" +#include "ios/chrome/browser/ntp_snippets/ios_chrome_content_suggestions_service_factory.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@implementation ContentSuggestionsSchedulerNotifications + ++ (void)notifyColdStart:(ios::ChromeBrowserState*)browserState { + if (!experimental_flags::IsSuggestionsUIEnabled()) + return; + + ntp_snippets::ContentSuggestionsService* contentSuggestionsService = + IOSChromeContentSuggestionsServiceFactory::GetForBrowserState( + browserState); + contentSuggestionsService->remote_suggestions_scheduler() + ->OnBrowserColdStart(); +} + ++ (void)notifyForeground:(ios::ChromeBrowserState*)browserState { + if (!experimental_flags::IsSuggestionsUIEnabled()) + return; + + ntp_snippets::ContentSuggestionsService* contentSuggestionsService = + IOSChromeContentSuggestionsServiceFactory::GetForBrowserState( + browserState); + contentSuggestionsService->remote_suggestions_scheduler() + ->OnBrowserForegrounded(); +} + +@end
diff --git a/ios/chrome/app/strings/ios_strings.grd b/ios/chrome/app/strings/ios_strings.grd index 64310782..812312d3 100644 --- a/ios/chrome/app/strings/ios_strings.grd +++ b/ios/chrome/app/strings/ios_strings.grd
@@ -758,6 +758,9 @@ <message name="IDS_IOS_NEW_TAB_BOOKMARKS_PAGE_TITLE_MOBILE" desc="The 'Bookmarks' title on the new tab page [Length: 10em]"> Bookmarks </message> + <message name="IDS_IOS_NEW_TAB_HOME" desc="Title for the Home panel of the new tab page. [Length: 10em] [iOS only]"> + Home + </message> <message name="IDS_IOS_NEW_TAB_INCOGNITO" desc="Title for the Incognito panel of the new tab page."> Incognito </message>
diff --git a/ios/chrome/browser/DEPS b/ios/chrome/browser/DEPS index 640e4637..1921db05 100644 --- a/ios/chrome/browser/DEPS +++ b/ios/chrome/browser/DEPS
@@ -104,6 +104,7 @@ "+libxml/xmlwriter.h", "+net", "+rlz/features", + "+services/metrics", "+third_party/brotli", "+third_party/google_toolbox_for_mac", "+third_party/libaddressinput",
diff --git a/ios/chrome/browser/about_flags.mm b/ios/chrome/browser/about_flags.mm index 4f2bb8c..be8d405 100644 --- a/ios/chrome/browser/about_flags.mm +++ b/ios/chrome/browser/about_flags.mm
@@ -181,14 +181,6 @@ } } - // Populate command line flags from EnablePopularSites. - NSString* EnablePopularSites = [defaults stringForKey:@"EnablePopularSites"]; - if ([EnablePopularSites isEqualToString:@"Enabled"]) { - command_line->AppendSwitch(ntp_tiles::switches::kEnableNTPPopularSites); - } else if ([EnablePopularSites isEqualToString:@"Disabled"]) { - command_line->AppendSwitch(ntp_tiles::switches::kDisableNTPPopularSites); - } - // Set the UA flag if UseMobileSafariUA is enabled. if ([defaults boolForKey:@"UseMobileSafariUA"]) { // Safari uses "Vesion/", followed by the OS version excluding bugfix, where
diff --git a/ios/chrome/browser/application_context_impl.cc b/ios/chrome/browser/application_context_impl.cc index d07e863..1a3fa6a 100644 --- a/ios/chrome/browser/application_context_impl.cc +++ b/ios/chrome/browser/application_context_impl.cc
@@ -31,7 +31,6 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/translate/core/browser/translate_download_manager.h" -#include "components/ukm/public/ukm_recorder.h" #include "components/ukm/ukm_service.h" #include "components/update_client/configurator.h" #include "components/update_client/update_query_params.h" @@ -56,6 +55,7 @@ #include "net/log/net_log_capture_mode.h" #include "net/socket/client_socket_pool_manager.h" #include "net/url_request/url_request_context_getter.h" +#include "services/metrics/public/cpp/ukm_recorder.h" ApplicationContextImpl::ApplicationContextImpl( base::SequencedTaskRunner* local_state_task_runner, @@ -67,9 +67,7 @@ DCHECK(!GetApplicationContext()); SetApplicationContext(this); - net_log_.reset(new net_log::ChromeNetLog( - base::FilePath(), net::NetLogCaptureMode::Default(), - command_line.GetCommandLineString(), GetChannelString())); + net_log_.reset(new net_log::ChromeNetLog()); SetApplicationLocale(locale);
diff --git a/ios/chrome/browser/content_suggestions/BUILD.gn b/ios/chrome/browser/content_suggestions/BUILD.gn index 2a96b02..d913df6 100644 --- a/ios/chrome/browser/content_suggestions/BUILD.gn +++ b/ios/chrome/browser/content_suggestions/BUILD.gn
@@ -14,10 +14,10 @@ "content_suggestions_coordinator.mm", "content_suggestions_favicon_mediator.h", "content_suggestions_favicon_mediator.mm", - "content_suggestions_header_controller.h", - "content_suggestions_header_controller.mm", - "content_suggestions_header_controller_delegate.h", "content_suggestions_header_provider.h", + "content_suggestions_header_view_controller.h", + "content_suggestions_header_view_controller.mm", + "content_suggestions_header_view_controller_delegate.h", "content_suggestions_mediator.h", "content_suggestions_mediator.mm", "content_suggestions_service_bridge_observer.h",
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.h b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.h index 8d5f1d3..dc521ca 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.h +++ b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.h
@@ -12,7 +12,10 @@ class ChromeBrowserState; } -@class ContentSuggestionsHeaderController; +@protocol BrowserCommands; +@protocol ChromeExecuteCommand; +@class ContentSuggestionsHeaderViewController; +@protocol OmniboxFocuser; @protocol UrlLoader; class WebStateList; @@ -26,14 +29,16 @@ // URLLoader used to open pages. @property(nonatomic, weak) id<UrlLoader> URLLoader; @property(nonatomic, assign) WebStateList* webStateList; -@property(nonatomic, weak) id dispatcher; +@property(nonatomic, weak) + id<BrowserCommands, ChromeExecuteCommand, OmniboxFocuser, UrlLoader> + dispatcher; // Whether the Suggestions UI is displayed. If this is true, start is a no-op. @property(nonatomic, readonly) BOOL visible; @property(nonatomic, strong, readonly) - ContentSuggestionsHeaderController* headerController; + ContentSuggestionsHeaderViewController* headerController; -- (UIViewController*)viewController; +@property(nonatomic, strong, readonly) UIViewController* viewController; @end
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm index 69075e0..a61413a 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/content_suggestions/content_suggestions_coordinator.mm
@@ -18,8 +18,8 @@ #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/content_suggestions/content_suggestions_alert_commands.h" #import "ios/chrome/browser/content_suggestions/content_suggestions_alert_factory.h" -#import "ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h" -#import "ios/chrome/browser/content_suggestions/content_suggestions_header_controller_delegate.h" +#import "ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.h" +#import "ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller_delegate.h" #import "ios/chrome/browser/content_suggestions/content_suggestions_mediator.h" #include "ios/chrome/browser/favicon/ios_chrome_large_icon_service_factory.h" #import "ios/chrome/browser/metrics/new_tab_page_uma.h" @@ -28,6 +28,7 @@ #include "ios/chrome/browser/reading_list/reading_list_model_factory.h" #import "ios/chrome/browser/ui/alert_coordinator/alert_coordinator.h" #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/generic_chrome_command.h" #include "ios/chrome/browser/ui/commands/ios_command_ids.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_item.h" @@ -58,7 +59,7 @@ @interface ContentSuggestionsCoordinator ()< ContentSuggestionsAlertCommands, ContentSuggestionsCommands, - ContentSuggestionsHeaderControllerCommandHandler, + ContentSuggestionsHeaderViewControllerCommandHandler, ContentSuggestionsViewControllerAudience, ContentSuggestionsViewControllerDelegate, OverscrollActionsControllerDelegate> @@ -74,7 +75,7 @@ // Redefined as readwrite. @property(nonatomic, strong, readwrite) - ContentSuggestionsHeaderController* headerController; + ContentSuggestionsHeaderViewController* headerController; @end @@ -108,7 +109,7 @@ self.browserState); contentSuggestionsService->remote_suggestions_scheduler()->OnNTPOpened(); - self.headerController = [[ContentSuggestionsHeaderController alloc] init]; + self.headerController = [[ContentSuggestionsHeaderViewController alloc] init]; self.headerController.dispatcher = self.dispatcher; self.headerController.readingListModel = ReadingListModelFactory::GetForBrowserState(self.browserState); @@ -135,6 +136,10 @@ self.suggestionsViewController.audience = self; self.suggestionsViewController.overscrollDelegate = self; + [self.suggestionsViewController addChildViewController:self.headerController]; + [self.headerController + didMoveToParentViewController:self.suggestionsViewController]; + self.headerCollectionInteractionHandler = [[ContentSuggestionsHeaderSynchronizer alloc] initWithCollectionController:self.suggestionsViewController @@ -319,6 +324,13 @@ [self.delegate updateNtpBarShadowForPanelController:self]; } +- (void)promoShown { + NotificationPromoWhatsNew* notificationPromo = + [self.contentSuggestionsMediator notificationPromo]; + notificationPromo->HandleViewed(); + [self.headerController setPromoCanShow:notificationPromo->CanShow()]; +} + #pragma mark - OverscrollActionsControllerDelegate - (void)overscrollActionsController:(OverscrollActionsController*)controller @@ -330,9 +342,7 @@ [self.suggestionsViewController chromeExecuteCommand:command]; } break; case OverscrollAction::CLOSE_TAB: { - base::scoped_nsobject<GenericChromeCommand> command( - [[GenericChromeCommand alloc] initWithTag:IDC_CLOSE_TAB]); - [self.suggestionsViewController chromeExecuteCommand:command]; + [_dispatcher closeCurrentTab]; } break; case OverscrollAction::REFRESH: [self reload];
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.h similarity index 69% rename from ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h rename to ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.h index 5a9b881..1731b91 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h +++ b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.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 IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_H_ -#define IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_H_ +#ifndef IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_H_ +#define IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_H_ #import <UIKit/UIKit.h> @@ -14,8 +14,8 @@ #import "ios/public/provider/chrome/browser/voice/logo_animation_controller.h" @protocol ContentSuggestionsCollectionSynchronizing; -@protocol ContentSuggestionsHeaderControllerDelegate; -@protocol ContentSuggestionsHeaderControllerCommandHandler; +@protocol ContentSuggestionsHeaderViewControllerDelegate; +@protocol ContentSuggestionsHeaderViewControllerCommandHandler; @protocol OmniboxFocuser; @protocol UrlLoader; class ReadingListModel; @@ -23,18 +23,19 @@ // Controller for the header containing the logo and the fake omnibox, handling // the interactions between the header and the collection, and the rest of the // application. -@interface ContentSuggestionsHeaderController - : NSObject<ContentSuggestionsHeaderControlling, - ContentSuggestionsHeaderProvider, - GoogleLandingConsumer, - ToolbarOwner, - LogoAnimationControllerOwnerOwner> +@interface ContentSuggestionsHeaderViewController + : UIViewController<ContentSuggestionsHeaderControlling, + ContentSuggestionsHeaderProvider, + GoogleLandingConsumer, + ToolbarOwner, + LogoAnimationControllerOwnerOwner> @property(nonatomic, weak) id<UrlLoader, OmniboxFocuser> dispatcher; -@property(nonatomic, weak) id<ContentSuggestionsHeaderControllerDelegate> +@property(nonatomic, weak) id<ContentSuggestionsHeaderViewControllerDelegate> delegate; -@property(nonatomic, weak) id<ContentSuggestionsHeaderControllerCommandHandler> - commandHandler; +@property(nonatomic, weak) + id<ContentSuggestionsHeaderViewControllerCommandHandler> + commandHandler; @property(nonatomic, weak) id<ContentSuggestionsCollectionSynchronizing> collectionSynchronizer; @property(nonatomic, assign) ReadingListModel* readingListModel; @@ -51,4 +52,4 @@ @end -#endif // IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_H_ +#endif // IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller.mm b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.mm similarity index 95% rename from ios/chrome/browser/content_suggestions/content_suggestions_header_controller.mm rename to ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.mm index 750344e3f..00864a6 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller.mm +++ b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.mm
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h" +#import "ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.h" #include "base/logging.h" #include "base/metrics/user_metrics.h" #include "components/strings/grit/components_strings.h" -#import "ios/chrome/browser/content_suggestions/content_suggestions_header_controller_delegate.h" +#import "ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller_delegate.h" #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h" #import "ios/chrome/browser/ui/commands/generic_chrome_command.h" #include "ios/chrome/browser/ui/commands/ios_command_ids.h" @@ -30,7 +30,7 @@ const CGFloat kHintLabelSidePadding = 12; } // namespace -@interface ContentSuggestionsHeaderController () +@interface ContentSuggestionsHeaderViewController () // |YES| when notifications indicate the omnibox is focused. @property(nonatomic, assign, getter=isOmniboxFocused, readwrite) @@ -76,7 +76,7 @@ @end -@implementation ContentSuggestionsHeaderController +@implementation ContentSuggestionsHeaderViewController @synthesize dispatcher = _dispatcher; @synthesize delegate = _delegate; @@ -256,9 +256,16 @@ } // If Google is not the default search engine, hide the logo, doodle and -// fakebox. +// fakebox. Make them appear if Google is set as default. - (void)updateLogoAndFakeboxDisplay { - // TODO(crbug.com/700375): implement this. + if (self.logoVendor.showingLogo != self.logoIsShowing) { + self.logoVendor.showingLogo = self.logoIsShowing; + [self.doodleHeightConstraint + setConstant:content_suggestions::doodleHeight(self.logoIsShowing)]; + if (IsIPadIdiom()) + [self.fakeOmnibox setHidden:!self.logoIsShowing]; + [self.collectionSynchronizer invalidateLayout]; + } } // Adds the constraints for the |logoView|, the |fakeomnibox| related to the
diff --git a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller_delegate.h b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller_delegate.h similarity index 72% rename from ios/chrome/browser/content_suggestions/content_suggestions_header_controller_delegate.h rename to ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller_delegate.h index ea70373..38e17d8e 100644 --- a/ios/chrome/browser/content_suggestions/content_suggestions_header_controller_delegate.h +++ b/ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller_delegate.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_DELEGATE_H_ -#define IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_DELEGATE_H_ +#ifndef IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_DELEGATE_H_ +#define IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_DELEGATE_H_ #import <UIKit/UIKit.h> // TODO(crbug.com/700375): Implement this protocol somewhere. -@protocol ContentSuggestionsHeaderControllerDelegate +@protocol ContentSuggestionsHeaderViewControllerDelegate - (BOOL)isContextMenuVisible; - (BOOL)isScrolledToTop; @@ -16,11 +16,11 @@ @end // Commands protocol for the header controller. -@protocol ContentSuggestionsHeaderControllerCommandHandler +@protocol ContentSuggestionsHeaderViewControllerCommandHandler // Dismisses all presented modals. - (void)dismissModals; @end -#endif // IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_CONTROLLER_DELEGATE_H_ +#endif // IOS_CHROME_BROWSER_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_HEADER_VIEW_CONTROLLER_DELEGATE_H_
diff --git a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm index 5ae210d4..b3900d3 100644 --- a/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm +++ b/ios/chrome/browser/passwords/ios_chrome_password_manager_client.mm
@@ -14,13 +14,13 @@ #include "components/password_manager/core/browser/password_manager_util.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/signin/core/browser/signin_manager_base.h" -#include "components/ukm/public/ukm_recorder.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h" #include "ios/chrome/browser/signin/signin_manager_factory.h" #include "ios/chrome/browser/sync/ios_chrome_profile_sync_service_factory.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "url/gurl.h" #if !defined(__has_feature) || !__has_feature(objc_arc)
diff --git a/ios/chrome/browser/payments/payment_request.h b/ios/chrome/browser/payments/payment_request.h index 52a58db..bd1b74a 100644 --- a/ios/chrome/browser/payments/payment_request.h +++ b/ios/chrome/browser/payments/payment_request.h
@@ -12,6 +12,7 @@ #include <vector> #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "components/autofill/core/browser/credit_card.h" #include "components/payments/core/payment_options_provider.h" #include "components/payments/core/payment_request_base_delegate.h" @@ -28,6 +29,8 @@ class AddressNormalizer; class AddressNormalizerImpl; class CurrencyFormatter; +class PaymentInstrument; +class AutofillPaymentInstrument; } // namespace payments namespace ios { @@ -39,17 +42,23 @@ // initiating UI to request full card details for payment. @protocol PaymentRequestUIDelegate<NSObject> -- (void)openFullCardRequestUI; +- (void) +requestFullCreditCard:(const autofill::CreditCard&)creditCard + resultDelegate: + (base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>) + resultDelegate; @end +namespace payments { + // Has a copy of web::PaymentRequest as provided by the page invoking the // PaymentRequest API. Also caches credit cards and addresses provided by the // |personal_data_manager| and manages shared resources and user selections for // the current PaymentRequest flow. It must be initialized with a non-null // instance of |personal_data_manager| that outlives this class. -class PaymentRequest : public payments::PaymentOptionsProvider, - public payments::PaymentRequestBaseDelegate { +class PaymentRequest : public PaymentOptionsProvider, + public PaymentRequestBaseDelegate { public: // |personal_data_manager| should not be null and should outlive this object. PaymentRequest(const web::PaymentRequest& web_payment_request, @@ -68,7 +77,7 @@ const autofill::CreditCard& credit_card, base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate> result_delegate) override; - payments::AddressNormalizer* GetAddressNormalizer() override; + AddressNormalizer* GetAddressNormalizer() override; autofill::RegionDataLoader* GetRegionDataLoader() override; ukm::UkmRecorder* GetUkmRecorder() override; std::string GetAuthenticatedEmail() const override; @@ -94,12 +103,12 @@ bool request_payer_name() const override; bool request_payer_phone() const override; bool request_payer_email() const override; - payments::PaymentShippingType shipping_type() const override; + PaymentShippingType shipping_type() const override; // Returns the payments::CurrencyFormatter instance for this PaymentRequest. // Note: Having multiple currencies per PaymentRequest flow is not supported; // hence the CurrencyFormatter is cached here. - payments::CurrencyFormatter* GetOrCreateCurrencyFormatter(); + CurrencyFormatter* GetOrCreateCurrencyFormatter(); // Adds |profile| to the list of cached profiles, updates the list of // available shipping and contact profiles, and returns a reference to the @@ -151,10 +160,6 @@ return supported_card_networks_; } - const std::set<std::string>& basic_card_specified_networks() const { - return basic_card_specified_networks_; - } - const std::map<std::string, std::set<std::string>>& stringified_method_data() const { return stringified_method_data_; @@ -165,27 +170,26 @@ return supported_card_types_set_; } - // Adds |credit_card| to the list of cached credit cards, updates the list of - // available credit cards, and returns a reference to the cached copy of + // Creates and adds an AutofillPaymentInstrument, which makes a copy of // |credit_card|. - virtual autofill::CreditCard* AddCreditCard( + virtual AutofillPaymentInstrument* AddAutofillPaymentInstrument( const autofill::CreditCard& credit_card); - // Returns the available autofill credit cards for this user that match a - // supported type specified in |web_payment_request_|. - const std::vector<autofill::CreditCard*>& credit_cards() const { - return credit_cards_; + // Returns the available payment methods for this user that match a supported + // type specified in |web_payment_request_|. + const std::vector<PaymentInstrument*>& payment_methods() const { + return payment_methods_; } - // Returns the currently selected credit card for this PaymentRequest flow if - // there is one. Returns nullptr if there is no selected credit card. - autofill::CreditCard* selected_credit_card() const { - return selected_credit_card_; + // Returns the currently selected payment method for this PaymentRequest flow + // if there is one. Returns nullptr if there is no selected payment method. + PaymentInstrument* selected_payment_method() const { + return selected_payment_method_; } - // Sets the currently selected credit card for this PaymentRequest flow. - void set_selected_credit_card(autofill::CreditCard* credit_card) { - selected_credit_card_ = credit_card; + // Sets the currently selected payment method for this PaymentRequest flow. + void set_selected_payment_method(PaymentInstrument* payment_method) { + selected_payment_method_ = payment_method; } // Returns the available shipping options from |web_payment_request_|. @@ -199,7 +203,7 @@ return selected_shipping_option_; } - virtual payments::PaymentsProfileComparator* profile_comparator(); + virtual PaymentsProfileComparator* profile_comparator(); // Returns whether the current PaymentRequest can be used to make a payment. bool CanMakePayment() const; @@ -216,14 +220,14 @@ // cached profiles ordered by completeness. void PopulateAvailableProfiles(); - // Fetches the autofill credit cards for this user from the - // PersonalDataManager that match a supported type specified in - // |web_payment_request_| and stores copies of them, owned by this - // PaymentRequest, in credit_card_cache_. - void PopulateCreditCardCache(); + // Fetches the payment methods for this user that match a supported type + // specified in |web_payment_request_| and stores copies of them, owned + // by this PaymentRequest, in payment_method_cache_. + void PopulatePaymentMethodCache(); - // Sets the available credit cards as references to the cached credit cards. - void PopulateAvailableCreditCards(); + // Sets the available payment methods as references to the cached payment + // methods. + void PopulateAvailablePaymentMethods(); // Sets the available shipping options as references to the shipping options // in |web_payment_request_|. @@ -247,10 +251,10 @@ __weak id<PaymentRequestUIDelegate> payment_request_ui_delegate_; // The address normalizer to use for the duration of the Payment Request. - payments::AddressNormalizerImpl* address_normalizer_; + AddressNormalizerImpl* address_normalizer_; // The currency formatter instance for this PaymentRequest flow. - std::unique_ptr<payments::CurrencyFormatter> currency_formatter_; + std::unique_ptr<CurrencyFormatter> currency_formatter_; // Profiles returned by the Data Manager may change due to (e.g.) sync events, // meaning PaymentRequest may outlive them. Therefore, profiles are fetched @@ -264,14 +268,15 @@ std::vector<autofill::AutofillProfile*> contact_profiles_; autofill::AutofillProfile* selected_contact_profile_; - // Credit cards returnd by the Data Manager may change due to (e.g.) - // sync events, meaning PaymentRequest may outlive them. Therefore, credit - // cards are fetched once and their copies are cached here. Whenever credit - // cards are requested a vector of pointers to these copies are returned. - std::vector<std::unique_ptr<autofill::CreditCard>> credit_card_cache_; + // Some payment methods, such as credit cards returned by the Data Manager, + // may change due to (e.g.) sync events, meaning PaymentRequest may outlive + // them. Therefore, payment methods are fetched once and their copies are + // cached here. Whenever payment methods are requested a vector of pointers to + // these copies are returned. + std::vector<std::unique_ptr<PaymentInstrument>> payment_method_cache_; - std::vector<autofill::CreditCard*> credit_cards_; - autofill::CreditCard* selected_credit_card_; + std::vector<PaymentInstrument*> payment_methods_; + PaymentInstrument* selected_payment_method_; // A vector of supported basic card networks. This encompasses everything that // the merchant supports and should be used for support checks. @@ -292,9 +297,11 @@ std::vector<web::PaymentShippingOption*> shipping_options_; web::PaymentShippingOption* selected_shipping_option_; - payments::PaymentsProfileComparator profile_comparator_; + PaymentsProfileComparator profile_comparator_; DISALLOW_COPY_AND_ASSIGN(PaymentRequest); }; +} // namespace payments + #endif // IOS_CHROME_BROWSER_PAYMENTS_PAYMENT_REQUEST_H_
diff --git a/ios/chrome/browser/payments/payment_request.mm b/ios/chrome/browser/payments/payment_request.mm index 091c41c..f3b5aba 100644 --- a/ios/chrome/browser/payments/payment_request.mm +++ b/ios/chrome/browser/payments/payment_request.mm
@@ -16,7 +16,9 @@ #include "components/autofill/core/browser/region_data_loader_impl.h" #include "components/autofill/core/browser/validation.h" #include "components/payments/core/address_normalizer_impl.h" +#include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/currency_formatter.h" +#include "components/payments/core/payment_instrument.h" #include "components/payments/core/payment_request_data_util.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_manager.h" @@ -49,6 +51,8 @@ } // namespace +namespace payments { + PaymentRequest::PaymentRequest( const web::PaymentRequest& web_payment_request, ios::ChromeBrowserState* browser_state, @@ -58,21 +62,21 @@ browser_state_(browser_state), personal_data_manager_(personal_data_manager), payment_request_ui_delegate_(payment_request_ui_delegate), - address_normalizer_(new payments::AddressNormalizerImpl( + address_normalizer_(new AddressNormalizerImpl( GetAddressInputSource( personal_data_manager_->GetURLRequestContextGetter()), GetAddressInputStorage())), selected_shipping_profile_(nullptr), selected_contact_profile_(nullptr), - selected_credit_card_(nullptr), + selected_payment_method_(nullptr), selected_shipping_option_(nullptr), profile_comparator_(GetApplicationContext()->GetApplicationLocale(), *this) { PopulateAvailableShippingOptions(); PopulateProfileCache(); PopulateAvailableProfiles(); - PopulateCreditCardCache(); - PopulateAvailableCreditCards(); + PopulatePaymentMethodCache(); + PopulateAvailablePaymentMethods(); SetSelectedShippingOption(); @@ -94,17 +98,15 @@ } } - // TODO(crbug.com/702063): Change this code to prioritize credit cards by use - // count and other means. - auto first_complete_credit_card = std::find_if( - credit_cards_.begin(), credit_cards_.end(), - [this](const autofill::CreditCard* credit_card) { - DCHECK(credit_card); - return payment_request_util::IsCreditCardCompleteForPayment( - *credit_card, billing_profiles()); - }); - if (first_complete_credit_card != credit_cards_.end()) - selected_credit_card_ = *first_complete_credit_card; + // TODO(crbug.com/702063): Change this code to prioritize payment methods by + // use count and other means. + auto first_complete_payment_method = + std::find_if(payment_methods_.begin(), payment_methods_.end(), + [this](PaymentInstrument* payment_method) { + return payment_method->IsCompleteForPayment(); + }); + if (first_complete_payment_method != payment_methods_.end()) + selected_payment_method_ = *first_complete_payment_method; } PaymentRequest::~PaymentRequest() {} @@ -135,13 +137,11 @@ const autofill::CreditCard& credit_card, base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate> result_delegate) { - // TODO: In the follow-up CL openFullCardRequestUI will take in arguments, - // specifically the |result_delegate| to be used in the - // |payment_request_ui_delegate_| object. - [payment_request_ui_delegate_ openFullCardRequestUI]; + [payment_request_ui_delegate_ requestFullCreditCard:credit_card + resultDelegate:result_delegate]; } -payments::AddressNormalizer* PaymentRequest::GetAddressNormalizer() { +AddressNormalizer* PaymentRequest::GetAddressNormalizer() { return address_normalizer_; } @@ -193,13 +193,13 @@ return web_payment_request_.options.request_payer_email; } -payments::PaymentShippingType PaymentRequest::shipping_type() const { +PaymentShippingType PaymentRequest::shipping_type() const { return web_payment_request_.options.shipping_type; } -payments::CurrencyFormatter* PaymentRequest::GetOrCreateCurrencyFormatter() { +CurrencyFormatter* PaymentRequest::GetOrCreateCurrencyFormatter() { if (!currency_formatter_) { - currency_formatter_.reset(new payments::CurrencyFormatter( + currency_formatter_.reset(new CurrencyFormatter( base::UTF16ToASCII(web_payment_request_.details.total.amount.currency), base::UTF16ToASCII( web_payment_request_.details.total.amount.currency_system), @@ -253,32 +253,58 @@ profile_comparator_.FilterProfilesForShipping(raw_profiles_for_filtering); } -autofill::CreditCard* PaymentRequest::AddCreditCard( +AutofillPaymentInstrument* PaymentRequest::AddAutofillPaymentInstrument( const autofill::CreditCard& credit_card) { - credit_card_cache_.push_back( - base::MakeUnique<autofill::CreditCard>(credit_card)); + std::string basic_card_issuer_network = + autofill::data_util::GetPaymentRequestData(credit_card.network()) + .basic_card_issuer_network; - PopulateAvailableCreditCards(); + if (!base::ContainsValue(supported_card_networks_, + basic_card_issuer_network) || + !supported_card_types_set_.count(credit_card.card_type())) { + return nullptr; + } - return credit_card_cache_.back().get(); + // If the merchant specified the card network as part of the "basic-card" + // payment method, use "basic-card" as the method_name. Otherwise, use + // the name of the network directly. + std::string method_name = basic_card_issuer_network; + if (basic_card_specified_networks_.count(basic_card_issuer_network)) { + method_name = "basic_card"; + } + + // The total number of card types: credit, debit, prepaid, unknown. + constexpr size_t kTotalNumberOfCardTypes = 4U; + + // Whether the card type (credit, debit, prepaid) matches the type that the + // merchant has requested exactly. This should be false for unknown card + // types, if the merchant cannot accept some card types. + bool matches_merchant_card_type_exactly = + credit_card.card_type() != autofill::CreditCard::CARD_TYPE_UNKNOWN || + supported_card_types_set_.size() == kTotalNumberOfCardTypes; + + // AutofillPaymentInstrument makes a copy of |credit_card| so it is + // effectively owned by this object. + payment_method_cache_.push_back(base::MakeUnique<AutofillPaymentInstrument>( + method_name, credit_card, matches_merchant_card_type_exactly, + billing_profiles(), GetApplicationContext()->GetApplicationLocale(), + this)); + + PopulateAvailablePaymentMethods(); + + return static_cast<AutofillPaymentInstrument*>( + payment_method_cache_.back().get()); } -payments::PaymentsProfileComparator* PaymentRequest::profile_comparator() { +PaymentsProfileComparator* PaymentRequest::profile_comparator() { return &profile_comparator_; } bool PaymentRequest::CanMakePayment() const { - for (const autofill::CreditCard* credit_card : credit_cards_) { - DCHECK(credit_card); - autofill::CreditCardCompletionStatus status = - autofill::GetCompletionStatusForCard( - *credit_card, GetApplicationContext()->GetApplicationLocale(), - billing_profiles()); - // A card only has to have a cardholder name and a number for the purposes - // of CanMakePayment. An expired card or one without a billing address is - // valid for this purpose. - return !(status & autofill::CREDIT_CARD_NO_CARDHOLDER || - status & autofill::CREDIT_CARD_NO_NUMBER); + for (PaymentInstrument* payment_method : payment_methods_) { + if (payment_method->IsValidForCanMakePayment()) { + return true; + } } return false; } @@ -299,12 +325,11 @@ } } - DCHECK(selected_credit_card_); - personal_data_manager_->RecordUseOf(*selected_credit_card_); + selected_payment_method_->RecordUse(); } -void PaymentRequest::PopulateCreditCardCache() { - for (const payments::PaymentMethodData& method_data_entry : +void PaymentRequest::PopulatePaymentMethodCache() { + for (const PaymentMethodData& method_data_entry : web_payment_request_.method_data) { for (const std::string& method : method_data_entry.supported_methods) { stringified_method_data_[method].insert(method_data_entry.data); @@ -312,12 +337,12 @@ } // TODO(crbug.com/709036): Validate method data. - payments::data_util::ParseBasicCardSupportedNetworks( - web_payment_request_.method_data, &supported_card_networks_, - &basic_card_specified_networks_); + data_util::ParseBasicCardSupportedNetworks(web_payment_request_.method_data, + &supported_card_networks_, + &basic_card_specified_networks_); - payments::data_util::ParseSupportedCardTypes(web_payment_request_.method_data, - &supported_card_types_set_); + data_util::ParseSupportedCardTypes(web_payment_request_.method_data, + &supported_card_types_set_); const std::vector<autofill::CreditCard*>& credit_cards_to_suggest = personal_data_manager_->GetCreditCardsToSuggest(); @@ -325,30 +350,25 @@ if (credit_cards_to_suggest.empty()) return; - credit_card_cache_.reserve(credit_cards_to_suggest.size()); + // TODO(crbug.com/602666): Determine number of possible payments so + // that we can appropriate reserve space in the following vector. - for (const auto* credit_card : credit_cards_to_suggest) { - std::string spec_issuer_network = - autofill::data_util::GetPaymentRequestData(credit_card->network()) - .basic_card_issuer_network; - if (base::ContainsValue(supported_card_networks_, spec_issuer_network)) { - credit_card_cache_.push_back( - base::MakeUnique<autofill::CreditCard>(*credit_card)); - } - } + payment_method_cache_.reserve(credit_cards_to_suggest.size()); + + for (const auto* credit_card : credit_cards_to_suggest) + AddAutofillPaymentInstrument(*credit_card); } -void PaymentRequest::PopulateAvailableCreditCards() { - if (credit_card_cache_.empty()) +void PaymentRequest::PopulateAvailablePaymentMethods() { + if (payment_method_cache_.empty()) return; - credit_cards_.clear(); - credit_cards_.reserve(credit_card_cache_.size()); + payment_methods_.clear(); + payment_methods_.reserve(payment_method_cache_.size()); - // TODO(crbug.com/602666): Implement prioritization rules for credit cards. - for (auto const& credit_card : credit_card_cache_) { - credit_cards_.push_back(credit_card.get()); - } + // TODO(crbug.com/602666): Implement prioritization rules for payment methods. + for (auto const& payment_method : payment_method_cache_) + payment_methods_.push_back(payment_method.get()); } void PaymentRequest::PopulateAvailableShippingOptions() { @@ -375,3 +395,5 @@ } } } + +} // namespace payments
diff --git a/ios/chrome/browser/payments/payment_request_unittest.mm b/ios/chrome/browser/payments/payment_request_unittest.mm index b6383c6..61e584b 100644 --- a/ios/chrome/browser/payments/payment_request_unittest.mm +++ b/ios/chrome/browser/payments/payment_request_unittest.mm
@@ -10,6 +10,7 @@ #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/currency_formatter.h" #include "components/payments/core/payment_method_data.h" #include "ios/chrome/browser/application_context.h" @@ -38,6 +39,8 @@ } // namespace +namespace payments { + class PaymentRequestTest : public testing::Test { protected: // Returns PaymentDetails with one shipping option that's selected. @@ -79,7 +82,7 @@ web_payment_request.details.total.amount.currency = base::ASCIIToUTF16("USD"); TestPaymentRequest payment_request1(web_payment_request, &personal_data_manager); - payments::CurrencyFormatter* currency_formatter = + CurrencyFormatter* currency_formatter = payment_request1.GetOrCreateCurrencyFormatter(); EXPECT_EQ(base::UTF8ToUTF16("$55.00"), currency_formatter->Format("55.00")); EXPECT_EQ("USD", currency_formatter->formatted_currency_code()); @@ -106,10 +109,10 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("visa"); web_payment_request.method_data.push_back(method_datum1); - payments::PaymentMethodData method_datum2; + PaymentMethodData method_datum2; method_datum2.supported_methods.push_back("mastercard"); web_payment_request.method_data.push_back(method_datum2); @@ -126,7 +129,7 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("visa"); method_datum1.supported_methods.push_back("mastercard"); method_datum1.supported_methods.push_back("invalid"); @@ -147,16 +150,16 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("visa"); web_payment_request.method_data.push_back(method_datum1); - payments::PaymentMethodData method_datum2; + PaymentMethodData method_datum2; method_datum2.supported_methods.push_back("mastercard"); web_payment_request.method_data.push_back(method_datum2); - payments::PaymentMethodData method_datum3; + PaymentMethodData method_datum3; method_datum3.supported_methods.push_back(""); web_payment_request.method_data.push_back(method_datum3); - payments::PaymentMethodData method_datum4; + PaymentMethodData method_datum4; method_datum4.supported_methods.push_back("visa"); web_payment_request.method_data.push_back(method_datum4); @@ -172,7 +175,7 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("basic-card"); web_payment_request.method_data.push_back(method_datum1); @@ -197,7 +200,7 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("jcb"); method_datum1.supported_methods.push_back("basic-card"); web_payment_request.method_data.push_back(method_datum1); @@ -224,11 +227,11 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("mastercard"); method_datum1.supported_methods.push_back("visa"); web_payment_request.method_data.push_back(method_datum1); - payments::PaymentMethodData method_datum2; + PaymentMethodData method_datum2; method_datum2.supported_methods.push_back("basic-card"); method_datum2.supported_networks.push_back("visa"); method_datum2.supported_networks.push_back("mastercard"); @@ -250,7 +253,7 @@ web::PaymentRequest web_payment_request; autofill::TestPersonalDataManager personal_data_manager; - payments::PaymentMethodData method_datum1; + PaymentMethodData method_datum1; method_datum1.supported_methods.push_back("basic-card"); method_datum1.supported_networks.push_back("visa"); method_datum1.supported_networks.push_back("unionpay"); @@ -265,10 +268,11 @@ EXPECT_EQ("unionpay", payment_request.supported_card_networks()[1]); } -// Tests that a credit card can be added to the list of available credit cards. -TEST_F(PaymentRequestTest, AddCreditCard) { +// Tests that an autofill payment instrumnt e.g., credit cards can be added +// to the list of available payment methods. +TEST_F(PaymentRequestTest, AddAutofillPaymentInstrument) { web::PaymentRequest web_payment_request; - payments::PaymentMethodData method_datum; + PaymentMethodData method_datum; method_datum.supported_methods.push_back("basic-card"); method_datum.supported_networks.push_back("visa"); method_datum.supported_networks.push_back("amex"); @@ -281,14 +285,14 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); - EXPECT_EQ(1U, payment_request.credit_cards().size()); + EXPECT_EQ(1U, payment_request.payment_methods().size()); autofill::CreditCard credit_card_2 = autofill::test::GetCreditCard2(); - autofill::CreditCard* added_credit_card = - payment_request.AddCreditCard(credit_card_2); + AutofillPaymentInstrument* added_credit_card = + payment_request.AddAutofillPaymentInstrument(credit_card_2); - EXPECT_EQ(2U, payment_request.credit_cards().size()); - EXPECT_EQ(credit_card_2, *added_credit_card); + EXPECT_EQ(2U, payment_request.payment_methods().size()); + EXPECT_EQ(credit_card_2, *added_credit_card->credit_card()); } // Tests that a profile can be added to the list of available profiles. @@ -491,7 +495,7 @@ // No payment methods are selected because none are available! TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); - EXPECT_EQ(nullptr, payment_request.selected_credit_card()); + EXPECT_EQ(nullptr, payment_request.selected_payment_method()); } // Test that loading expired credit cards works as expected. @@ -510,7 +514,12 @@ // credit_card is selected because expired cards are valid for payment. TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(payment_request.selected_payment_method()->type(), + PaymentInstrument::Type::AUTOFILL); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); } // Test that loading complete payment methods works as expected. @@ -534,8 +543,10 @@ // model). TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); - EXPECT_EQ(credit_card2.guid(), - payment_request.selected_credit_card()->guid()); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); + EXPECT_EQ(credit_card2.guid(), payment_instrument->credit_card()->guid()); } // Test that loading incomplete payment methods works as expected. @@ -558,7 +569,10 @@ // because it is complete. TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); } // Test that the use counts of the data models are updated as expected when @@ -585,11 +599,14 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); EXPECT_EQ(address.guid(), payment_request.selected_shipping_profile()->guid()); EXPECT_EQ(contact_info.guid(), payment_request.selected_contact_profile()->guid()); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); EXPECT_CALL(personal_data_manager, RecordUseOf(GuidMatches(address.guid()))) .Times(1); @@ -618,10 +635,13 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); EXPECT_EQ(address.guid(), payment_request.selected_shipping_profile()->guid()); EXPECT_EQ(address.guid(), payment_request.selected_contact_profile()->guid()); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); // Even though |address| is used for contact info, shipping address, and // credit_card's billing address, the stats should be updated only once. @@ -652,10 +672,13 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); EXPECT_EQ(address.guid(), payment_request.selected_shipping_profile()->guid()); EXPECT_EQ(nullptr, payment_request.selected_contact_profile()); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); EXPECT_CALL(personal_data_manager, RecordUseOf(GuidMatches(address.guid()))) .Times(1); @@ -682,9 +705,12 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); EXPECT_EQ(nullptr, payment_request.selected_shipping_profile()); EXPECT_EQ(address.guid(), payment_request.selected_contact_profile()->guid()); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); EXPECT_CALL(personal_data_manager, RecordUseOf(GuidMatches(address.guid()))) .Times(1); @@ -714,9 +740,12 @@ TestPaymentRequest payment_request(web_payment_request, &personal_data_manager); + AutofillPaymentInstrument* payment_instrument = + static_cast<AutofillPaymentInstrument*>( + payment_request.selected_payment_method()); EXPECT_EQ(nullptr, payment_request.selected_shipping_profile()); EXPECT_EQ(nullptr, payment_request.selected_contact_profile()); - EXPECT_EQ(credit_card.guid(), payment_request.selected_credit_card()->guid()); + EXPECT_EQ(credit_card.guid(), payment_instrument->credit_card()->guid()); EXPECT_CALL(personal_data_manager, RecordUseOf(GuidMatches(address.guid()))) .Times(0); @@ -726,3 +755,5 @@ payment_request.RecordUseStats(); } + +} // namespace payments
diff --git a/ios/chrome/browser/payments/payment_request_util.h b/ios/chrome/browser/payments/payment_request_util.h index 3bbb6d6..5a054a1 100644 --- a/ios/chrome/browser/payments/payment_request_util.h +++ b/ios/chrome/browser/payments/payment_request_util.h
@@ -14,10 +14,12 @@ namespace autofill { class AutofillProfile; -class CreditCard; } // namespace autofill +namespace payments { +class PaymentInstrument; class PaymentRequest; +} // namespace payments namespace payment_request_util { @@ -49,19 +51,13 @@ // Helper function to create a notification label for an address cell from an // autofill profile. Returns nil if the resulting label is empty. NSString* GetAddressNotificationLabelFromAutofillProfile( - PaymentRequest& payment_request, + payments::PaymentRequest& payment_request, const autofill::AutofillProfile& profile); -// Returns whether the credit card is complete to be used as a payment method -// without further editing. -BOOL IsCreditCardCompleteForPayment( - const autofill::CreditCard& credit_card, - const std::vector<autofill::AutofillProfile*>& billing_profiles); - // Helper function to create a notification label for what's missing from a -// credit card. Returns nil if the resulting label is empty. -NSString* GetPaymentMethodNotificationLabelFromCreditCard( - const autofill::CreditCard& credit_card, +// payment method. Returns nil if the resulting label is empty. +NSString* GetPaymentMethodNotificationLabelFromPaymentMethod( + payments::PaymentInstrument& payment_method, const std::vector<autofill::AutofillProfile*>& billing_profiles); // Returns the title for the shipping section of the payment summary view given @@ -71,12 +67,12 @@ // Returns the error message to be displayed in the shipping address selection // view given the shipping type specified in |payment_request|. NSString* GetShippingAddressSelectorErrorMessage( - const PaymentRequest& payment_request); + const payments::PaymentRequest& payment_request); // Returns the error message to be displayed in the shipping option selection // view given the shipping type specified in |payment_request|. NSString* GetShippingOptionSelectorErrorMessage( - const PaymentRequest& payment_request); + const payments::PaymentRequest& payment_request); } // namespace payment_request_util
diff --git a/ios/chrome/browser/payments/payment_request_util.mm b/ios/chrome/browser/payments/payment_request_util.mm index 0759516..b272ae4 100644 --- a/ios/chrome/browser/payments/payment_request_util.mm +++ b/ios/chrome/browser/payments/payment_request_util.mm
@@ -13,6 +13,7 @@ #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/validation.h" +#include "components/payments/core/payment_instrument.h" #include "components/payments/core/payment_request_data_util.h" #include "components/payments/core/strings_util.h" #include "components/strings/grit/components_strings.h" @@ -65,7 +66,7 @@ } NSString* GetAddressNotificationLabelFromAutofillProfile( - PaymentRequest& payment_request, + payments::PaymentRequest& payment_request, const autofill::AutofillProfile& profile) { base::string16 label = payment_request.profile_comparator()->GetStringForMissingShippingFields( @@ -73,23 +74,10 @@ return !label.empty() ? base::SysUTF16ToNSString(label) : nil; } -BOOL IsCreditCardCompleteForPayment( - const autofill::CreditCard& credit_card, +NSString* GetPaymentMethodNotificationLabelFromPaymentMethod( + payments::PaymentInstrument& payment_method, const std::vector<autofill::AutofillProfile*>& billing_profiles) { - // EXPIRED cards are considered valid for payment. The user will be prompted - // to enter the new expiration at the CVC step. - return autofill::GetCompletionStatusForCard( - credit_card, GetApplicationContext()->GetApplicationLocale(), - billing_profiles) <= autofill::CREDIT_CARD_EXPIRED; -} - -NSString* GetPaymentMethodNotificationLabelFromCreditCard( - const autofill::CreditCard& credit_card, - const std::vector<autofill::AutofillProfile*>& billing_profiles) { - base::string16 label = autofill::GetCompletionMessageForCard( - autofill::GetCompletionStatusForCard( - credit_card, GetApplicationContext()->GetApplicationLocale(), - billing_profiles)); + base::string16 label = payment_method.GetMissingInfoLabel(); return !label.empty() ? base::SysUTF16ToNSString(label) : nil; } @@ -108,7 +96,7 @@ } NSString* GetShippingAddressSelectorErrorMessage( - const PaymentRequest& payment_request) { + const payments::PaymentRequest& payment_request) { if (!payment_request.payment_details().error.empty()) return base::SysUTF16ToNSString(payment_request.payment_details().error); @@ -126,7 +114,7 @@ } NSString* GetShippingOptionSelectorErrorMessage( - const PaymentRequest& payment_request) { + const payments::PaymentRequest& payment_request) { if (!payment_request.payment_details().error.empty()) return base::SysUTF16ToNSString(payment_request.payment_details().error);
diff --git a/ios/chrome/browser/payments/test_payment_request.h b/ios/chrome/browser/payments/test_payment_request.h index 6d0415f..2d119851 100644 --- a/ios/chrome/browser/payments/test_payment_request.h +++ b/ios/chrome/browser/payments/test_payment_request.h
@@ -28,6 +28,8 @@ class PrefService; +namespace payments { + // PaymentRequest for use in tests. class TestPaymentRequest : public PaymentRequest { public: @@ -69,8 +71,7 @@ pref_service_ = pref_service; } - void SetProfileComparator( - payments::PaymentsProfileComparator* profile_comparator) { + void SetProfileComparator(PaymentsProfileComparator* profile_comparator) { profile_comparator_ = profile_comparator; } @@ -84,8 +85,8 @@ // Removes all the contact profiles. void ClearContactProfiles(); - // Removes all the credit cards. - void ClearCreditCards(); + // Removes all the payment methods. + void ClearPaymentMethods(); // Sets the currently selected shipping option for this PaymentRequest flow. void set_selected_shipping_option(web::PaymentShippingOption* option) { @@ -95,7 +96,7 @@ // PaymentRequest autofill::RegionDataLoader* GetRegionDataLoader() override; PrefService* GetPrefService() override; - payments::PaymentsProfileComparator* profile_comparator() override; + PaymentsProfileComparator* profile_comparator() override; private: // Not owned and must outlive this object. @@ -105,9 +106,11 @@ PrefService* pref_service_; // Not owned and must outlive this object. - payments::PaymentsProfileComparator* profile_comparator_; + PaymentsProfileComparator* profile_comparator_; DISALLOW_COPY_AND_ASSIGN(TestPaymentRequest); }; +} // namespace payments + #endif // IOS_CHROME_BROWSER_PAYMENTS_TEST_PAYMENT_REQUEST_H_
diff --git a/ios/chrome/browser/payments/test_payment_request.mm b/ios/chrome/browser/payments/test_payment_request.mm index 171ba59..95320576 100644 --- a/ios/chrome/browser/payments/test_payment_request.mm +++ b/ios/chrome/browser/payments/test_payment_request.mm
@@ -14,6 +14,8 @@ #error "This file requires ARC support." #endif +namespace payments { + void TestPaymentRequest::ClearShippingProfiles() { shipping_profiles_.clear(); } @@ -22,8 +24,8 @@ contact_profiles_.clear(); } -void TestPaymentRequest::ClearCreditCards() { - credit_cards_.clear(); +void TestPaymentRequest::ClearPaymentMethods() { + payment_methods_.clear(); } autofill::RegionDataLoader* TestPaymentRequest::GetRegionDataLoader() { @@ -38,8 +40,10 @@ return PaymentRequest::GetPrefService(); } -payments::PaymentsProfileComparator* TestPaymentRequest::profile_comparator() { +PaymentsProfileComparator* TestPaymentRequest::profile_comparator() { if (profile_comparator_) return profile_comparator_; return PaymentRequest::profile_comparator(); } + +} // namespace payments
diff --git a/ios/chrome/browser/resources/Settings.bundle/Experimental.plist b/ios/chrome/browser/resources/Settings.bundle/Experimental.plist index a666936..cbc230c 100644 --- a/ios/chrome/browser/resources/Settings.bundle/Experimental.plist +++ b/ios/chrome/browser/resources/Settings.bundle/Experimental.plist
@@ -104,28 +104,6 @@ </dict> <dict> <key>Type</key> - <string>PSMultiValueSpecifier</string> - <key>Title</key> - <string>Enable Popular Sites</string> - <key>Key</key> - <string>EnablePopularSites</string> - <key>DefaultValue</key> - <string></string> - <key>Titles</key> - <array> - <string>Default</string> - <string>Enabled</string> - <string>Disabled</string> - </array> - <key>Values</key> - <array> - <string></string> - <string>Enabled</string> - <string>Disabled</string> - </array> - </dict> - <dict> - <key>Type</key> <string>PSToggleSwitchSpecifier</string> <key>Title</key> <string>Enable Pseudo-RTL</string>
diff --git a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.h b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.h index 7d1c066..52abb4a3 100644 --- a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.h +++ b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.h
@@ -14,11 +14,11 @@ // Objective-C protocol mirroring ChromeIdentityService::Observer. @protocol ChromeIdentityServiceObserver<NSObject> @optional -- (void)onIdentityListChanged; -- (void)onAccessTokenRefreshFailed:(ChromeIdentity*)identity - userInfo:(NSDictionary*)userInfo; -- (void)onProfileUpdate:(ChromeIdentity*)identity; -- (void)onChromeIdentityServiceWillBeDestroyed; +- (void)identityListChanged; +- (void)accessTokenRefreshFailed:(ChromeIdentity*)identity + userInfo:(NSDictionary*)userInfo; +- (void)profileUpdate:(ChromeIdentity*)identity; +- (void)chromeIdentityServiceWillBeDestroyed; @end // Simple observer bridge that forwards all events to its delegate observer.
diff --git a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.mm b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.mm index 46886bd..8db3316 100644 --- a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.mm +++ b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge.mm
@@ -22,30 +22,29 @@ ChromeIdentityServiceObserverBridge::~ChromeIdentityServiceObserverBridge() {} void ChromeIdentityServiceObserverBridge::OnIdentityListChanged() { - if ([observer_ respondsToSelector:@selector(onIdentityListChanged)]) - [observer_ onIdentityListChanged]; + if ([observer_ respondsToSelector:@selector(identityListChanged)]) + [observer_ identityListChanged]; } void ChromeIdentityServiceObserverBridge::OnAccessTokenRefreshFailed( ChromeIdentity* identity, NSDictionary* user_info) { if ([observer_ - respondsToSelector:@selector(onAccessTokenRefreshFailed:userInfo:)]) { - [observer_ onAccessTokenRefreshFailed:identity userInfo:user_info]; + respondsToSelector:@selector(accessTokenRefreshFailed:userInfo:)]) { + [observer_ accessTokenRefreshFailed:identity userInfo:user_info]; } } void ChromeIdentityServiceObserverBridge::OnProfileUpdate( ChromeIdentity* identity) { - if ([observer_ respondsToSelector:@selector(onProfileUpdate:)]) - [observer_ onProfileUpdate:identity]; + if ([observer_ respondsToSelector:@selector(profileUpdate:)]) + [observer_ profileUpdate:identity]; } void ChromeIdentityServiceObserverBridge:: OnChromeIdentityServiceWillBeDestroyed() { if ([observer_ - respondsToSelector:@selector( - onChromeIdentityServiceWillBeDestroyed)]) { - [observer_ onChromeIdentityServiceWillBeDestroyed]; + respondsToSelector:@selector(chromeIdentityServiceWillBeDestroyed)]) { + [observer_ chromeIdentityServiceWillBeDestroyed]; } }
diff --git a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge_unittest.mm b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge_unittest.mm index ae034c27..33384e4 100644 --- a/ios/chrome/browser/signin/chrome_identity_service_observer_bridge_unittest.mm +++ b/ios/chrome/browser/signin/chrome_identity_service_observer_bridge_unittest.mm
@@ -53,23 +53,23 @@ #pragma mark - ios::ChromeIdentityService::Observer -- (void)onIdentityListChanged { +- (void)identityListChanged { _onIdentityListChangedCalled = YES; } -- (void)onAccessTokenRefreshFailed:(ChromeIdentity*)identity - userInfo:(NSDictionary*)userInfo { +- (void)accessTokenRefreshFailed:(ChromeIdentity*)identity + userInfo:(NSDictionary*)userInfo { _onAccessTokenRefreshFailedCalled = YES; _userInfo = userInfo; _identity = identity; } -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { _onProfileUpdateCalled = YES; _identity = identity; } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _onChromeIdentityServiceWillBeDestroyedCalled = YES; }
diff --git a/ios/chrome/browser/tabs/DEPS b/ios/chrome/browser/tabs/DEPS index 8a3f4f299..63246ee6 100644 --- a/ios/chrome/browser/tabs/DEPS +++ b/ios/chrome/browser/tabs/DEPS
@@ -1,7 +1,6 @@ specific_include_rules = { # TODO(crbug.com/620465): Remove tab.mm and tab_unittest.mm exceptions. "^tab\.mm$": [ - "+ios/web/navigation/navigation_item_impl.h", "+ios/web/web_state/web_state_impl.h", "+ios/web/web_state/ui/crw_web_controller.h", "+ios/web/navigation/navigation_manager_impl.h", @@ -13,9 +12,9 @@ "+ios/web/web_state/web_state_impl.h", ], - # TODO(crbug.com/620480): Remove tab.mm and tab_unittest.mm exceptions. + # TODO(crbug.com/620480): Remove tab_model.mm and tab_model_unittest.mm + # exceptions. "^tab_model\.mm$": [ - "+ios/web/web_state/web_state_impl.h", "+ios/web/web_state/ui/crw_web_controller.h", ], "^tab_model_unittest\.mm$": [
diff --git a/ios/chrome/browser/tabs/tab.mm b/ios/chrome/browser/tabs/tab.mm index 7ca80f6..f566d48 100644 --- a/ios/chrome/browser/tabs/tab.mm +++ b/ios/chrome/browser/tabs/tab.mm
@@ -102,12 +102,12 @@ #include "ios/chrome/browser/web/print_observer.h" #import "ios/chrome/browser/web/tab_id_tab_helper.h" #include "ios/chrome/grit/ios_strings.h" -#import "ios/web/navigation/navigation_item_impl.h" #import "ios/web/navigation/navigation_manager_impl.h" #include "ios/web/public/favicon_status.h" #include "ios/web/public/favicon_url.h" #include "ios/web/public/interstitials/web_interstitial.h" #include "ios/web/public/load_committed_details.h" +#import "ios/web/public/navigation_item.h" #import "ios/web/public/navigation_manager.h" #include "ios/web/public/referrer.h" #import "ios/web/public/serializable_user_data_manager.h"
diff --git a/ios/chrome/browser/tabs/tab_model.mm b/ios/chrome/browser/tabs/tab_model.mm index 74d2415e..7acb8c8 100644 --- a/ios/chrome/browser/tabs/tab_model.mm +++ b/ios/chrome/browser/tabs/tab_model.mm
@@ -56,7 +56,6 @@ #include "ios/web/public/web_state/session_certificate_policy_cache.h" #include "ios/web/public/web_thread.h" #import "ios/web/web_state/ui/crw_web_controller.h" -#import "ios/web/web_state/web_state_impl.h" #include "url/gurl.h" #if !defined(__has_feature) || !__has_feature(objc_arc)
diff --git a/ios/chrome/browser/translate/chrome_ios_translate_client.mm b/ios/chrome/browser/translate/chrome_ios_translate_client.mm index 4b984e2e..65bef03 100644 --- a/ios/chrome/browser/translate/chrome_ios_translate_client.mm +++ b/ios/chrome/browser/translate/chrome_ios_translate_client.mm
@@ -23,6 +23,7 @@ #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/browser/translate_step.h" #include "components/translate/core/common/language_detection_details.h" +#include "components/translate/core/common/language_detection_logging_helper.h" #include "components/translate/core/common/translation_logging_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/infobars/infobar.h" @@ -193,7 +194,25 @@ void ChromeIOSTranslateClient::RecordLanguageDetectionEvent( const translate::LanguageDetectionDetails& details) const { - // TODO(crbug.com/728491): Implement this. + if (!base::FeatureList::IsEnabled(switches::kSyncUserLanguageDetectionEvents)) + return; + + syncer::UserEventService* const user_event_service = + IOSUserEventServiceFactory::GetForBrowserState( + ios::ChromeBrowserState::FromBrowserState( + web_state()->GetBrowserState())); + const auto* const item = + web_state()->GetNavigationManager()->GetLastCommittedItem(); + + // If entry is null, we don't record the page. + // The navigation entry can be null in situations like download or initial + // blank page. + if (item != nullptr && + TranslateServiceIOS::IsTranslatableURL(item->GetVirtualURL())) { + user_event_service->RecordUserEvent( + translate::ConstructLanguageDetectionEvent( + item->GetTimestamp().ToInternalValue(), details)); + } } bool ChromeIOSTranslateClient::IsTranslatableURL(const GURL& url) {
diff --git a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm index 9323b06..c0df24f 100644 --- a/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/chrome_signin_view_controller.mm
@@ -374,7 +374,7 @@ return; } strongSelf->_addedAccount = YES; - [strongSelf onIdentityListChanged]; + [strongSelf identityListChanged]; [strongSelf setSelectedIdentity:identity]; [strongSelf changeToState:SIGNIN_PENDING_STATE]; }; @@ -773,7 +773,7 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onIdentityListChanged { +- (void)identityListChanged { switch (_currentState) { case NULL_STATE: case DONE_STATE: @@ -790,7 +790,7 @@ } } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm index cacd6a1c..cc0aa96 100644 --- a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm
@@ -166,7 +166,7 @@ #pragma mark ChromeIdentityServiceObserver -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { CollectionViewAccountItem* item = base::mac::ObjCCastStrict<CollectionViewAccountItem>( [_identityMap objectForKey:identity.gaiaID]); @@ -175,7 +175,7 @@ [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/authentication/signin_account_selector_view_controller.mm b/ios/chrome/browser/ui/authentication/signin_account_selector_view_controller.mm index 2a6fc37..592cedfe 100644 --- a/ios/chrome/browser/ui/authentication/signin_account_selector_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/signin_account_selector_view_controller.mm
@@ -252,7 +252,7 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onIdentityListChanged { +- (void)identityListChanged { ChromeIdentity* selectedIdentity = [self selectedIdentity]; [self loadModel]; [self.collectionView reloadData]; @@ -273,7 +273,7 @@ } } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.mm b/ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.mm index a81b239..243cad4 100644 --- a/ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/signin_confirmation_view_controller.mm
@@ -301,13 +301,13 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { if (identity == _identity) { [self updateViewWithIdentity:identity]; } } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm index 4bf9db6..327c8f23 100644 --- a/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm +++ b/ios/chrome/browser/ui/authentication/signin_promo_view_mediator.mm
@@ -274,7 +274,7 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onIdentityListChanged { +- (void)identityListChanged { ChromeIdentity* newIdentity = nil; NSArray* identities = ios::GetChromeBrowserProvider() ->GetChromeIdentityService() @@ -288,7 +288,7 @@ } } -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { if (identity == _defaultIdentity) { [self sendConsumerNotificationWithIdentityChanged:NO]; }
diff --git a/ios/chrome/browser/ui/background_generator.mm b/ios/chrome/browser/ui/background_generator.mm index d21b44d..a6e46855 100644 --- a/ios/chrome/browser/ui/background_generator.mm +++ b/ios/chrome/browser/ui/background_generator.mm
@@ -52,7 +52,7 @@ void InstallBackgroundInView(UIView* view) { UIImageView* imageView = [[UIImageView alloc] initWithFrame:view.bounds]; - imageView.image = [UIImage imageNamed:@"stack_view_background_noise.jpg"]; + imageView.image = [UIImage imageNamed:@"stack_view_background_noise"]; imageView.contentMode = UIViewContentModeScaleAspectFill; imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
diff --git a/ios/chrome/browser/ui/bookmarks/bookmarks_egtest.mm b/ios/chrome/browser/ui/bookmarks/bookmarks_egtest.mm index 653bce0..27838b2 100644 --- a/ios/chrome/browser/ui/bookmarks/bookmarks_egtest.mm +++ b/ios/chrome/browser/ui/bookmarks/bookmarks_egtest.mm
@@ -214,9 +214,7 @@ } // Close the opened tab. - GenericChromeCommand* command = - [[GenericChromeCommand alloc] initWithTag:IDC_CLOSE_TAB]; - chrome_test_util::RunCommandWithActiveViewController(command); + [chrome_test_util::BrowserCommandDispatcherForMainBVC() closeCurrentTab]; } // Tests that tapping a bookmark on the NTP navigates to the proper URL.
diff --git a/ios/chrome/browser/ui/browser_view_controller.h b/ios/chrome/browser/ui/browser_view_controller.h index d4af89e..97311df 100644 --- a/ios/chrome/browser/ui/browser_view_controller.h +++ b/ios/chrome/browser/ui/browser_view_controller.h
@@ -16,6 +16,7 @@ #import "ios/chrome/browser/ui/url_loader.h" #import "ios/public/provider/chrome/browser/voice/voice_search_presenter.h" +@protocol BrowserCommands; @class BrowserContainerView; @class BrowserViewControllerDependencyFactory; @class ContextualSearchController; @@ -71,6 +72,8 @@ - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; +@property(nonatomic, readonly) id<BrowserCommands> dispatcher; + // The top-level browser container view. @property(nonatomic, strong) BrowserContainerView* contentArea;
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 39998f93..9892269af 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -93,6 +93,7 @@ #import "ios/chrome/browser/ui/browser_view_controller_dependency_factory.h" #import "ios/chrome/browser/ui/chrome_web_view_factory.h" #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/generic_chrome_command.h" #include "ios/chrome/browser/ui/commands/ios_command_ids.h" #import "ios/chrome/browser/ui/commands/open_url_command.h" @@ -957,6 +958,8 @@ forProtocol:@protocol(WebToolbarDelegate)]; [_dispatcher startDispatchingToTarget:self forSelector:@selector(chromeExecuteCommand:)]; + [_dispatcher startDispatchingToTarget:self + forProtocol:@protocol(BrowserCommands)]; _javaScriptDialogPresenter.reset( new JavaScriptDialogPresenterImpl(_dialogPresenter)); @@ -998,6 +1001,10 @@ #pragma mark - Properties +- (id<BrowserCommands>)dispatcher { + return static_cast<id<BrowserCommands>>(_dispatcher); +} + - (void)setActive:(BOOL)active { if (_active == active) { return; @@ -1780,10 +1787,11 @@ new ToolbarModelDelegateIOS([_model webStateList])); _toolbarModelIOS.reset([_dependencyFactory newToolbarModelIOSWithDelegate:_toolbarModelDelegate.get()]); - _toolbarController = [_dependencyFactory - newWebToolbarControllerWithDelegate:self - urlLoader:self - preloadProvider:_preloadController]; + _toolbarController = + [_dependencyFactory newWebToolbarControllerWithDelegate:self + urlLoader:self + preloadProvider:_preloadController + dispatcher:self.dispatcher]; [_dispatcher startDispatchingToTarget:_toolbarController forProtocol:@protocol(OmniboxFocuser)]; [_toolbarController setTabCount:[_model count]]; @@ -2969,7 +2977,7 @@ [self newTab:nil]; break; case OverscrollAction::CLOSE_TAB: - [self closeCurrentTab]; + [self.dispatcher closeCurrentTab]; break; case OverscrollAction::REFRESH: { if ([[[_model currentTab] webController] loadPhase] == @@ -3083,7 +3091,7 @@ pageController.swipeRecognizerProvider = self.sideSwipeController; // Panel is always NTP for iPhone. - NewTabPage::PanelIdentifier panelType = NewTabPage::kMostVisitedPanel; + NewTabPage::PanelIdentifier panelType = NewTabPage::kHomePanel; if (IsIPadIdiom()) { // New Tab Page can have multiple panels. Each panel is addressable @@ -3714,6 +3722,7 @@ } return [self.keyCommandsProvider keyCommandsForConsumer:self + dispatcher:self.dispatcher editingText:![self isFirstResponder]]; } @@ -4010,6 +4019,16 @@ return card; } +#pragma mark - BrowserCommands + +- (void)goBack { + [[_model currentTab] goBack]; +} + +- (void)goForward { + [[_model currentTab] goForward]; +} + #pragma mark - Command Handling - (IBAction)chromeExecuteCommand:(id)sender { @@ -4020,9 +4039,6 @@ Tab* currentTab = [_model currentTab]; switch (command) { - case IDC_BACK: - [[_model currentTab] goBack]; - break; case IDC_BOOKMARK_PAGE: [self initializeBookmarkInteractionController]; [_bookmarkInteractionController @@ -4031,9 +4047,6 @@ inView:[_toolbarController bookmarkButtonView] originRect:[_toolbarController bookmarkButtonAnchorRect]]; break; - case IDC_CLOSE_TAB: - [self closeCurrentTab]; - break; case IDC_FIND: [self initFindBarForTab]; break; @@ -4061,9 +4074,6 @@ case IDC_FIND_UPDATE: [self searchFindInPage]; break; - case IDC_FORWARD: - [[_model currentTab] goForward]; - break; case IDC_FULLSCREEN: NOTIMPLEMENTED(); break;
diff --git a/ios/chrome/browser/ui/browser_view_controller_dependency_factory.h b/ios/chrome/browser/ui/browser_view_controller_dependency_factory.h index e38cefe..7b57a2d 100644 --- a/ios/chrome/browser/ui/browser_view_controller_dependency_factory.h +++ b/ios/chrome/browser/ui/browser_view_controller_dependency_factory.h
@@ -10,6 +10,7 @@ #include "ios/chrome/browser/ui/tabs/tab_strip_controller.h" @class AlertCoordinator; +@protocol BrowserCommands; @class KeyCommandsProvider; @class MessageBubbleView; @class PKPass; @@ -65,7 +66,8 @@ - (WebToolbarController*) newWebToolbarControllerWithDelegate:(id<WebToolbarDelegate>)delegate urlLoader:(id<UrlLoader>)urlLoader - preloadProvider:(id<PreloadProvider>)preload; + preloadProvider:(id<PreloadProvider>)preload + dispatcher:(id<BrowserCommands>)dispatcher; // Returns a new keyboard commands coordinator to handle keyboard commands. - (KeyCommandsProvider*)newKeyCommandsProvider;
diff --git a/ios/chrome/browser/ui/browser_view_controller_dependency_factory.mm b/ios/chrome/browser/ui/browser_view_controller_dependency_factory.mm index 3708124..36a34f2 100644 --- a/ios/chrome/browser/ui/browser_view_controller_dependency_factory.mm +++ b/ios/chrome/browser/ui/browser_view_controller_dependency_factory.mm
@@ -81,11 +81,13 @@ - (WebToolbarController*) newWebToolbarControllerWithDelegate:(id<WebToolbarDelegate>)delegate urlLoader:(id<UrlLoader>)urlLoader - preloadProvider:(id<PreloadProvider>)preload { + preloadProvider:(id<PreloadProvider>)preload + dispatcher:(id<BrowserCommands>)dispatcher { return [[WebToolbarController alloc] initWithDelegate:delegate urlLoader:urlLoader browserState:browserState_ - preloadProvider:preload]; + preloadProvider:preload + dispatcher:dispatcher]; } - (KeyCommandsProvider*)newKeyCommandsProvider {
diff --git a/ios/chrome/browser/ui/browser_view_controller_unittest.mm b/ios/chrome/browser/ui/browser_view_controller_unittest.mm index 11d3e6ee..72f2e73 100644 --- a/ios/chrome/browser/ui/browser_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/browser_view_controller_unittest.mm
@@ -236,7 +236,8 @@ [[[factory stub] andReturn:nil] newWebToolbarControllerWithDelegate:[OCMArg any] urlLoader:[OCMArg any] - preloadProvider:[OCMArg any]]; + preloadProvider:[OCMArg any] + dispatcher:[OCMArg any]]; [[[factory stub] andReturn:shareController_] shareControllerInstance]; [[[factory stub] andReturn:passKitViewController_] newPassKitViewControllerForPass:nil];
diff --git a/ios/chrome/browser/ui/commands/BUILD.gn b/ios/chrome/browser/ui/commands/BUILD.gn index ce2d052..68681ef 100644 --- a/ios/chrome/browser/ui/commands/BUILD.gn +++ b/ios/chrome/browser/ui/commands/BUILD.gn
@@ -7,6 +7,7 @@ sources = [ "UIKit+ChromeExecuteCommand.h", "UIKit+ChromeExecuteCommand.mm", + "browser_commands.h", "clear_browsing_data_command.h", "clear_browsing_data_command.mm", "generic_chrome_command.h",
diff --git a/ios/chrome/browser/ui/commands/browser_commands.h b/ios/chrome/browser/ui/commands/browser_commands.h new file mode 100644 index 0000000..ee911d0 --- /dev/null +++ b/ios/chrome/browser/ui/commands/browser_commands.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 IOS_CHROME_BROWSER_UI_COMMANDS_BROWSER_COMMANDS_H_ +#define IOS_CHROME_BROWSER_UI_COMMANDS_BROWSER_COMMANDS_H_ + +// Protocol for commands that will generally be handled by the "current tab", +// which in practice is the BrowserViewController instance displaying the tab. +@protocol BrowserCommands + +// Closes the current tab. +- (void)closeCurrentTab; + +// Navigates backwards in the current tab's history. +- (void)goBack; + +// Navigates forwards in the current tab's history. +- (void)goForward; + +@end + +#endif // IOS_CHROME_BROWSER_UI_COMMANDS_BROWSER_COMMANDS_H_
diff --git a/ios/chrome/browser/ui/commands/ios_command_ids.h b/ios/chrome/browser/ui/commands/ios_command_ids.h index a2925a3..58a4aa3 100644 --- a/ios/chrome/browser/ui/commands/ios_command_ids.h +++ b/ios/chrome/browser/ui/commands/ios_command_ids.h
@@ -13,12 +13,9 @@ // also need to be updated. // clang-format off -#define IDC_BACK 33000 -#define IDC_FORWARD 33001 #define IDC_RELOAD 33002 #define IDC_STOP 33006 #define IDC_NEW_TAB 34014 -#define IDC_CLOSE_TAB 34015 #define IDC_FULLSCREEN 34030 #define IDC_BOOKMARK_PAGE 35000 #define IDC_VIEW_SOURCE 35002
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h index f2e6b4e..52e5d7b 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_synchronizing.h
@@ -16,6 +16,9 @@ // Moves the tiles up by pinning the omnibox to the top. Completion called only // if scrolled to top. - (void)shiftTilesUpWithCompletionBlock:(ProceduralBlock)completionBlock; +// Notifies the collection that its layout has changed and should be +// invalidated. +- (void)invalidateLayout; @end
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_updater.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_updater.mm index 563330e8..8b33943 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_updater.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_updater.mm
@@ -22,6 +22,7 @@ #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_data_source.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_image_fetcher.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h" #import "ios/chrome/browser/ui/content_suggestions/identifier/content_suggestion_identifier.h" #import "ios/chrome/browser/ui/content_suggestions/identifier/content_suggestions_section_information.h" #include "ui/base/l10n/l10n_util.h" @@ -123,6 +124,8 @@ sectionInfoBySectionIdentifier; // Width of the collection. Upon size change, it reflects the new size. @property(nonatomic, assign) CGFloat collectionWidth; +// Whether an item of type ItemTypePromo has already been added to the model. +@property(nonatomic, assign) BOOL promoAdded; @end @@ -132,11 +135,13 @@ @synthesize dataSource = _dataSource; @synthesize sectionInfoBySectionIdentifier = _sectionInfoBySectionIdentifier; @synthesize collectionWidth = _collectionWidth; +@synthesize promoAdded = _promoAdded; - (instancetype)initWithDataSource: (id<ContentSuggestionsDataSource>)dataSource { self = [super init]; if (self) { + _promoAdded = NO; _dataSource = dataSource; _dataSource.dataSink = self; } @@ -329,6 +334,10 @@ return; } ItemType type = ItemTypeForInfo(sectionInfo); + if (type == ItemTypePromo && !self.promoAdded) { + self.promoAdded = YES; + [self.collectionViewController.audience promoShown]; + } item.type = type; NSIndexPath* addedIndexPath = [self addItem:item toSectionWithIdentifier:sectionIdentifier];
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm index 53c9f7c..b32362fc 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm
@@ -141,6 +141,10 @@ }]; } +- (void)invalidateLayout { + [self.collectionView.collectionViewLayout invalidateLayout]; +} + #pragma mark - ContentSuggestionsHeaderSynchronizing - (void)updateFakeOmniboxForScrollView:(UIScrollView*)scrollView {
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm index 529a6e6..597a0d6 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm
@@ -195,6 +195,7 @@ - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>)coordinator { + [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; // Change the margin, in case -willTransitionToTraitCollection: is called // after this method. self.cardStyleMargin = MAX(0, (size.width - kMaxCardWidth) / 2); @@ -209,6 +210,8 @@ - (void)willTransitionToTraitCollection:(UITraitCollection*)newCollection withTransitionCoordinator: (id<UIViewControllerTransitionCoordinator>)coordinator { + [super willTransitionToTraitCollection:newCollection + withTransitionCoordinator:coordinator]; if (ShouldCellsBeFullWidth(newCollection)) { self.collectionView.contentInset = UIEdgeInsetsZero; self.styler.cellStyle = MDCCollectionViewCellStyleGrouped;
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h index 9b13e41..3975502 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h
@@ -11,6 +11,8 @@ // Notifies the audience that the content suggestions collection has been // scrolled. - (void)contentSuggestionsDidScroll; +// Notifies the audience that the promo has been shown. +- (void)promoShown; @end
diff --git a/ios/chrome/browser/ui/key_commands_provider.h b/ios/chrome/browser/ui/key_commands_provider.h index cc914ee..37bfd51 100644 --- a/ios/chrome/browser/ui/key_commands_provider.h +++ b/ios/chrome/browser/ui/key_commands_provider.h
@@ -7,6 +7,8 @@ #import <UIKit/UIKit.h> +#import "ios/chrome/browser/ui/commands/browser_commands.h" + @protocol KeyCommandsPlumbing<NSObject> #pragma mark Query information @@ -52,6 +54,7 @@ @interface KeyCommandsProvider : NSObject - (NSArray*)keyCommandsForConsumer:(id<KeyCommandsPlumbing>)consumer + dispatcher:(id<BrowserCommands>)dispatcher editingText:(BOOL)editingText; @end
diff --git a/ios/chrome/browser/ui/key_commands_provider.mm b/ios/chrome/browser/ui/key_commands_provider.mm index 72c99b7..e09cb7c 100644 --- a/ios/chrome/browser/ui/key_commands_provider.mm +++ b/ios/chrome/browser/ui/key_commands_provider.mm
@@ -20,8 +20,10 @@ @implementation KeyCommandsProvider - (NSArray*)keyCommandsForConsumer:(id<KeyCommandsPlumbing>)consumer + dispatcher:(id<BrowserCommands>)dispatcher editingText:(BOOL)editingText { __weak id<KeyCommandsPlumbing> weakConsumer = consumer; + __weak id<BrowserCommands> weakDispatcher = dispatcher; // Block to execute a command from the |tag|. void (^execute)(NSInteger) = ^(NSInteger tag) { @@ -37,22 +39,36 @@ const BOOL hasTabs = [consumer tabsCount] > 0; const BOOL useRTLLayout = UseRTLLayout(); - const NSInteger browseLeft = useRTLLayout ? IDC_FORWARD : IDC_BACK; - const NSInteger browseRight = useRTLLayout ? IDC_BACK : IDC_FORWARD; + + // Blocks for navigating forward/back. + void (^browseLeft)(); + void (^browseRight)(); + if (useRTLLayout) { + browseLeft = ^{ + if ([weakConsumer canGoForward]) + [weakDispatcher goForward]; + }; + browseRight = ^{ + if ([weakConsumer canGoBack]) + [weakDispatcher goBack]; + }; + } else { + browseLeft = ^{ + if ([weakConsumer canGoBack]) + [weakDispatcher goBack]; + }; + browseRight = ^{ + if ([weakConsumer canGoForward]) + [weakDispatcher goForward]; + }; + } + const int browseLeftDescriptionID = useRTLLayout ? IDS_IOS_KEYBOARD_HISTORY_FORWARD : IDS_IOS_KEYBOARD_HISTORY_BACK; const int browseRightDescriptionID = useRTLLayout ? IDS_IOS_KEYBOARD_HISTORY_BACK : IDS_IOS_KEYBOARD_HISTORY_FORWARD; - BOOL (^canBrowseLeft)() = ^() { - return useRTLLayout ? [weakConsumer canGoForward] - : [weakConsumer canGoBack]; - }; - BOOL (^canBrowseRight)() = ^() { - return useRTLLayout ? [weakConsumer canGoBack] - : [weakConsumer canGoForward]; - }; // Initialize the array of commands with an estimated capacity. NSMutableArray* keyCommands = [NSMutableArray arrayWithCapacity:32]; @@ -105,7 +121,7 @@ title:l10n_util::GetNSStringWithFixup( IDS_IOS_TOOLS_MENU_CLOSE_TAB) action:^{ - execute(IDC_CLOSE_TAB); + [weakDispatcher closeCurrentTab]; }], [UIKeyCommand cr_keyCommandWithInput:@"d" @@ -153,18 +169,14 @@ title:l10n_util::GetNSStringWithFixup( browseLeftDescriptionID) action:^{ - if (canBrowseLeft()) { - execute(browseLeft); - } + browseLeft(); }], [UIKeyCommand cr_keyCommandWithInput:UIKeyInputRightArrow modifierFlags:UIKeyModifierCommand title:l10n_util::GetNSStringWithFixup( browseRightDescriptionID) action:^{ - if (canBrowseRight()) { - execute(browseRight); - } + browseRight(); }], ]]; } @@ -223,17 +235,13 @@ modifierFlags:UIKeyModifierCommand title:nil action:^{ - if (canBrowseLeft()) { - execute(browseLeft); - } + browseLeft(); }], [UIKeyCommand cr_keyCommandWithInput:@"]" modifierFlags:UIKeyModifierCommand title:nil action:^{ - if (canBrowseRight()) { - execute(browseRight); - } + browseRight(); }], [UIKeyCommand cr_keyCommandWithInput:@"." modifierFlags:UIKeyModifierCommand
diff --git a/ios/chrome/browser/ui/key_commands_provider_unittest.mm b/ios/chrome/browser/ui/key_commands_provider_unittest.mm index b616ce4..6bfe4a0f 100644 --- a/ios/chrome/browser/ui/key_commands_provider_unittest.mm +++ b/ios/chrome/browser/ui/key_commands_provider_unittest.mm
@@ -22,20 +22,25 @@ KeyCommandsProvider* provider = [[KeyCommandsProvider alloc] init]; id mockConsumer = [OCMockObject mockForProtocol:@protocol(KeyCommandsPlumbing)]; + id<BrowserCommands> dispatcher = nil; [[[mockConsumer expect] andReturnUnsignedInteger:0] tabsCount]; - EXPECT_NE(nil, - [provider keyCommandsForConsumer:mockConsumer editingText:YES]); + EXPECT_NE(nil, [provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:YES]); } TEST(KeyCommandsProviderTest, ReturnsKeyCommandsObjects) { KeyCommandsProvider* provider = [[KeyCommandsProvider alloc] init]; id mockConsumer = [OCMockObject mockForProtocol:@protocol(KeyCommandsPlumbing)]; + id<BrowserCommands> dispatcher = nil; + [[[mockConsumer expect] andReturnUnsignedInteger:0] tabsCount]; - for (id element in - [provider keyCommandsForConsumer:mockConsumer editingText:YES]) { + for (id element in [provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:YES]) { EXPECT_TRUE([element isKindOfClass:[UIKeyCommand class]]); } } @@ -44,16 +49,21 @@ KeyCommandsProvider* provider = [[KeyCommandsProvider alloc] init]; id mockConsumer = [OCMockObject mockForProtocol:@protocol(KeyCommandsPlumbing)]; + id<BrowserCommands> dispatcher = nil; // No tabs. [[[mockConsumer expect] andReturnUnsignedInteger:0] tabsCount]; NSUInteger numberOfKeyCommandsWithoutTabs = - [[provider keyCommandsForConsumer:mockConsumer editingText:NO] count]; + [[provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:NO] count]; // Tabs. [[[mockConsumer expect] andReturnUnsignedInteger:1] tabsCount]; NSUInteger numberOfKeyCommandsWithTabs = - [[provider keyCommandsForConsumer:mockConsumer editingText:NO] count]; + [[provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:NO] count]; EXPECT_GT(numberOfKeyCommandsWithTabs, numberOfKeyCommandsWithoutTabs); } @@ -62,16 +72,21 @@ KeyCommandsProvider* provider = [[KeyCommandsProvider alloc] init]; id mockConsumer = [OCMockObject mockForProtocol:@protocol(KeyCommandsPlumbing)]; + id<BrowserCommands> dispatcher = nil; // Not editing text. [[[mockConsumer expect] andReturnUnsignedInteger:1] tabsCount]; NSUInteger numberOfKeyCommandsWhenNotEditingText = - [[provider keyCommandsForConsumer:mockConsumer editingText:NO] count]; + [[provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:NO] count]; // Editing text. [[[mockConsumer expect] andReturnUnsignedInteger:1] tabsCount]; NSUInteger numberOfKeyCommandsWhenEditingText = - [[provider keyCommandsForConsumer:mockConsumer editingText:YES] count]; + [[provider keyCommandsForConsumer:mockConsumer + dispatcher:dispatcher + editingText:YES] count]; EXPECT_LT(numberOfKeyCommandsWhenEditingText, numberOfKeyCommandsWhenNotEditingText);
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index c093a5b..24cc4ab 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -2,107 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -bundle_data("resources") { - sources = [ - "resources/bookmarks_bar_bg.png", - "resources/bookmarks_bar_bg@2x.png", - "resources/bookmarks_bar_bg@2x~ipad.png", - "resources/bookmarks_bar_bg_pressed@2x~ipad.png", - "resources/bookmarks_bar_bg_pressed~ipad.png", - "resources/bookmarks_bar_bg~ipad.png", - "resources/bookmarks_bar_breadcrumb.png", - "resources/bookmarks_bar_breadcrumb@2x.png", - "resources/bookmarks_bar_breadcrumb@2x~ipad.png", - "resources/bookmarks_bar_breadcrumb~ipad.png", - "resources/bookmarks_bar_edit.png", - "resources/bookmarks_bar_edit@2x.png", - "resources/bookmarks_bar_edit@2x~ipad.png", - "resources/bookmarks_bar_edit_moreshadow.png", - "resources/bookmarks_bar_edit_moreshadow@2x.png", - "resources/bookmarks_bar_edit_pressed.png", - "resources/bookmarks_bar_edit_pressed@2x.png", - "resources/bookmarks_bar_edit_pressed@2x~ipad.png", - "resources/bookmarks_bar_edit_pressed_moreshadow.png", - "resources/bookmarks_bar_edit_pressed_moreshadow@2x.png", - "resources/bookmarks_bar_edit_pressed~ipad.png", - "resources/bookmarks_bar_edit~ipad.png", - "resources/bookmarks_bar_left@2x~ipad.png", - "resources/bookmarks_bar_left~ipad.png", - "resources/bookmarks_button_bg.png", - "resources/bookmarks_button_bg@2x.png", - "resources/bookmarks_button_border.png", - "resources/bookmarks_button_border@2x.png", - "resources/disclosure_open.png", - "resources/disclosure_open@2x.png", - "resources/incognito_icon.png", - "resources/incognito_icon@2x.png", - "resources/incognito_icon@3x.png", - "resources/ntp_bookmarks.png", - "resources/ntp_bookmarks@2x.png", - "resources/ntp_bookmarks@3x.png", - "resources/ntp_bottom_bar_shadow.png", - "resources/ntp_bottom_bar_shadow@2x.png", - "resources/ntp_delete_button.png", - "resources/ntp_delete_button@2x.png", - "resources/ntp_google_search_box.png", - "resources/ntp_google_search_box@2x.png", - "resources/ntp_google_search_box@3x.png", - "resources/ntp_incognito.png", - "resources/ntp_incognito@2x.png", - "resources/ntp_mv_placeholder_bg.png", - "resources/ntp_mv_placeholder_bg@2x.png", - "resources/ntp_mv_placeholder_bg@3x.png", - "resources/ntp_mv_recentbar@2x~ipad.png", - "resources/ntp_mv_recentbar~ipad.png", - "resources/ntp_mv_recentpress@2x~ipad.png", - "resources/ntp_mv_recentpress~ipad.png", - "resources/ntp_mv_search.png", - "resources/ntp_mv_search@2x.png", - "resources/ntp_mv_thumbnail_container.png", - "resources/ntp_mv_thumbnail_container@2x.png", - "resources/ntp_mv_thumbnail_container@3x.png", - "resources/ntp_mv_thumbnail_empty.png", - "resources/ntp_mv_thumbnail_empty@2x.png", - "resources/ntp_mv_thumbnail_empty@2x~ipad.png", - "resources/ntp_mv_thumbnail_empty~ipad.png", - "resources/ntp_mv_welcome_favicon.png", - "resources/ntp_mv_welcome_favicon@2x.png", - "resources/ntp_opentabs@2x.png", - "resources/ntp_opentabs@3x.png", - "resources/ntp_opentabs_clock.png", - "resources/ntp_opentabs_clock@2x.png", - "resources/ntp_opentabs_clock@3x.png", - "resources/ntp_opentabs_header@2x~ipad.png", - "resources/ntp_opentabs_header~ipad.png", - "resources/ntp_opentabs_laptop.png", - "resources/ntp_opentabs_laptop@2x.png", - "resources/ntp_opentabs_laptop@3x.png", - "resources/ntp_opentabs_last_row@2x~ipad.png", - "resources/ntp_opentabs_last_row_h@2x~ipad.png", - "resources/ntp_opentabs_last_row_h~ipad.png", - "resources/ntp_opentabs_last_row~ipad.png", - "resources/ntp_opentabs_list_item@2x~ipad.png", - "resources/ntp_opentabs_list_item_h@2x~ipad.png", - "resources/ntp_opentabs_list_item_h~ipad.png", - "resources/ntp_opentabs_list_item~ipad.png", - "resources/ntp_opentabs_phone.png", - "resources/ntp_opentabs_phone@2x.png", - "resources/ntp_opentabs_phone@3x.png", - "resources/ntp_opentabs_recent_arrow.png", - "resources/ntp_opentabs_recent_arrow@2x.png", - "resources/ntp_opentabs_recent_arrow@3x.png", - "resources/ntp_opentabs_tablet.png", - "resources/ntp_opentabs_tablet@2x.png", - "resources/ntp_opentabs_tablet@3x.png", - "resources/ntp_recently_closed.png", - "resources/ntp_recently_closed@2x.png", - "resources/ntp_recently_closed@3x.png", - ] - outputs = [ - "{{bundle_resources_dir}}/{{source_file_part}}", - ] -} - source_set("ntp") { sources = [ "new_tab_page_panel_protocol.h", @@ -203,7 +102,42 @@ ] deps = [ ":ntp", - ":resources", + "resources:bookmarks_bar_bg", + "resources:bookmarks_bar_bg_pressed", + "resources:bookmarks_bar_breadcrumb", + "resources:bookmarks_bar_edit", + "resources:bookmarks_bar_edit_moreshadow", + "resources:bookmarks_bar_edit_pressed", + "resources:bookmarks_bar_edit_pressed_moreshadow", + "resources:bookmarks_bar_left", + "resources:bookmarks_button_bg", + "resources:bookmarks_button_border", + "resources:disclosure_open", + "resources:incognito_icon", + "resources:ntp_bookmarks", + "resources:ntp_bottom_bar_shadow", + "resources:ntp_delete_button", + "resources:ntp_google_search_box", + "resources:ntp_incognito", + "resources:ntp_mv_placeholder_bg", + "resources:ntp_mv_recentbar", + "resources:ntp_mv_recentpress", + "resources:ntp_mv_search", + "resources:ntp_mv_thumbnail_container", + "resources:ntp_mv_thumbnail_empty", + "resources:ntp_mv_welcome_favicon", + "resources:ntp_opentabs", + "resources:ntp_opentabs_clock", + "resources:ntp_opentabs_header", + "resources:ntp_opentabs_laptop", + "resources:ntp_opentabs_last_row", + "resources:ntp_opentabs_last_row_h", + "resources:ntp_opentabs_list_item", + "resources:ntp_opentabs_list_item_h", + "resources:ntp_opentabs_phone", + "resources:ntp_opentabs_recent_arrow", + "resources:ntp_opentabs_tablet", + "resources:ntp_recently_closed", "//base", "//base:i18n", "//components/favicon/core",
diff --git a/ios/chrome/browser/ui/ntp/google_landing_mediator.mm b/ios/chrome/browser/ui/ntp/google_landing_mediator.mm index 487c223..ffdf13f 100644 --- a/ios/chrome/browser/ui/ntp/google_landing_mediator.mm +++ b/ios/chrome/browser/ui/ntp/google_landing_mediator.mm
@@ -307,7 +307,9 @@ UIImage* favicon = [UIImage imageWithData:[NSData dataWithBytes:data->front() length:data->size()] scale:[UIScreen mainScreen].scale]; - imageCallback(favicon); + if (imageCallback) { + imageCallback(favicon); + } tileType = ntp_tiles::TileVisualType::ICON_REAL; } else if (result.fallback_icon_style) { UIColor* backgroundColor = skia::UIColorFromSkColor( @@ -316,16 +318,19 @@ skia::UIColorFromSkColor(result.fallback_icon_style->text_color); BOOL isDefaultColor = result.fallback_icon_style->is_default_background_color; - fallbackCallback(textColor, backgroundColor, isDefaultColor); - fallbackCallback(backgroundColor, textColor, isDefaultColor); + if (fallbackCallback) { + fallbackCallback(textColor, backgroundColor, isDefaultColor); + } tileType = isDefaultColor ? ntp_tiles::TileVisualType::ICON_DEFAULT : ntp_tiles::TileVisualType::ICON_COLOR; } GoogleLandingMediator* strongSelf = weakSelf; - if (strongSelf && - (result.bitmap.is_valid() || result.fallback_icon_style)) { - [strongSelf largeIconCache]->SetCachedResult(URL, result); + if (strongSelf) { + if (result.bitmap.is_valid() || result.fallback_icon_style) { + [strongSelf largeIconCache]->SetCachedResult(URL, result); + } + [strongSelf faviconOfType:tileType fetchedForURL:URL]; } };
diff --git a/ios/chrome/browser/ui/ntp/google_landing_view_controller.h b/ios/chrome/browser/ui/ntp/google_landing_view_controller.h index a40c9877..d44e4a2 100644 --- a/ios/chrome/browser/ui/ntp/google_landing_view_controller.h +++ b/ios/chrome/browser/ui/ntp/google_landing_view_controller.h
@@ -14,6 +14,7 @@ #import "ios/chrome/browser/ui/toolbar/toolbar_owner.h" #import "ios/public/provider/chrome/browser/voice/logo_animation_controller.h" +@protocol BrowserCommands; @protocol GoogleLandingDataSource; @protocol OmniboxFocuser; @protocol UrlLoader; @@ -27,7 +28,8 @@ @property(nonatomic, weak) id<GoogleLandingDataSource> dataSource; -@property(nonatomic, weak) id<UrlLoader, OmniboxFocuser> dispatcher; +@property(nonatomic, weak) id<BrowserCommands, OmniboxFocuser, UrlLoader> + dispatcher; @end
diff --git a/ios/chrome/browser/ui/ntp/google_landing_view_controller.mm b/ios/chrome/browser/ui/ntp/google_landing_view_controller.mm index 69f1073..5149dac 100644 --- a/ios/chrome/browser/ui/ntp/google_landing_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/google_landing_view_controller.mm
@@ -11,6 +11,7 @@ #include "base/strings/sys_string_conversions.h" #include "components/strings/grit/components_strings.h" #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/generic_chrome_command.h" #include "ios/chrome/browser/ui/commands/ios_command_ids.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.h" @@ -1224,11 +1225,9 @@ [[GenericChromeCommand alloc] initWithTag:IDC_NEW_TAB]; [[self view] chromeExecuteCommand:command]; } break; - case OverscrollAction::CLOSE_TAB: { - GenericChromeCommand* command = - [[GenericChromeCommand alloc] initWithTag:IDC_CLOSE_TAB]; - [[self view] chromeExecuteCommand:command]; - } break; + case OverscrollAction::CLOSE_TAB: + [self.dispatcher closeCurrentTab]; + break; case OverscrollAction::REFRESH: [self reload]; break;
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_controller.h b/ios/chrome/browser/ui/ntp/new_tab_page_controller.h index 92f18a11..cde4bb2 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_controller.h +++ b/ios/chrome/browser/ui/ntp/new_tab_page_controller.h
@@ -22,7 +22,7 @@ enum PanelIdentifier { kNone, - kMostVisitedPanel, + kHomePanel, kBookmarksPanel, kOpenTabsPanel, kIncognitoPanel,
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_controller.mm index 806efc8..3e0ed72 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_controller.mm
@@ -16,7 +16,7 @@ #include "components/sync_sessions/synced_session.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #import "ios/chrome/browser/content_suggestions/content_suggestions_coordinator.h" -#import "ios/chrome/browser/content_suggestions/content_suggestions_header_controller.h" +#import "ios/chrome/browser/content_suggestions/content_suggestions_header_view_controller.h" #include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/pref_names.h" #include "ios/chrome/browser/search_engines/template_url_service_factory.h" @@ -65,7 +65,7 @@ // See chrome/browser/resources/mobile_ntp/mobile_ntp.js PanelIdentifier IdentifierFromFragment(const std::string& fragment) { if (fragment == kMostVisitedFragment) - return NewTabPage::kMostVisitedPanel; + return NewTabPage::kHomePanel; else if (fragment == kBookmarksFragment) return NewTabPage::kBookmarksPanel; else if (fragment == kOpenTabsFragment) @@ -82,7 +82,7 @@ switch (panel) { case NewTabPage::kNone: return ""; - case NewTabPage::kMostVisitedPanel: + case NewTabPage::kHomePanel: return kMostVisitedFragment; case NewTabPage::kBookmarksPanel: return kBookmarksFragment; @@ -246,8 +246,9 @@ bool isIncognito = _browserState->IsOffTheRecord(); NSString* incognito = l10n_util::GetNSString(IDS_IOS_NEW_TAB_INCOGNITO); - NSString* mostVisited = - l10n_util::GetNSString(IDS_IOS_NEW_TAB_MOST_VISITED); + NSString* home = experimental_flags::IsSuggestionsUIEnabled() + ? l10n_util::GetNSString(IDS_IOS_NEW_TAB_HOME) + : l10n_util::GetNSString(IDS_IOS_NEW_TAB_MOST_VISITED); NSString* bookmarks = l10n_util::GetNSString(IDS_IOS_NEW_TAB_BOOKMARKS_PAGE_TITLE_MOBILE); NSString* openTabs = l10n_util::GetNSString(IDS_IOS_NEW_TAB_RECENT_TABS); @@ -271,9 +272,9 @@ } itemToDisplay = incognitoItem; } else { - NewTabPageBarItem* mostVisitedItem = [NewTabPageBarItem - newTabPageBarItemWithTitle:mostVisited - identifier:NewTabPage::kMostVisitedPanel + NewTabPageBarItem* homeItem = [NewTabPageBarItem + newTabPageBarItemWithTitle:home + identifier:NewTabPage::kHomePanel image:[UIImage imageNamed:@"ntp_mv_search"]]; NewTabPageBarItem* bookmarksItem = [NewTabPageBarItem newTabPageBarItemWithTitle:bookmarks @@ -281,7 +282,7 @@ image:[UIImage imageNamed:@"ntp_bookmarks"]]; [tabBarItems addObject:bookmarksItem]; if (IsIPadIdiom()) { - [tabBarItems addObject:mostVisitedItem]; + [tabBarItems addObject:homeItem]; } NewTabPageBarItem* openTabsItem = [NewTabPageBarItem @@ -292,7 +293,7 @@ self.ntpView.tabBar.items = tabBarItems; if (!IsIPadIdiom()) { - itemToDisplay = mostVisitedItem; + itemToDisplay = homeItem; } else { PrefService* prefs = _browserState->GetPrefs(); int shownPage = prefs->GetInteger(prefs::kNtpShownPage); @@ -303,7 +304,7 @@ } else if (shownPage == OPEN_TABS_PAGE_ID) { itemToDisplay = openTabsItem; } else { - itemToDisplay = mostVisitedItem; + itemToDisplay = homeItem; } } } @@ -373,7 +374,7 @@ } - (BOOL)wantsKeyboardShield { - return [self selectedPanelID] != NewTabPage::kMostVisitedPanel; + return [self selectedPanelID] != NewTabPage::kHomePanel; } - (BOOL)wantsLocationBarHintText { @@ -396,7 +397,7 @@ if (_browserState->IsOffTheRecord()) return YES; - return [self selectedPanelID] != NewTabPage::kMostVisitedPanel; + return [self selectedPanelID] != NewTabPage::kHomePanel; } - (void)dismissKeyboard { @@ -531,7 +532,7 @@ // Intentionally omitting a metric for the Incognito panel. if (item.identifier == NewTabPage::kBookmarksPanel) base::RecordAction(UserMetricsAction("MobileNTPShowBookmarks")); - else if (item.identifier == NewTabPage::kMostVisitedPanel) + else if (item.identifier == NewTabPage::kHomePanel) base::RecordAction(UserMetricsAction("MobileNTPShowMostVisited")); else if (item.identifier == NewTabPage::kOpenTabsPanel) base::RecordAction(UserMetricsAction("MobileNTPShowOpenTabs")); @@ -565,7 +566,7 @@ panelController = _bookmarkController; view = [_bookmarkController view]; [_bookmarkController setDelegate:self]; - } else if (item.identifier == NewTabPage::kMostVisitedPanel) { + } else if (item.identifier == NewTabPage::kHomePanel) { if (experimental_flags::IsSuggestionsUIEnabled()) { if (!self.contentSuggestionsCoordinator) { self.contentSuggestionsCoordinator = @@ -689,7 +690,7 @@ NewTabPageBarItem* item = self.ntpView.tabBar.items[index]; return static_cast<NewTabPage::PanelIdentifier>(item.identifier); } - return NewTabPage::kMostVisitedPanel; + return NewTabPage::kHomePanel; } - (void)updateCurrentController:(NewTabPageBarItem*)item @@ -705,7 +706,7 @@ self.ntpView.tabBar.selectedIndex = index; if (item.identifier == NewTabPage::kBookmarksPanel) _currentController = _bookmarkController; - else if (item.identifier == NewTabPage::kMostVisitedPanel) + else if (item.identifier == NewTabPage::kHomePanel) _currentController = self.homePanel; else if (item.identifier == NewTabPage::kOpenTabsPanel) _currentController = _openTabsController; @@ -738,7 +739,7 @@ if (item.identifier == NewTabPage::kBookmarksPanel) { base::RecordAction(UserMetricsAction("MobileNTPSwitchToBookmarks")); prefs->SetInteger(prefs::kNtpShownPage, BOOKMARKS_PAGE_ID); - } else if (item.identifier == NewTabPage::kMostVisitedPanel) { + } else if (item.identifier == NewTabPage::kHomePanel) { base::RecordAction(UserMetricsAction("MobileNTPSwitchToMostVisited")); prefs->SetInteger(prefs::kNtpShownPage, MOST_VISITED_PAGE_ID); } else if (item.identifier == NewTabPage::kOpenTabsPanel) {
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_egtest.mm b/ios/chrome/browser/ui/ntp/new_tab_page_egtest.mm index 538d27b..51fdcfb 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_egtest.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_egtest.mm
@@ -107,7 +107,7 @@ // Tests that all items are accessible on the most visited page. - (void)testAccessibilityOnMostVisited { - SelectNewTabPagePanel(NewTabPage::kMostVisitedPanel); + SelectNewTabPagePanel(NewTabPage::kHomePanel); chrome_test_util::VerifyAccessibilityForCurrentScreen(); } @@ -145,7 +145,7 @@ NSString* ntpOmniboxLabel = l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT); NSString* focusedOmniboxLabel = l10n_util::GetNSString(IDS_ACCNAME_LOCATION); - SelectNewTabPagePanel(NewTabPage::kMostVisitedPanel); + SelectNewTabPagePanel(NewTabPage::kHomePanel); AssertNTPScrolledToTop(NO); if (IsIPadIdiom()) { @@ -221,7 +221,7 @@ NSString* omniboxLabel = l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT); NSString* cancelLabel = l10n_util::GetNSString(IDS_CANCEL); if (IsIPadIdiom()) { - SelectNewTabPagePanel(NewTabPage::kMostVisitedPanel); + SelectNewTabPagePanel(NewTabPage::kHomePanel); } // Check that the NTP is in its normal state.
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_header_view.mm b/ios/chrome/browser/ui/ntp/new_tab_page_header_view.mm index 0381854..13e228c 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_header_view.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_header_view.mm
@@ -70,8 +70,8 @@ DCHECK(!_toolbarController); DCHECK(readingListModel); - _toolbarController = [[NewTabPageToolbarController alloc] init]; - [_toolbarController setDispatcher:dispatcher]; + _toolbarController = + [[NewTabPageToolbarController alloc] initWithDispatcher:dispatcher]; _toolbarController.readingListModel = readingListModel; UIView* toolbarView = [_toolbarController view];
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.h b/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.h index 8e90625..58533816 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.h +++ b/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.h
@@ -7,9 +7,10 @@ #import "ios/chrome/browser/ui/toolbar/toolbar_controller.h" +@protocol BrowserCommands; @protocol GoogleLandingDataSource; -@protocol UrlLoader; @protocol OmniboxFocuser; +@protocol UrlLoader; @protocol WebToolbarDelegate; // New tab page specific toolbar. The background view is hidden and the @@ -20,10 +21,13 @@ // Designated initializer. The underlying ToolbarController is initialized with // ToolbarControllerStyleLightMode. -- (instancetype)init; +- (instancetype)initWithDispatcher: + (id<BrowserCommands, OmniboxFocuser, UrlLoader, WebToolbarDelegate>) + dispatcher; -@property(nonatomic, weak) id<UrlLoader, OmniboxFocuser, WebToolbarDelegate> - dispatcher; +@property(nonatomic, readonly, weak) + id<BrowserCommands, OmniboxFocuser, UrlLoader, WebToolbarDelegate> + dispatcher; // |YES| if the toolbar can show the forward arrow. - (void)setCanGoForward:(BOOL)canGoForward;
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.mm index deeb6f8..7d601fa 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_toolbar_controller.mm
@@ -62,8 +62,11 @@ @synthesize canGoForward = _canGoForward; @synthesize canGoBack = _canGoBack; -- (instancetype)init { - self = [super initWithStyle:ToolbarControllerStyleLightMode]; +- (instancetype)initWithDispatcher: + (id<BrowserCommands, OmniboxFocuser, UrlLoader, WebToolbarDelegate>) + dispatcher { + self = [super initWithStyle:ToolbarControllerStyleLightMode + dispatcher:dispatcher]; if (self) { [self.backgroundView setHidden:YES]; @@ -125,13 +128,18 @@ initWithTarget:self action:@selector(handleLongPress:)]; [_backButton addGestureRecognizer:backLongPress]; + [_backButton addTarget:self.dispatcher + action:@selector(goBack) + forControlEvents:UIControlEventTouchUpInside]; + UILongPressGestureRecognizer* forwardLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; [_forwardButton addGestureRecognizer:forwardLongPress]; - [_backButton setTag:IDC_BACK]; - [_forwardButton setTag:IDC_FORWARD]; + [_forwardButton addTarget:self.dispatcher + action:@selector(goForward) + forControlEvents:UIControlEventTouchUpInside]; [_omniboxFocuser addTarget:self action:@selector(focusOmnibox:)
diff --git a/ios/chrome/browser/ui/ntp/resources/BUILD.gn b/ios/chrome/browser/ui/ntp/resources/BUILD.gn new file mode 100644 index 0000000..34e13c26 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/BUILD.gn
@@ -0,0 +1,314 @@ +# 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("//build/config/ios/imageset.gni") + +imageset("ntp_mv_thumbnail_container") { + sources = [ + "ntp_mv_thumbnail_container.imageset/Contents.json", + "ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container.png", + "ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@2x.png", + "ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@3x.png", + ] +} + +imageset("ntp_opentabs_last_row_h") { + sources = [ + "ntp_opentabs_last_row_h.imageset/Contents.json", + "ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h@2x~ipad.png", + "ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h~ipad.png", + ] +} + +imageset("ntp_opentabs_clock") { + sources = [ + "ntp_opentabs_clock.imageset/Contents.json", + "ntp_opentabs_clock.imageset/ntp_opentabs_clock.png", + "ntp_opentabs_clock.imageset/ntp_opentabs_clock@2x.png", + "ntp_opentabs_clock.imageset/ntp_opentabs_clock@3x.png", + ] +} + +imageset("ntp_opentabs_tablet") { + sources = [ + "ntp_opentabs_tablet.imageset/Contents.json", + "ntp_opentabs_tablet.imageset/ntp_opentabs_tablet.png", + "ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@2x.png", + "ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@3x.png", + ] +} + +imageset("ntp_opentabs_last_row") { + sources = [ + "ntp_opentabs_last_row.imageset/Contents.json", + "ntp_opentabs_last_row.imageset/ntp_opentabs_last_row@2x~ipad.png", + "ntp_opentabs_last_row.imageset/ntp_opentabs_last_row~ipad.png", + ] +} + +imageset("ntp_opentabs") { + sources = [ + "ntp_opentabs.imageset/Contents.json", + "ntp_opentabs.imageset/ntp_opentabs@2x.png", + "ntp_opentabs.imageset/ntp_opentabs@3x.png", + ] +} + +imageset("ntp_bookmarks") { + sources = [ + "ntp_bookmarks.imageset/Contents.json", + "ntp_bookmarks.imageset/ntp_bookmarks.png", + "ntp_bookmarks.imageset/ntp_bookmarks@2x.png", + "ntp_bookmarks.imageset/ntp_bookmarks@3x.png", + ] +} + +imageset("bookmarks_button_border") { + sources = [ + "bookmarks_button_border.imageset/Contents.json", + "bookmarks_button_border.imageset/bookmarks_button_border.png", + "bookmarks_button_border.imageset/bookmarks_button_border@2x.png", + ] +} + +imageset("bookmarks_bar_edit_pressed_moreshadow") { + sources = [ + "bookmarks_bar_edit_pressed_moreshadow.imageset/Contents.json", + "bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow.png", + "bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow@2x.png", + ] +} + +imageset("bookmarks_bar_edit_pressed") { + sources = [ + "bookmarks_bar_edit_pressed.imageset/Contents.json", + "bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed.png", + "bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x.png", + "bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x~ipad.png", + "bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed~ipad.png", + ] +} + +imageset("bookmarks_bar_breadcrumb") { + sources = [ + "bookmarks_bar_breadcrumb.imageset/Contents.json", + "bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb.png", + "bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x.png", + "bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x~ipad.png", + "bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb~ipad.png", + ] +} + +imageset("ntp_opentabs_header") { + sources = [ + "ntp_opentabs_header.imageset/Contents.json", + "ntp_opentabs_header.imageset/ntp_opentabs_header@2x~ipad.png", + "ntp_opentabs_header.imageset/ntp_opentabs_header~ipad.png", + ] +} + +imageset("bookmarks_bar_edit_moreshadow") { + sources = [ + "bookmarks_bar_edit_moreshadow.imageset/Contents.json", + "bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow.png", + "bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow@2x.png", + ] +} + +imageset("ntp_delete_button") { + sources = [ + "ntp_delete_button.imageset/Contents.json", + "ntp_delete_button.imageset/ntp_delete_button.png", + "ntp_delete_button.imageset/ntp_delete_button@2x.png", + ] +} + +imageset("ntp_opentabs_phone") { + sources = [ + "ntp_opentabs_phone.imageset/Contents.json", + "ntp_opentabs_phone.imageset/ntp_opentabs_phone.png", + "ntp_opentabs_phone.imageset/ntp_opentabs_phone@2x.png", + "ntp_opentabs_phone.imageset/ntp_opentabs_phone@3x.png", + ] +} + +imageset("ntp_mv_recentpress") { + sources = [ + "ntp_mv_recentpress.imageset/Contents.json", + "ntp_mv_recentpress.imageset/ntp_mv_recentpress@2x~ipad.png", + "ntp_mv_recentpress.imageset/ntp_mv_recentpress~ipad.png", + ] +} + +imageset("bookmarks_bar_left") { + sources = [ + "bookmarks_bar_left.imageset/Contents.json", + "bookmarks_bar_left.imageset/bookmarks_bar_left@2x~ipad.png", + "bookmarks_bar_left.imageset/bookmarks_bar_left~ipad.png", + ] +} + +imageset("ntp_opentabs_list_item_h") { + sources = [ + "ntp_opentabs_list_item_h.imageset/Contents.json", + "ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h@2x~ipad.png", + "ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h~ipad.png", + ] +} + +imageset("ntp_opentabs_list_item") { + sources = [ + "ntp_opentabs_list_item.imageset/Contents.json", + "ntp_opentabs_list_item.imageset/ntp_opentabs_list_item@2x~ipad.png", + "ntp_opentabs_list_item.imageset/ntp_opentabs_list_item~ipad.png", + ] +} + +imageset("disclosure_open") { + sources = [ + "disclosure_open.imageset/Contents.json", + "disclosure_open.imageset/disclosure_open.png", + "disclosure_open.imageset/disclosure_open@2x.png", + ] +} + +imageset("bookmarks_bar_edit") { + sources = [ + "bookmarks_bar_edit.imageset/Contents.json", + "bookmarks_bar_edit.imageset/bookmarks_bar_edit.png", + "bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x.png", + "bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x~ipad.png", + "bookmarks_bar_edit.imageset/bookmarks_bar_edit~ipad.png", + ] +} + +imageset("incognito_icon") { + sources = [ + "incognito_icon.imageset/Contents.json", + "incognito_icon.imageset/incognito_icon.png", + "incognito_icon.imageset/incognito_icon@2x.png", + "incognito_icon.imageset/incognito_icon@3x.png", + ] +} + +imageset("ntp_opentabs_recent_arrow") { + sources = [ + "ntp_opentabs_recent_arrow.imageset/Contents.json", + "ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow.png", + "ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@2x.png", + "ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@3x.png", + ] +} + +imageset("bookmarks_bar_bg") { + sources = [ + "bookmarks_bar_bg.imageset/Contents.json", + "bookmarks_bar_bg.imageset/bookmarks_bar_bg.png", + "bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x.png", + "bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x~ipad.png", + "bookmarks_bar_bg.imageset/bookmarks_bar_bg~ipad.png", + ] +} + +imageset("ntp_google_search_box") { + sources = [ + "ntp_google_search_box.imageset/Contents.json", + "ntp_google_search_box.imageset/ntp_google_search_box.png", + "ntp_google_search_box.imageset/ntp_google_search_box@2x.png", + "ntp_google_search_box.imageset/ntp_google_search_box@3x.png", + ] +} + +imageset("ntp_bottom_bar_shadow") { + sources = [ + "ntp_bottom_bar_shadow.imageset/Contents.json", + "ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow.png", + "ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow@2x.png", + ] +} + +imageset("ntp_opentabs_laptop") { + sources = [ + "ntp_opentabs_laptop.imageset/Contents.json", + "ntp_opentabs_laptop.imageset/ntp_opentabs_laptop.png", + "ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@2x.png", + "ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@3x.png", + ] +} + +imageset("ntp_mv_recentbar") { + sources = [ + "ntp_mv_recentbar.imageset/Contents.json", + "ntp_mv_recentbar.imageset/ntp_mv_recentbar@2x~ipad.png", + "ntp_mv_recentbar.imageset/ntp_mv_recentbar~ipad.png", + ] +} + +imageset("bookmarks_button_bg") { + sources = [ + "bookmarks_button_bg.imageset/Contents.json", + "bookmarks_button_bg.imageset/bookmarks_button_bg.png", + "bookmarks_button_bg.imageset/bookmarks_button_bg@2x.png", + ] +} + +imageset("ntp_mv_search") { + sources = [ + "ntp_mv_search.imageset/Contents.json", + "ntp_mv_search.imageset/ntp_mv_search.png", + "ntp_mv_search.imageset/ntp_mv_search@2x.png", + ] +} + +imageset("ntp_mv_placeholder_bg") { + sources = [ + "ntp_mv_placeholder_bg.imageset/Contents.json", + "ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg.png", + "ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@2x.png", + "ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@3x.png", + ] +} + +imageset("ntp_recently_closed") { + sources = [ + "ntp_recently_closed.imageset/Contents.json", + "ntp_recently_closed.imageset/ntp_recently_closed.png", + "ntp_recently_closed.imageset/ntp_recently_closed@2x.png", + "ntp_recently_closed.imageset/ntp_recently_closed@3x.png", + ] +} + +imageset("ntp_mv_thumbnail_empty") { + sources = [ + "ntp_mv_thumbnail_empty.imageset/Contents.json", + "ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty.png", + "ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x.png", + "ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x~ipad.png", + "ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty~ipad.png", + ] +} + +imageset("ntp_incognito") { + sources = [ + "ntp_incognito.imageset/Contents.json", + "ntp_incognito.imageset/ntp_incognito.png", + "ntp_incognito.imageset/ntp_incognito@2x.png", + ] +} + +imageset("ntp_mv_welcome_favicon") { + sources = [ + "ntp_mv_welcome_favicon.imageset/Contents.json", + "ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon.png", + "ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon@2x.png", + ] +} + +imageset("bookmarks_bar_bg_pressed") { + sources = [ + "bookmarks_bar_bg_pressed.imageset/Contents.json", + "bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed@2x~ipad.png", + "bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed~ipad.png", + ] +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/Contents.json new file mode 100644 index 0000000..608e023c --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/Contents.json
@@ -0,0 +1,28 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "bookmarks_bar_bg.png" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "bookmarks_bar_bg@2x.png" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_bg@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_bg~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg.imageset/bookmarks_bar_bg~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/Contents.json new file mode 100644 index 0000000..9ff186f --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_bg_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_bg_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_bg_pressed.imageset/bookmarks_bar_bg_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/Contents.json new file mode 100644 index 0000000..c4724fd --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/Contents.json
@@ -0,0 +1,28 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "bookmarks_bar_breadcrumb.png" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "bookmarks_bar_breadcrumb@2x.png" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_breadcrumb@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_breadcrumb~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_breadcrumb.imageset/bookmarks_bar_breadcrumb~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/Contents.json new file mode 100644 index 0000000..31b64cb --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/Contents.json
@@ -0,0 +1,28 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "bookmarks_bar_edit.png" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "bookmarks_bar_edit@2x.png" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_edit@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_edit~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit.imageset/bookmarks_bar_edit~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/Contents.json new file mode 100644 index 0000000..8991eb9b --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "bookmarks_bar_edit_moreshadow.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "bookmarks_bar_edit_moreshadow@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_moreshadow.imageset/bookmarks_bar_edit_moreshadow@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/Contents.json new file mode 100644 index 0000000..8107b44 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/Contents.json
@@ -0,0 +1,28 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "bookmarks_bar_edit_pressed.png" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "bookmarks_bar_edit_pressed@2x.png" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_edit_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_edit_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed.imageset/bookmarks_bar_edit_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/Contents.json new file mode 100644 index 0000000..23d486f --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "bookmarks_bar_edit_pressed_moreshadow.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "bookmarks_bar_edit_pressed_moreshadow@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_edit_pressed_moreshadow.imageset/bookmarks_bar_edit_pressed_moreshadow@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/Contents.json new file mode 100644 index 0000000..151f807 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "bookmarks_bar_left@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "bookmarks_bar_left~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/bookmarks_bar_left@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/bookmarks_bar_left@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left~ipad.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/bookmarks_bar_left~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left~ipad.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_bar_left.imageset/bookmarks_bar_left~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/Contents.json new file mode 100644 index 0000000..bc53e909 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "bookmarks_button_bg.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "bookmarks_button_bg@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/bookmarks_button_bg.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/bookmarks_button_bg.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/bookmarks_button_bg@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_button_bg.imageset/bookmarks_button_bg@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/Contents.json new file mode 100644 index 0000000..c948d99 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "bookmarks_button_border.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "bookmarks_button_border@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/bookmarks_button_border.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/bookmarks_button_border.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border@2x.png b/ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/bookmarks_button_border@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/bookmarks_button_border@2x.png rename to ios/chrome/browser/ui/ntp/resources/bookmarks_button_border.imageset/bookmarks_button_border@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/Contents.json new file mode 100644 index 0000000..c7cb532 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "disclosure_open.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "disclosure_open@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/disclosure_open.png b/ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/disclosure_open.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/disclosure_open.png rename to ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/disclosure_open.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/disclosure_open@2x.png b/ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/disclosure_open@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/disclosure_open@2x.png rename to ios/chrome/browser/ui/ntp/resources/disclosure_open.imageset/disclosure_open@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/Contents.json new file mode 100644 index 0000000..1b1a3794 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "incognito_icon.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "incognito_icon@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "incognito_icon@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/incognito_icon.png b/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/incognito_icon.png rename to ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/incognito_icon@2x.png b/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/incognito_icon@2x.png rename to ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/incognito_icon@3x.png b/ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/incognito_icon@3x.png rename to ios/chrome/browser/ui/ntp/resources/incognito_icon.imageset/incognito_icon@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/Contents.json new file mode 100644 index 0000000..7c7c6aa --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_bookmarks.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_bookmarks@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_bookmarks@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.png b/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.png rename to ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_bookmarks@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_bookmarks@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_bookmarks.imageset/ntp_bookmarks@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/Contents.json new file mode 100644 index 0000000..74d4477 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_bottom_bar_shadow.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_bottom_bar_shadow@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.png b/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.png rename to ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_bottom_bar_shadow.imageset/ntp_bottom_bar_shadow@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/Contents.json new file mode 100644 index 0000000..096916700 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_delete_button.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_delete_button@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.png b/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/ntp_delete_button.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_delete_button.png rename to ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/ntp_delete_button.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_delete_button@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/ntp_delete_button@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_delete_button@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_delete_button.imageset/ntp_delete_button@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/Contents.json new file mode 100644 index 0000000..0512e147 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_google_search_box.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_google_search_box@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_google_search_box@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.png b/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.png rename to ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_google_search_box@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_google_search_box@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_google_search_box.imageset/ntp_google_search_box@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/Contents.json new file mode 100644 index 0000000..30d3a84 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_incognito.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_incognito@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_incognito.png b/ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/ntp_incognito.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_incognito.png rename to ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/ntp_incognito.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_incognito@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/ntp_incognito@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_incognito@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_incognito.imageset/ntp_incognito@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/Contents.json new file mode 100644 index 0000000..e3b9fad --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_mv_placeholder_bg.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_mv_placeholder_bg@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_mv_placeholder_bg@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_placeholder_bg.imageset/ntp_mv_placeholder_bg@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/Contents.json new file mode 100644 index 0000000..39a30a6 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_mv_recentbar@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_mv_recentbar~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/ntp_mv_recentbar@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/ntp_mv_recentbar@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/ntp_mv_recentbar~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_recentbar.imageset/ntp_mv_recentbar~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/Contents.json new file mode 100644 index 0000000..4ed3786 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_mv_recentpress@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_mv_recentpress~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/ntp_mv_recentpress@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/ntp_mv_recentpress@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/ntp_mv_recentpress~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_recentpress.imageset/ntp_mv_recentpress~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/Contents.json new file mode 100644 index 0000000..593b5d0 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_mv_search.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_mv_search@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/ntp_mv_search.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_search.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/ntp_mv_search.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_search@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/ntp_mv_search@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_search@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_search.imageset/ntp_mv_search@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/Contents.json new file mode 100644 index 0000000..d00307c --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_mv_thumbnail_container.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_mv_thumbnail_container@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_mv_thumbnail_container@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_container.imageset/ntp_mv_thumbnail_container@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/Contents.json new file mode 100644 index 0000000..f913a1f --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/Contents.json
@@ -0,0 +1,28 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "ntp_mv_thumbnail_empty.png" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "ntp_mv_thumbnail_empty@2x.png" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_mv_thumbnail_empty@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_mv_thumbnail_empty~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_thumbnail_empty.imageset/ntp_mv_thumbnail_empty~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/Contents.json new file mode 100644 index 0000000..af8dde2 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_mv_welcome_favicon.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_mv_welcome_favicon@2x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_mv_welcome_favicon.imageset/ntp_mv_welcome_favicon@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/Contents.json new file mode 100644 index 0000000..6bcff21d --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/ntp_opentabs@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/ntp_opentabs@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/ntp_opentabs@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs.imageset/ntp_opentabs@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/Contents.json new file mode 100644 index 0000000..97fa1cc7 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_opentabs_clock.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs_clock@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs_clock@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_clock.imageset/ntp_opentabs_clock@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/Contents.json new file mode 100644 index 0000000..0a75826 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_opentabs_header@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_opentabs_header~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/ntp_opentabs_header@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/ntp_opentabs_header@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/ntp_opentabs_header~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_header.imageset/ntp_opentabs_header~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/Contents.json new file mode 100644 index 0000000..3c7a06f --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_opentabs_laptop.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs_laptop@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs_laptop@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_laptop.imageset/ntp_opentabs_laptop@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/Contents.json new file mode 100644 index 0000000..9aef9de5 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_opentabs_last_row@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_opentabs_last_row~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/ntp_opentabs_last_row@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/ntp_opentabs_last_row@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/ntp_opentabs_last_row~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row.imageset/ntp_opentabs_last_row~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/Contents.json new file mode 100644 index 0000000..e389ef0b --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_opentabs_last_row_h@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_opentabs_last_row_h~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_last_row_h.imageset/ntp_opentabs_last_row_h~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/Contents.json new file mode 100644 index 0000000..0c1f5ce1 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_opentabs_list_item@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_opentabs_list_item~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/ntp_opentabs_list_item@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/ntp_opentabs_list_item@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/ntp_opentabs_list_item~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item.imageset/ntp_opentabs_list_item~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/Contents.json new file mode 100644 index 0000000..e81806c --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "ntp_opentabs_list_item_h@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "ntp_opentabs_list_item_h~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h@2x~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h@2x~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h~ipad.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h~ipad.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h~ipad.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_list_item_h.imageset/ntp_opentabs_list_item_h~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/Contents.json new file mode 100644 index 0000000..b224bd2 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_opentabs_phone.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs_phone@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs_phone@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_phone.imageset/ntp_opentabs_phone@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/Contents.json new file mode 100644 index 0000000..01eaa95d --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_opentabs_recent_arrow.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs_recent_arrow@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs_recent_arrow@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_recent_arrow.imageset/ntp_opentabs_recent_arrow@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/Contents.json new file mode 100644 index 0000000..ad77de9 --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_opentabs_tablet.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_opentabs_tablet@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_opentabs_tablet@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_opentabs_tablet.imageset/ntp_opentabs_tablet@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/Contents.json b/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/Contents.json new file mode 100644 index 0000000..d0f035cd --- /dev/null +++ b/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "ntp_recently_closed.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "ntp_recently_closed@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "ntp_recently_closed@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.png b/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.png rename to ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed@2x.png b/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed@2x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_recently_closed@2x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed@3x.png b/ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed@3x.png similarity index 100% rename from ios/chrome/browser/ui/ntp/resources/ntp_recently_closed@3x.png rename to ios/chrome/browser/ui/ntp/resources/ntp_recently_closed.imageset/ntp_recently_closed@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/omnibox_perftest.mm b/ios/chrome/browser/ui/omnibox_perftest.mm index 66538de..3f76fa3 100644 --- a/ios/chrome/browser/ui/omnibox_perftest.mm +++ b/ios/chrome/browser/ui/omnibox_perftest.mm
@@ -107,7 +107,8 @@ initWithDelegate:webToolbarDelegate urlLoader:urlLoader browserState:chrome_browser_state_.get() - preloadProvider:nil]; + preloadProvider:nil + dispatcher:nil]; UIView* toolbarView = [toolbar_ view]; CGRect toolbarFrame = toolbarView.frame; toolbarFrame.origin = CGPointZero;
diff --git a/ios/chrome/browser/ui/payments/address_edit_coordinator.h b/ios/chrome/browser/ui/payments/address_edit_coordinator.h index f6f8a3b6..a09a469 100644 --- a/ios/chrome/browser/ui/payments/address_edit_coordinator.h +++ b/ios/chrome/browser/ui/payments/address_edit_coordinator.h
@@ -13,7 +13,9 @@ class AutofillProfile; } // namespace autofill +namespace payments { class PaymentRequest; +} // namespace payments @class AddressEditCoordinator; @@ -48,7 +50,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This pointer is not // owned by this class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user returns or finishes creating or // editing an address.
diff --git a/ios/chrome/browser/ui/payments/address_edit_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/address_edit_coordinator_unittest.mm index bc7aa98..3e44150 100644 --- a/ios/chrome/browser/ui/payments/address_edit_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/address_edit_coordinator_unittest.mm
@@ -50,11 +50,12 @@ MOCK_METHOD1(Invalidate, void(const autofill::AutofillProfile&)); }; -class MockTestPaymentRequest : public TestPaymentRequest { +class MockTestPaymentRequest : public payments::TestPaymentRequest { public: MockTestPaymentRequest(web::PaymentRequest web_payment_request, autofill::PersonalDataManager* personal_data_manager) - : TestPaymentRequest(web_payment_request, personal_data_manager) {} + : payments::TestPaymentRequest(web_payment_request, + personal_data_manager) {} MOCK_METHOD1(AddAutofillProfile, autofill::AutofillProfile*(const autofill::AutofillProfile&)); };
diff --git a/ios/chrome/browser/ui/payments/address_edit_mediator.h b/ios/chrome/browser/ui/payments/address_edit_mediator.h index 84cad80..1c41d9d 100644 --- a/ios/chrome/browser/ui/payments/address_edit_mediator.h +++ b/ios/chrome/browser/ui/payments/address_edit_mediator.h
@@ -8,13 +8,16 @@ #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller_data_source.h" #import "ios/chrome/browser/ui/payments/region_data_loader.h" -class PaymentRequest; @protocol PaymentRequestEditConsumer; namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + // Serves as data source for AddressEditViewController. @interface AddressEditMediator : NSObject<PaymentRequestEditViewControllerDataSource, @@ -34,7 +37,7 @@ // of web::PaymentRequest as provided by the page invoking the Payment Request // API as well as |address| which is the address to be edited, if any. // This object will not take ownership of |paymentRequest| or |address|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest address:(autofill::AutofillProfile*)address NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/payments/address_edit_mediator.mm b/ios/chrome/browser/ui/payments/address_edit_mediator.mm index 0ee0c5e1..1590f90 100644 --- a/ios/chrome/browser/ui/payments/address_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/address_edit_mediator.mm
@@ -44,7 +44,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The address to be edited, if any. This pointer is not owned by this class and // should outlive it. @@ -76,7 +76,7 @@ @synthesize fields = _fields; @synthesize regionField = _regionField; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest address:(autofill::AutofillProfile*)address { self = [super init]; if (self) {
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h b/ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h index 5238cd3..4d49fd6 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h +++ b/ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h
@@ -11,12 +11,14 @@ #import "ios/chrome/browser/ui/payments/address_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller.h" -class PaymentRequest; - namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + @class BillingAddressSelectionCoordinator; // Delegate protocol for BillingAddressSelectionCoordinator. @@ -48,7 +50,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects a billing address or // returns without selecting one.
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/billing_address_selection_coordinator_unittest.mm index 1daeba1..d7fb8e70 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/billing_address_selection_coordinator_unittest.mm
@@ -44,7 +44,7 @@ autofill::AutofillType(autofill::PHONE_HOME_WHOLE_NUMBER), base::string16(), "en-US"); personal_data_manager_.AddTestingProfile(&autofill_profile2_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); @@ -82,7 +82,7 @@ std::unique_ptr<PrefService> pref_service_; autofill::TestPersonalDataManager personal_data_manager_; autofill::TestRegionDataLoader test_region_data_loader_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.h b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.h index 4c975ee..c696ac3 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.h +++ b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.h
@@ -7,12 +7,14 @@ #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" -class PaymentRequest; - namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + // Serves as data source for PaymentRequestSelectorViewController. @interface BillingAddressSelectionMediator : NSObject<PaymentRequestSelectorViewControllerDataSource> @@ -30,7 +32,7 @@ // of web::PaymentRequest as provided by the page invoking the Payment Request // API as well as the selected billing profile. This object will not take // ownership of |paymentRequest| or |selectedBillingProfile|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest selectedBillingProfile: (autofill::AutofillProfile*)selectedBillingProfile NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm index 6007b41a..62df00f 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/billing_address_selection_mediator.mm
@@ -34,7 +34,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The selected billing address, if any. @property(nonatomic, assign) autofill::AutofillProfile* selectedBillingProfile; @@ -52,7 +52,7 @@ @synthesize selectedBillingProfile = _selectedBillingProfile; @synthesize items = _items; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest selectedBillingProfile: (autofill::AutofillProfile*)selectedBillingProfile { self = [super init];
diff --git a/ios/chrome/browser/ui/payments/billing_address_selection_mediator_unittest.mm b/ios/chrome/browser/ui/payments/billing_address_selection_mediator_unittest.mm index 6a6829df..988a417 100644 --- a/ios/chrome/browser/ui/payments/billing_address_selection_mediator_unittest.mm +++ b/ios/chrome/browser/ui/payments/billing_address_selection_mediator_unittest.mm
@@ -51,7 +51,7 @@ personal_data_manager_.AddTestingProfile(&autofill_profile_2_); personal_data_manager_.AddTestingProfile(&autofill_profile_3_); personal_data_manager_.AddTestingProfile(&autofill_profile_4_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); profile_comparator_ = base::MakeUnique<FakePaymentsProfileComparator>( @@ -77,7 +77,7 @@ autofill::AutofillProfile autofill_profile_3_; autofill::AutofillProfile autofill_profile_4_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; std::unique_ptr<FakePaymentsProfileComparator> profile_comparator_; };
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h b/ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h index b9fb1382..aac37af 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h +++ b/ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h
@@ -12,7 +12,9 @@ class AutofillProfile; } // namespace autofill +namespace payments { class PaymentRequest; +} // namespace payments @class ContactInfoEditCoordinator; @@ -47,7 +49,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This pointer is not // owned by this class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user returns or finishes creating or // editing a profile.
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/contact_info_edit_coordinator_unittest.mm index 66f92fbe..95adbe5 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/contact_info_edit_coordinator_unittest.mm
@@ -49,11 +49,12 @@ MOCK_METHOD1(Invalidate, void(const autofill::AutofillProfile&)); }; -class MockTestPaymentRequest : public TestPaymentRequest { +class MockTestPaymentRequest : public payments::TestPaymentRequest { public: MockTestPaymentRequest(web::PaymentRequest web_payment_request, autofill::PersonalDataManager* personal_data_manager) - : TestPaymentRequest(web_payment_request, personal_data_manager) {} + : payments::TestPaymentRequest(web_payment_request, + personal_data_manager) {} MOCK_METHOD1(AddAutofillProfile, autofill::AutofillProfile*(const autofill::AutofillProfile&)); };
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.h b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.h index c5824719..9192be9 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.h +++ b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.h
@@ -9,13 +9,16 @@ #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller_data_source.h" -class PaymentRequest; @protocol PaymentRequestEditConsumer; namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + // Serves as data source for AddressEditViewController. @interface ContactInfoEditMediator : NSObject<PaymentRequestEditViewControllerDataSource> @@ -28,7 +31,7 @@ // of web::PaymentRequest as provided by the page invoking the Payment Request // API as well as |profile| which is the profile to be edited, if any. // This object will not take ownership of |paymentRequest| or |profile|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest profile:(autofill::AutofillProfile*)profile NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm index 0649a8b..70a210f 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/contact_info_edit_mediator.mm
@@ -28,7 +28,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The profile to be edited, if any. This pointer is not owned by this class and // should outlive it. @@ -47,7 +47,7 @@ @synthesize profile = _profile; @synthesize fields = _fields; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest profile:(autofill::AutofillProfile*)profile { self = [super init]; if (self) {
diff --git a/ios/chrome/browser/ui/payments/contact_info_edit_mediator_unittest.mm b/ios/chrome/browser/ui/payments/contact_info_edit_mediator_unittest.mm index 3995ef8..8439a02 100644 --- a/ios/chrome/browser/ui/payments/contact_info_edit_mediator_unittest.mm +++ b/ios/chrome/browser/ui/payments/contact_info_edit_mediator_unittest.mm
@@ -29,14 +29,14 @@ class PaymentRequestContactInfoEditMediatorTest : public PlatformTest { protected: PaymentRequestContactInfoEditMediatorTest() - : payment_request_(base::MakeUnique<TestPaymentRequest>( + : payment_request_(base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_)) {} base::test::ScopedTaskEnvironment scoped_task_evironment_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that the expected editor fields are created when creating a profile.
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_coordinator.h b/ios/chrome/browser/ui/payments/contact_info_selection_coordinator.h index 5c0541c..f3faf5a 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_coordinator.h +++ b/ios/chrome/browser/ui/payments/contact_info_selection_coordinator.h
@@ -12,12 +12,14 @@ #import "ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller.h" -class PaymentRequest; - namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + @class ContactInfoSelectionCoordinator; // Delegate protocol for ContactInfoSelectionCoordinator. @@ -45,7 +47,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects a contact profile or // returns without selecting one.
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/contact_info_selection_coordinator_unittest.mm index 3e63def..4957c513 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/contact_info_selection_coordinator_unittest.mm
@@ -32,7 +32,7 @@ // Add testing profiles to autofill::TestPersonalDataManager. personal_data_manager_.AddTestingProfile(&autofill_profile_1_); personal_data_manager_.AddTestingProfile(&autofill_profile_2_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); } @@ -42,7 +42,7 @@ autofill::AutofillProfile autofill_profile_1_; autofill::AutofillProfile autofill_profile_2_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.h b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.h index 9577b80..3d6ea32 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.h +++ b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // Serves as data source for PaymentRequestSelectorViewController. @interface ContactInfoSelectionMediator @@ -25,7 +27,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm index ebf3fa4f..a0394d32 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/contact_info_selection_mediator.mm
@@ -32,7 +32,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The selectable items to display in the collection. @property(nonatomic, strong) NSMutableArray<AutofillProfileItem*>* items; @@ -46,7 +46,8 @@ @synthesize paymentRequest = _paymentRequest; @synthesize items = _items; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest;
diff --git a/ios/chrome/browser/ui/payments/contact_info_selection_mediator_unittest.mm b/ios/chrome/browser/ui/payments/contact_info_selection_mediator_unittest.mm index b267333c..de1506b 100644 --- a/ios/chrome/browser/ui/payments/contact_info_selection_mediator_unittest.mm +++ b/ios/chrome/browser/ui/payments/contact_info_selection_mediator_unittest.mm
@@ -36,7 +36,7 @@ // Add testing profiles to autofill::TestPersonalDataManager. personal_data_manager_.AddTestingProfile(&autofill_profile_1_); personal_data_manager_.AddTestingProfile(&autofill_profile_2_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); // Override the selected contact profile. @@ -58,7 +58,7 @@ autofill::AutofillProfile autofill_profile_1_; autofill::AutofillProfile autofill_profile_2_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that the expected selectable items are created and that the index of
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h index 3797cb9..a499ad9 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h +++ b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h
@@ -10,11 +10,13 @@ #import "ios/chrome/browser/ui/payments/billing_address_selection_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller.h" -namespace autofill { -class CreditCard; -} // namespace autofill +namespace payments { +class AutofillPaymentInstrument; +} +namespace payments { class PaymentRequest; +} // namespace payments @class CreditCardEditCoordinator; @@ -22,11 +24,12 @@ @protocol CreditCardEditCoordinatorDelegate<NSObject> // Notifies the delegate that the user has finished editing or creating -// |creditCard|. |creditCard| will be a new credit card owned by the -// PaymentRequest object if no credit card instance was provided to the +// |paymentMethod|. |paymentMethod| will be a new payment method owned by the +// PaymentRequest object if no payment method instance was provided to the // coordinator. Otherwise, it will be the same edited instance. - (void)creditCardEditCoordinator:(CreditCardEditCoordinator*)coordinator - didFinishEditingCreditCard:(autofill::CreditCard*)creditCard; + didFinishEditingPaymentMethod: + (payments::AutofillPaymentInstrument*)paymentMethod; // Notifies the delegate that the user has chosen to cancel editing or creating // a credit card and return to the previous screen. @@ -44,14 +47,14 @@ PaymentRequestEditViewControllerDelegate, PaymentRequestEditViewControllerValidator> -// The credit card to be edited, if any. This pointer is not owned by this class -// and should outlive it. -@property(nonatomic, assign) autofill::CreditCard* creditCard; +// The payment method to be edited, if any. This pointer is not owned by this +// class and should outlive it. +@property(nonatomic, assign) payments::AutofillPaymentInstrument* paymentMethod; // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This pointer is not // owned by this class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user returns or finishes creating or // editing a credit card.
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.mm b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.mm index b31867e..a84724d9 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.mm +++ b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator.mm
@@ -15,6 +15,8 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #import "components/autofill/ios/browser/credit_card_util.h" +#include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/payment_instrument.h" #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/payments/payment_request.h" @@ -36,7 +38,7 @@ // |error_message| can't be null and will be filled with the appropriate error // message iff the return value is false. bool IsValidCreditCardNumber(const base::string16& card_number, - PaymentRequest* payment_request, + payments::PaymentRequest* payment_request, const autofill::CreditCard* credit_card_to_edit, base::string16* error_message) { std::set<std::string> supported_card_networks( @@ -69,6 +71,8 @@ @interface CreditCardEditCoordinator () +@property(nonatomic, assign) autofill::CreditCard* creditCard; + @property(nonatomic, strong) BillingAddressSelectionCoordinator* billingAddressSelectionCoordinator; @@ -85,9 +89,10 @@ @implementation CreditCardEditCoordinator -@synthesize creditCard = _creditCard; +@synthesize paymentMethod = _paymentMethod; @synthesize paymentRequest = _paymentRequest; @synthesize delegate = _delegate; +@synthesize creditCard = _creditCard; @synthesize billingAddressSelectionCoordinator = _billingAddressSelectionCoordinator; @synthesize addressEditCoordinator = _addressEditCoordinator; @@ -96,6 +101,8 @@ @synthesize mediator = _mediator; - (void)start { + _creditCard = _paymentMethod ? _paymentMethod->credit_card() : nil; + _editViewController = [[PaymentRequestEditViewController alloc] init]; // TODO(crbug.com/602666): Title varies depending on the missing fields. NSString* title = _creditCard @@ -238,8 +245,8 @@ if (saveCreditCard) _paymentRequest->GetPersonalDataManager()->AddCreditCard(creditCard); - // Add the credit card to the list of credit cards in |_paymentRequest|. - _creditCard = _paymentRequest->AddCreditCard(creditCard); + // Add the credit card to the list of payment methods in |_paymentRequest|. + _paymentMethod = _paymentRequest->AddAutofillPaymentInstrument(creditCard); } else { // Override the origin. creditCard.set_origin(autofill::kSettingsOrigin); @@ -257,7 +264,7 @@ } [_delegate creditCardEditCoordinator:self - didFinishEditingCreditCard:_creditCard]; + didFinishEditingPaymentMethod:_paymentMethod]; } - (void)paymentRequestEditViewControllerDidCancel:
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator_unittest.mm index 282645f0..73e990b 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/credit_card_edit_coordinator_unittest.mm
@@ -12,6 +12,8 @@ #include "base/test/scoped_task_environment.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/payment_instrument.h" #include "ios/chrome/browser/payments/payment_request_test_util.h" #include "ios/chrome/browser/payments/test_payment_request.h" #import "ios/chrome/browser/ui/autofill/autofill_ui_type.h" @@ -35,13 +37,15 @@ MOCK_METHOD1(UpdateCreditCard, void(const autofill::CreditCard&)); }; -class MockPaymentRequest : public TestPaymentRequest { +class MockPaymentRequest : public payments::TestPaymentRequest { public: MockPaymentRequest(web::PaymentRequest web_payment_request, autofill::PersonalDataManager* personal_data_manager) - : TestPaymentRequest(web_payment_request, personal_data_manager) {} - MOCK_METHOD1(AddCreditCard, - autofill::CreditCard*(const autofill::CreditCard&)); + : payments::TestPaymentRequest(web_payment_request, + personal_data_manager) {} + MOCK_METHOD1( + AddAutofillPaymentInstrument, + payments::AutofillPaymentInstrument*(const autofill::CreditCard&)); }; MATCHER_P5(CreditCardMatches, @@ -151,10 +155,10 @@ } // Tests that calling the view controller delegate method which signals that the -// user has finished creating a new credit card, causes the credit card to be -// added to the PaymentRequest instance and the corresponding coordinator -// delegate method to get called. The new credit card is expected to get added -// to the PersonalDataManager if user chooses to save it locally. +// user has finished creating a new payment method, causes the payment method to +// be added to the PaymentRequest instance and the corresponding coordinator +// delegate method to get called. The new payment method is expected to get +// added to the PersonalDataManager if user chooses to save it locally. TEST_F(PaymentRequestCreditCardEditCoordinatorTest, DidFinishCreatingWithSave) { UIViewController* base_view_controller = [[UIViewController alloc] init]; ScopedKeyWindow scoped_key_window_; @@ -168,9 +172,10 @@ id delegate = [OCMockObject mockForProtocol:@protocol(CreditCardEditCoordinatorDelegate)]; [[delegate expect] - creditCardEditCoordinator:coordinator - didFinishEditingCreditCard:static_cast<autofill::CreditCard*>( - [OCMArg anyPointer])]; + creditCardEditCoordinator:coordinator + didFinishEditingPaymentMethod:static_cast< + payments::AutofillPaymentInstrument*>( + [OCMArg anyPointer])]; [coordinator setDelegate:delegate]; EXPECT_EQ(nil, base_view_controller.presentedViewController); @@ -180,17 +185,17 @@ base::test::ios::SpinRunLoopWithMaxDelay(base::TimeDelta::FromSecondsD(1.0)); EXPECT_NE(nil, base_view_controller.presentedViewController); - // Expect a credit card to be added to the PaymentRequest. + // Expect a payment method to be added to the PaymentRequest. EXPECT_CALL(*payment_request_, - AddCreditCard(CreditCardMatches("4111111111111111", "John Doe", - "12", "2090", "12345"))) + AddAutofillPaymentInstrument(CreditCardMatches( + "4111111111111111", "John Doe", "12", "2090", "12345"))) .Times(1); - // Expect a credit card to be added to the PersonalDataManager. + // Expect a payment method to be added to the PersonalDataManager. EXPECT_CALL(personal_data_manager_, AddCreditCard(CreditCardMatches("4111111111111111", "John Doe", "12", "2090", "12345"))) .Times(1); - // No credit card should get updated in the PersonalDataManager. + // No payment method should get updated in the PersonalDataManager. EXPECT_CALL(personal_data_manager_, UpdateCreditCard(_)).Times(0); // Call the controller delegate method. @@ -209,9 +214,9 @@ } // Tests that calling the view controller delegate method which signals that the -// user has finished creating a new credit card, causes the credit card to be -// added to the PaymentRequest instance and the corresponding coordinator -// delegate method to get called. The new credit card should not get added to +// user has finished creating a new payment method, causes the payment method to +// be added to the PaymentRequest instance and the corresponding coordinator +// delegate method to get called. The new payment method should not get added to // the PersonalDataManager if user chooses to not to save it locally. TEST_F(PaymentRequestCreditCardEditCoordinatorTest, DidFinishCreatingNoSave) { UIViewController* base_view_controller = [[UIViewController alloc] init]; @@ -226,9 +231,10 @@ id delegate = [OCMockObject mockForProtocol:@protocol(CreditCardEditCoordinatorDelegate)]; [[delegate expect] - creditCardEditCoordinator:coordinator - didFinishEditingCreditCard:static_cast<autofill::CreditCard*>( - [OCMArg anyPointer])]; + creditCardEditCoordinator:coordinator + didFinishEditingPaymentMethod:static_cast< + payments::AutofillPaymentInstrument*>( + [OCMArg anyPointer])]; [coordinator setDelegate:delegate]; EXPECT_EQ(nil, base_view_controller.presentedViewController); @@ -238,14 +244,14 @@ base::test::ios::SpinRunLoopWithMaxDelay(base::TimeDelta::FromSecondsD(1.0)); EXPECT_NE(nil, base_view_controller.presentedViewController); - // Expect a credit card to be added to the PaymentRequest. + // Expect a payment method to be added to the PaymentRequest. EXPECT_CALL(*payment_request_, - AddCreditCard(CreditCardMatches("4111111111111111", "John Doe", - "12", "2090", "12345"))) + AddAutofillPaymentInstrument(CreditCardMatches( + "4111111111111111", "John Doe", "12", "2090", "12345"))) .Times(1); - // No credit card should get added to the PersonalDataManager. + // No payment method should get added to the PersonalDataManager. EXPECT_CALL(personal_data_manager_, AddCreditCard(_)).Times(0); - // No credit card should get updated in the PersonalDataManager. + // No payment method should get updated in the PersonalDataManager. EXPECT_CALL(personal_data_manager_, UpdateCreditCard(_)).Times(0); // Call the controller delegate method. @@ -264,9 +270,9 @@ } // Tests that calling the view controller delegate method which signals that the -// user has finished editing a credit card, causes the corresponding coordinator -// delegate method to get called. The credit card should not get re-added to the -// PaymentRequest nor the PersonalDataManager. +// user has finished editing a payment method, causes the corresponding +// coordinator delegate method to get called. The payment method should not get +// re-added to the PaymentRequest nor the PersonalDataManager. TEST_F(PaymentRequestCreditCardEditCoordinatorTest, DidFinishEditing) { UIViewController* base_view_controller = [[UIViewController alloc] init]; ScopedKeyWindow scoped_key_window_; @@ -276,17 +282,20 @@ initWithBaseViewController:base_view_controller]; [coordinator setPaymentRequest:payment_request_.get()]; - // Set the credit card to be edited. + // Set the payment method to be edited. autofill::CreditCard credit_card; - [coordinator setCreditCard:&credit_card]; + payments::AutofillPaymentInstrument payment_method( + "", credit_card, false, payment_request_->billing_profiles(), "", nil); + [coordinator setPaymentMethod:&payment_method]; // Mock the coordinator delegate. id delegate = [OCMockObject mockForProtocol:@protocol(CreditCardEditCoordinatorDelegate)]; [[delegate expect] - creditCardEditCoordinator:coordinator - didFinishEditingCreditCard:static_cast<autofill::CreditCard*>( - [OCMArg anyPointer])]; + creditCardEditCoordinator:coordinator + didFinishEditingPaymentMethod:static_cast< + payments::AutofillPaymentInstrument*>( + [OCMArg anyPointer])]; [coordinator setDelegate:delegate]; EXPECT_EQ(nil, base_view_controller.presentedViewController); @@ -296,11 +305,11 @@ base::test::ios::SpinRunLoopWithMaxDelay(base::TimeDelta::FromSecondsD(1.0)); EXPECT_NE(nil, base_view_controller.presentedViewController); - // No credit card should get added to the PaymentRequest. - EXPECT_CALL(*payment_request_, AddCreditCard(_)).Times(0); - // No credit card should get added to the PersonalDataManager. + // No payment method should get added to the PaymentRequest. + EXPECT_CALL(*payment_request_, AddAutofillPaymentInstrument(_)).Times(0); + // No payment method should get added to the PersonalDataManager. EXPECT_CALL(personal_data_manager_, AddCreditCard(_)).Times(0); - // Expect a credit card to be updated in the PersonalDataManager. + // Expect a payment method to be updated in the PersonalDataManager. EXPECT_CALL(personal_data_manager_, UpdateCreditCard(CreditCardMatches("4111111111111111", "John Doe", "12", "2090", "12345"))) @@ -322,7 +331,7 @@ } // Tests that calling the view controller delegate method which signals that the -// user has chosen to cancel creating/editing a credit card, causes the +// user has chosen to cancel creating/editing a payment method, causes the // corresponding coordinator delegate method to get called. TEST_F(PaymentRequestCreditCardEditCoordinatorTest, DidCancel) { UIViewController* base_view_controller = [[UIViewController alloc] init];
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.h b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.h index 0bdf723b..5e6bedd 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.h +++ b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.h
@@ -7,7 +7,6 @@ #import "ios/chrome/browser/ui/payments/payment_request_edit_view_controller_data_source.h" -class PaymentRequest; @protocol PaymentRequestEditConsumer; namespace autofill { @@ -15,6 +14,10 @@ class CreditCard; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + // Serves as data source for CreditCardEditViewController. @interface CreditCardEditViewControllerMediator : NSObject<PaymentRequestEditViewControllerDataSource> @@ -30,7 +33,7 @@ // of web::PaymentRequest as provided by the page invoking the Payment Request // API as well as |creditCard| which is the credit card to be edited, if any. // This object will not take ownership of |paymentRequest| or |creditCard|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest creditCard:(autofill::CreditCard*)creditCard NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm index b03947d..6d6c970 100644 --- a/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm +++ b/ios/chrome/browser/ui/payments/credit_card_edit_mediator.mm
@@ -39,7 +39,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The credit card to be edited, if any. This pointer is not owned by this class // and should outlive it. @@ -68,7 +68,7 @@ @synthesize fieldsMap = _fieldsMap; @synthesize creditCardExpDateField = _creditCardExpDateField; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest creditCard:(autofill::CreditCard*)creditCard { self = [super init]; if (self) {
diff --git a/ios/chrome/browser/ui/payments/full_card_requester.h b/ios/chrome/browser/ui/payments/full_card_requester.h index ea6f1a0..c6092c7 100644 --- a/ios/chrome/browser/ui/payments/full_card_requester.h +++ b/ios/chrome/browser/ui/payments/full_card_requester.h
@@ -5,14 +5,16 @@ #ifndef IOS_CHROME_BROWSER_UI_PAYMENTS_FULL_CARD_REQUESTER_H_ #define IOS_CHROME_BROWSER_UI_PAYMENTS_FULL_CARD_REQUESTER_H_ +#include <string> + #import <UIKit/UIKit.h> #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/strings/string16.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/payments/full_card_request.h" #include "components/autofill/core/browser/ui/card_unmask_prompt_controller_impl.h" +#include "components/payments/core/payment_instrument.h" namespace autofill { class AutofillManager; @@ -25,19 +27,17 @@ @protocol FullCardRequesterConsumer -// Called when a credit card has been successfully unmasked. Note that |card| -// may be different from what passed to GetFullCard method of FullCardRequester, -// because CVC unmasking process may update the credit card number and -// expiration date. -- (void)fullCardRequestDidSucceedWithCard:(const autofill::CreditCard&)card - verificationCode: - (const base::string16&)verificationCode; +// Called when a credit card has been successfully unmasked. Should be +// called wth method name (e.g., "visa") and json-serialized details. +- (void)fullCardRequestDidSucceedWithMethodName:(const std::string&)methodName + stringifiedDetails: + (const std::string&)stringifiedDetails; @end // Receives the full credit card details. Also displays the unmask prompt UI. class FullCardRequester - : public autofill::payments::FullCardRequest::ResultDelegate, + : public payments::PaymentInstrument::Delegate, public autofill::payments::FullCardRequest::UIDelegate, public base::SupportsWeakPtr<FullCardRequester> { public: @@ -45,14 +45,17 @@ UIViewController* base_view_controller, ios::ChromeBrowserState* browser_state); - void GetFullCard(autofill::CreditCard* card, - autofill::AutofillManager* autofill_manager); - - // payments::FullCardRequest::ResultDelegate: - void OnFullCardRequestSucceeded( + void GetFullCard( const autofill::CreditCard& card, - const base::string16& verificationCode) override; - void OnFullCardRequestFailed() override; + autofill::AutofillManager* autofill_manager, + base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate> + result_delegate); + + // payments::PaymentInstrument::Delegate: + void OnInstrumentDetailsReady( + const std::string& method_name, + const std::string& stringified_details) override; + void OnInstrumentDetailsError() override{}; // payments::FullCardRequest::UIDelegate: void ShowUnmaskPrompt(
diff --git a/ios/chrome/browser/ui/payments/full_card_requester.mm b/ios/chrome/browser/ui/payments/full_card_requester.mm index 74cc6e4..55e0995 100644 --- a/ios/chrome/browser/ui/payments/full_card_requester.mm +++ b/ios/chrome/browser/ui/payments/full_card_requester.mm
@@ -51,27 +51,22 @@ browser_state->IsOffTheRecord()) {} void FullCardRequester::GetFullCard( - autofill::CreditCard* card, - autofill::AutofillManager* autofill_manager) { - DCHECK(card); - DCHECK(autofill_manager); - autofill_manager->GetOrCreateFullCardRequest()->GetFullCard( - *card, autofill::AutofillClient::UNMASK_FOR_PAYMENT_REQUEST, AsWeakPtr(), - AsWeakPtr()); -} - -void FullCardRequester::OnFullCardRequestSucceeded( const autofill::CreditCard& card, - const base::string16& verificationCode) { - [consumer_ fullCardRequestDidSucceedWithCard:card - verificationCode:verificationCode]; + autofill::AutofillManager* autofill_manager, + base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate> + result_delegate) { + DCHECK(autofill_manager); + DCHECK(result_delegate); + autofill_manager->GetOrCreateFullCardRequest()->GetFullCard( + card, autofill::AutofillClient::UNMASK_FOR_PAYMENT_REQUEST, + result_delegate, AsWeakPtr()); } -void FullCardRequester::OnFullCardRequestFailed() { - // No action is required here. PRCardUnmaskPromptViewBridge manages its own - // life cycle. When the prompt is explicitly dismissed via tapping the close - // button (either in presence or absence of an error), the unmask prompt - // dialog pops itself and the user is back to the Payment Request UI. +void FullCardRequester::OnInstrumentDetailsReady( + const std::string& method_name, + const std::string& stringified_details) { + [consumer_ fullCardRequestDidSucceedWithMethodName:method_name + stringifiedDetails:stringified_details]; } void FullCardRequester::ShowUnmaskPrompt(
diff --git a/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm b/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm index 13de877..d84f5e08 100644 --- a/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm +++ b/ios/chrome/browser/ui/payments/full_card_requester_unittest.mm
@@ -4,6 +4,10 @@ #import "ios/chrome/browser/ui/payments/full_card_requester.h" +#include <string> + +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" #include "base/logging.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" @@ -12,6 +16,9 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/ios/browser/autofill_driver_ios.h" +#include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/basic_card_response.h" +#include "components/payments/core/payment_request_data_util.h" #import "ios/chrome/browser/autofill/autofill_agent.h" #import "ios/chrome/browser/autofill/autofill_controller.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" @@ -34,18 +41,40 @@ @implementation FullCardRequesterConsumerMock -typedef void (^mock_full_card_request_did_succeed)(const autofill::CreditCard&, - const base::string16&); +typedef void (^mock_full_card_request_did_succeed_with_method_name)( + const std::string&, + const std::string&); -- (void)fullCardRequestDidSucceedWithCard:(const autofill::CreditCard&)card - verificationCode: - (const base::string16&)verificationCode { - return static_cast<mock_full_card_request_did_succeed>( - [self blockForSelector:_cmd])(card, verificationCode); +- (void)fullCardRequestDidSucceedWithMethodName:(const std::string&)methodName + stringifiedDetails: + (const std::string&)stringifiedDetails { + return static_cast<mock_full_card_request_did_succeed_with_method_name>( + [self blockForSelector:_cmd])(methodName, stringifiedDetails); } @end +class FakeResultDelegate + : public autofill::payments::FullCardRequest::ResultDelegate { + public: + FakeResultDelegate() : weak_ptr_factory_(this) {} + ~FakeResultDelegate() override {} + + void OnFullCardRequestSucceeded(const autofill::CreditCard& card, + const base::string16& cvc) override {} + + void OnFullCardRequestFailed() override {} + + base::WeakPtr<FakeResultDelegate> GetWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); + } + + private: + base::WeakPtrFactory<FakeResultDelegate> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(FakeResultDelegate); +}; + class PaymentRequestFullCardRequesterTest : public ChromeWebTest { protected: PaymentRequestFullCardRequesterTest() @@ -98,7 +127,9 @@ autofill::AutofillManager* autofill_manager = autofill::AutofillDriverIOS::FromWebState(web_state()) ->autofill_manager(); - full_card_requester.GetFullCard(&credit_card_, autofill_manager); + FakeResultDelegate* fake_result_delegate = new FakeResultDelegate; + full_card_requester.GetFullCard(credit_card_, autofill_manager, + fake_result_delegate->GetWeakPtr()); // Spin the run loop to trigger the animation. base::test::ios::SpinRunLoopWithMaxDelay(base::TimeDelta::FromSecondsD(1.0)); @@ -119,23 +150,38 @@ // Tests that calling the FullCardRequester's delegate method which signals that // the full credit card details have been successfully received, causes the // FullCardRequester's delegate method to get called. -TEST_F(PaymentRequestFullCardRequesterTest, FullCardRequestSucceeded) { +TEST_F(PaymentRequestFullCardRequesterTest, InstrumentDetailsReady) { // Mock the consumer. id consumer = [OCMockObject mockForProtocol:@protocol(FullCardRequesterConsumer)]; id consumer_mock([[FullCardRequesterConsumerMock alloc] initWithRepresentedObject:consumer]); - SEL selector = @selector(fullCardRequestDidSucceedWithCard:verificationCode:); + SEL selector = + @selector(fullCardRequestDidSucceedWithMethodName:stringifiedDetails:); [consumer_mock onSelector:selector - callBlockExpectation:^(const autofill::CreditCard& card, - const base::string16& verificationCode) { - EXPECT_EQ(credit_card_, card); - EXPECT_EQ(base::ASCIIToUTF16("123"), verificationCode); + callBlockExpectation:^(const std::string& methodName, + const std::string& stringifiedDetails) { + EXPECT_EQ("visa", methodName); + + std::string cvc; + std::unique_ptr<base::DictionaryValue> detailsDict = + base::DictionaryValue::From( + base::JSONReader::Read(stringifiedDetails)); + detailsDict->GetString("cardSecurityCode", &cvc); + EXPECT_EQ("123", cvc); }]; FullCardRequester full_card_requester(consumer_mock, nil, chrome_browser_state_.get()); - full_card_requester.OnFullCardRequestSucceeded(credit_card_, - base::ASCIIToUTF16("123")); + autofill::AutofillProfile billing_address; + + std::unique_ptr<base::DictionaryValue> response_value = + payments::data_util::GetBasicCardResponseFromAutofillCreditCard( + credit_card_, base::ASCIIToUTF16("123"), billing_address, "en-US") + .ToDictionaryValue(); + std::string stringifiedDetails; + base::JSONWriter::Write(*response_value, &stringifiedDetails); + + full_card_requester.OnInstrumentDetailsReady("visa", stringifiedDetails); }
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_coordinator.h b/ios/chrome/browser/ui/payments/payment_items_display_coordinator.h index cebc72d..e1c3dbf 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_coordinator.h +++ b/ios/chrome/browser/ui/payments/payment_items_display_coordinator.h
@@ -11,7 +11,9 @@ #import "ios/chrome/browser/chrome_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_items_display_view_controller.h" +namespace payments { class PaymentRequest; +} // namespace payments @class PaymentItemsDisplayCoordinator; @@ -38,7 +40,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects touches the return button // or the pay button.
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_coordinator.mm b/ios/chrome/browser/ui/payments/payment_items_display_coordinator.mm index 027990af..44a8349 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_coordinator.mm +++ b/ios/chrome/browser/ui/payments/payment_items_display_coordinator.mm
@@ -26,7 +26,7 @@ @synthesize delegate = _delegate; - (void)start { - BOOL payButtonEnabled = _paymentRequest->selected_credit_card() != nil; + BOOL payButtonEnabled = _paymentRequest->selected_payment_method() != nil; _viewController = [[PaymentItemsDisplayViewController alloc] initWithPayButtonEnabled:payButtonEnabled]; [_viewController setDelegate:self];
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/payment_items_display_coordinator_unittest.mm index 6d74540d..ea41a4f4 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_items_display_coordinator_unittest.mm
@@ -28,7 +28,7 @@ class PaymentRequestPaymentItemsDisplayCoordinatorTest : public PlatformTest { protected: PaymentRequestPaymentItemsDisplayCoordinatorTest() { - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); } @@ -36,7 +36,7 @@ base::test::ScopedTaskEnvironment scoped_task_evironment_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_mediator.h b/ios/chrome/browser/ui/payments/payment_items_display_mediator.h index 0874430..a00bc96c6 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_mediator.h +++ b/ios/chrome/browser/ui/payments/payment_items_display_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_items_display_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // Serves as data source for PaymentItemsDisplayViewController. @interface PaymentItemsDisplayMediator @@ -16,7 +18,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_mediator.mm b/ios/chrome/browser/ui/payments/payment_items_display_mediator.mm index 2ba9d9b..8c7e081e 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_items_display_mediator.mm
@@ -24,7 +24,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; @end @@ -32,7 +32,8 @@ @synthesize paymentRequest = _paymentRequest; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest;
diff --git a/ios/chrome/browser/ui/payments/payment_items_display_view_controller_unittest.mm b/ios/chrome/browser/ui/payments/payment_items_display_view_controller_unittest.mm index 56261ce..5d3a679 100644 --- a/ios/chrome/browser/ui/payments/payment_items_display_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_items_display_view_controller_unittest.mm
@@ -46,7 +46,7 @@ : public CollectionViewControllerTest { protected: CollectionViewController* InstantiateController() override { - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); mediator_ = [[TestPaymentItemsDisplayMediator alloc] init]; @@ -64,7 +64,7 @@ base::test::ScopedTaskEnvironment scoped_task_evironment_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; TestPaymentItemsDisplayMediator* mediator_ = nil; };
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.h b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.h index c644675..c7374b45 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.h +++ b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.h
@@ -12,11 +12,10 @@ #import "ios/chrome/browser/ui/payments/credit_card_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller.h" +namespace payments { +class PaymentInstrument; class PaymentRequest; - -namespace autofill { -class CreditCard; -} // namespace autofill +} // namespace payments @class PaymentMethodSelectionCoordinator; @@ -26,7 +25,8 @@ // Notifies the delegate that the user has selected a payment method. - (void)paymentMethodSelectionCoordinator: (PaymentMethodSelectionCoordinator*)coordinator - didSelectPaymentMethod:(autofill::CreditCard*)paymentMethod; + didSelectPaymentMethod: + (payments::PaymentInstrument*)paymentMethod; // Notifies the delegate that the user has chosen to return to the previous // screen without making a selection. @@ -45,7 +45,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects a payment method or returns // without selecting a payment method.
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.mm b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.mm index 8441248..f4e2771 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.mm +++ b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator.mm
@@ -8,6 +8,8 @@ #include "base/logging.h" #include "components/autofill/core/browser/credit_card.h" +#include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/payment_instrument.h" #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/payments/payment_request.h" #import "ios/chrome/browser/ui/payments/cells/payment_method_item.h" @@ -33,16 +35,17 @@ @property(nonatomic, strong) PaymentMethodSelectionMediator* mediator; -// Initializes and starts the CreditCardEditCoordinator. Sets |creditCard| as -// the credit card to be edited. -- (void)startCreditCardEditCoordinatorWithCreditCard: - (autofill::CreditCard*)creditCard; +// Initializes and starts the CreditCardEditCoordinator. Sets +// |autofillInstrument| as the autofill payment instrument to be edited. +- (void)startCreditCardEditCoordinatorWithAutofillPaymentInstrument: + (payments::AutofillPaymentInstrument*)autofillInstrument; // Called when the user selects a payment method. The cell is checked, the // UI is locked so that the user can't interact with it, then the delegate is // notified. The delay is here to let the user get a visual feedback of the // selection before this view disappears. -- (void)delayedNotifyDelegateOfSelection:(autofill::CreditCard*)paymentMethod; +- (void)delayedNotifyDelegateOfSelection: + (payments::PaymentInstrument*)paymentMethod; @end @@ -83,20 +86,25 @@ - (BOOL)paymentRequestSelectorViewController: (PaymentRequestSelectorViewController*)controller didSelectItemAtIndex:(NSUInteger)index { - DCHECK(index < self.paymentRequest->credit_cards().size()); - autofill::CreditCard* creditCard = self.paymentRequest->credit_cards()[index]; + DCHECK(index < self.paymentRequest->payment_methods().size()); + payments::PaymentInstrument* paymentMethod = + self.paymentRequest->payment_methods()[index]; // Proceed with item selection only if the item has all required info, or - // else bring up the credit card editor. + // else bring up the credit card editor. A payment method can be incomplete + // only if it is an AutofillPaymentInstrument. CollectionViewItem<PaymentsIsSelectable>* selectedItem = self.mediator.selectableItems[index]; if (selectedItem.complete) { // Update the data source with the selection. self.mediator.selectedItemIndex = index; - [self delayedNotifyDelegateOfSelection:creditCard]; + [self delayedNotifyDelegateOfSelection:paymentMethod]; return YES; } else { - [self startCreditCardEditCoordinatorWithCreditCard:creditCard]; + DCHECK(paymentMethod->type() == + payments::PaymentInstrument::Type::AUTOFILL); + [self startCreditCardEditCoordinatorWithAutofillPaymentInstrument: + static_cast<payments::AutofillPaymentInstrument*>(paymentMethod)]; return NO; } } @@ -108,7 +116,7 @@ - (void)paymentRequestSelectorViewControllerDidSelectAddItem: (PaymentRequestSelectorViewController*)controller { - [self startCreditCardEditCoordinatorWithCreditCard:nil]; + [self startCreditCardEditCoordinatorWithAutofillPaymentInstrument:nil]; } - (void)paymentRequestSelectorViewControllerDidToggleEditingMode: @@ -120,33 +128,41 @@ - (void)paymentRequestSelectorViewController: (PaymentRequestSelectorViewController*)controller didSelectItemAtIndexForEditing:(NSUInteger)index { - DCHECK(index < self.paymentRequest->credit_cards().size()); - [self - startCreditCardEditCoordinatorWithCreditCard:self.paymentRequest - ->credit_cards()[index]]; + DCHECK(index < self.paymentRequest->payment_methods().size()); + + // We should only edit the payment instrument if it is an + // AutofillPaymentInstrument. + if (self.paymentRequest->payment_methods()[index]->type() == + payments::PaymentInstrument::Type::AUTOFILL) { + [self startCreditCardEditCoordinatorWithAutofillPaymentInstrument: + static_cast<payments::AutofillPaymentInstrument*>( + self.paymentRequest->payment_methods()[index])]; + } } #pragma mark - CreditCardEditCoordinatorDelegate - (void)creditCardEditCoordinator:(CreditCardEditCoordinator*)coordinator - didFinishEditingCreditCard:(autofill::CreditCard*)creditCard { + didFinishEditingPaymentMethod: + (payments::AutofillPaymentInstrument*)creditCard { // Update the data source with the new data. [self.mediator loadItems]; - const std::vector<autofill::CreditCard*>& creditCards = - self.paymentRequest->credit_cards(); - auto position = std::find(creditCards.begin(), creditCards.end(), creditCard); - DCHECK(position != creditCards.end()); + const std::vector<payments::PaymentInstrument*>& paymentMethods = + self.paymentRequest->payment_methods(); + auto position = + std::find(paymentMethods.begin(), paymentMethods.end(), creditCard); + DCHECK(position != paymentMethods.end()); // Mark the edited item as complete meaning all required information has been // filled out. CollectionViewItem<PaymentsIsSelectable>* editedItem = - self.mediator.selectableItems[position - creditCards.begin()]; + self.mediator.selectableItems[position - paymentMethods.begin()]; editedItem.complete = YES; if (![self.viewController isEditing]) { // Update the data source with the selection. - self.mediator.selectedItemIndex = position - creditCards.begin(); + self.mediator.selectedItemIndex = position - paymentMethods.begin(); } [self.viewController loadModel]; @@ -170,17 +186,18 @@ #pragma mark - Helper methods -- (void)startCreditCardEditCoordinatorWithCreditCard: - (autofill::CreditCard*)creditCard { +- (void)startCreditCardEditCoordinatorWithAutofillPaymentInstrument: + (payments::AutofillPaymentInstrument*)autofillInstrument { self.creditCardEditCoordinator = [[CreditCardEditCoordinator alloc] initWithBaseViewController:self.viewController]; self.creditCardEditCoordinator.paymentRequest = self.paymentRequest; - self.creditCardEditCoordinator.creditCard = creditCard; + self.creditCardEditCoordinator.paymentMethod = autofillInstrument; self.creditCardEditCoordinator.delegate = self; [self.creditCardEditCoordinator start]; } -- (void)delayedNotifyDelegateOfSelection:(autofill::CreditCard*)paymentMethod { +- (void)delayedNotifyDelegateOfSelection: + (payments::PaymentInstrument*)paymentMethod { self.viewController.view.userInteractionEnabled = NO; __weak PaymentMethodSelectionCoordinator* weakSelf = self; dispatch_after(
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator_unittest.mm index 145efaf..616e75ca 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_method_selection_coordinator_unittest.mm
@@ -12,6 +12,7 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/core/payment_instrument.h" #include "ios/chrome/browser/payments/payment_request.h" #include "ios/chrome/browser/payments/payment_request_test_util.h" #include "ios/chrome/browser/payments/test_payment_request.h" @@ -41,7 +42,7 @@ personal_data_manager_.AddTestingCreditCard(&credit_card1_); credit_card2_.set_use_count(5U); personal_data_manager_.AddTestingCreditCard(&credit_card2_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); } @@ -52,7 +53,7 @@ autofill::CreditCard credit_card1_; autofill::CreditCard credit_card2_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses @@ -106,10 +107,10 @@ mockForProtocol:@protocol(PaymentMethodSelectionCoordinatorDelegate)]; [[delegate expect] paymentMethodSelectionCoordinator:coordinator - didSelectPaymentMethod:payment_request_->credit_cards()[0]]; + didSelectPaymentMethod:payment_request_->payment_methods()[0]]; [[delegate reject] paymentMethodSelectionCoordinator:coordinator - didSelectPaymentMethod:payment_request_->credit_cards()[1]]; + didSelectPaymentMethod:payment_request_->payment_methods()[1]]; [coordinator setDelegate:delegate]; EXPECT_EQ(1u, navigation_controller.viewControllers.count);
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.h b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.h index 359f0d2..8d3c712 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.h +++ b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // Serves as data source for PaymentRequestSelectorViewController. @interface PaymentMethodSelectionMediator @@ -25,7 +27,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm index 4513447e..3a202ea9 100644 --- a/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_method_selection_mediator.mm
@@ -8,10 +8,11 @@ #include "base/strings/string16.h" #include "base/strings/sys_string_conversions.h" -#include "components/autofill/core/browser/autofill_data_util.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" +#include "components/payments/core/autofill_payment_instrument.h" +#include "components/payments/core/payment_instrument.h" #include "components/payments/core/strings_util.h" #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/payments/payment_request.h" @@ -28,6 +29,8 @@ namespace { using ::payment_request_util::GetBillingAddressLabelFromAutofillProfile; +using ::payment_request_util:: + GetPaymentMethodNotificationLabelFromPaymentMethod; } // namespace @interface PaymentMethodSelectionMediator () @@ -35,7 +38,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The selectable items to display in the collection. @property(nonatomic, strong) NSMutableArray<PaymentMethodItem*>* items; @@ -49,7 +52,8 @@ @synthesize paymentRequest = _paymentRequest; @synthesize items = _items; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest; @@ -90,39 +94,36 @@ #pragma mark - Public methods - (void)loadItems { - const std::vector<autofill::CreditCard*>& paymentMethods = - _paymentRequest->credit_cards(); + const std::vector<payments::PaymentInstrument*>& paymentMethods = + _paymentRequest->payment_methods(); _items = [NSMutableArray arrayWithCapacity:paymentMethods.size()]; for (size_t index = 0; index < paymentMethods.size(); ++index) { - autofill::CreditCard* paymentMethod = paymentMethods[index]; + payments::PaymentInstrument* paymentMethod = paymentMethods[index]; DCHECK(paymentMethod); PaymentMethodItem* item = [[PaymentMethodItem alloc] init]; - item.methodID = - base::SysUTF16ToNSString(paymentMethod->NetworkAndLastFourDigits()); - item.methodDetail = base::SysUTF16ToNSString( - paymentMethod->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL)); - item.notification = - payment_request_util::GetPaymentMethodNotificationLabelFromCreditCard( - *paymentMethod, _paymentRequest->billing_profiles()); - item.complete = payment_request_util::IsCreditCardCompleteForPayment( + item.methodID = base::SysUTF16ToNSString(paymentMethod->GetLabel()); + item.methodDetail = base::SysUTF16ToNSString(paymentMethod->GetSublabel()); + item.notification = GetPaymentMethodNotificationLabelFromPaymentMethod( *paymentMethod, _paymentRequest->billing_profiles()); + item.complete = paymentMethod->IsCompleteForPayment(); - autofill::AutofillProfile* billingAddress = - autofill::PersonalDataManager::GetProfileFromProfilesByGUID( - paymentMethod->billing_address_id(), - _paymentRequest->billing_profiles()); - if (billingAddress) { - item.methodAddress = - GetBillingAddressLabelFromAutofillProfile(*billingAddress); + if (paymentMethod->type() == payments::PaymentInstrument::Type::AUTOFILL) { + payments::AutofillPaymentInstrument* autofillInstrument = + static_cast<payments::AutofillPaymentInstrument*>(paymentMethod); + autofill::AutofillProfile* billingAddress = + autofill::PersonalDataManager::GetProfileFromProfilesByGUID( + autofillInstrument->credit_card()->billing_address_id(), + _paymentRequest->billing_profiles()); + if (billingAddress) { + item.methodAddress = + GetBillingAddressLabelFromAutofillProfile(*billingAddress); + } } - int methodTypeIconID = - autofill::data_util::GetPaymentRequestData(paymentMethod->network()) - .icon_resource_id; - item.methodTypeIcon = NativeImage(methodTypeIconID); + item.methodTypeIcon = NativeImage(paymentMethod->icon_resource_id()); item.reserveRoomForAccessoryType = YES; - if (_paymentRequest->selected_credit_card() == paymentMethod) + if (_paymentRequest->selected_payment_method() == paymentMethod) _selectedItemIndex = index; [_items addObject:item];
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator.h b/ios/chrome/browser/ui/payments/payment_request_coordinator.h index aa70e22..b5d860a3 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator.h +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator.h
@@ -9,6 +9,7 @@ #include "base/ios/block_types.h" #include "base/strings/string16.h" +#include "components/autofill/core/browser/payments/full_card_request.h" #import "ios/chrome/browser/chrome_coordinator.h" #import "ios/chrome/browser/ui/payments/address_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/contact_info_edit_coordinator.h" @@ -22,8 +23,6 @@ #import "ios/chrome/browser/ui/payments/shipping_address_selection_coordinator.h" #import "ios/chrome/browser/ui/payments/shipping_option_selection_coordinator.h" -class PaymentRequest; - namespace autofill { class AutofillManager; } // namespace autofill @@ -32,6 +31,10 @@ class ChromeBrowserState; } // namespace ios +namespace payments { +class PaymentRequest; +} // namespace payments + namespace web { class PaymentDetails; class PaymentShippingOption; @@ -51,10 +54,11 @@ - (void)paymentRequestCoordinatorDidSelectSettings: (PaymentRequestCoordinator*)coordinator; -// Notifies the delegate that the user has completed the payment request. +// Notifies the delegate that the full payment method name and details +// have been receieved. - (void)paymentRequestCoordinator:(PaymentRequestCoordinator*)coordinator - didCompletePaymentRequestWithCard:(const autofill::CreditCard&)card - verificationCode:(const base::string16&)verificationCode; + didReceiveFullMethodName:(const std::string&)methodName + stringifiedDetails:(const std::string&)stringifiedDetails; // Notifies the delegate that the user has selected a shipping address. - (void)paymentRequestCoordinator:(PaymentRequestCoordinator*)coordinator @@ -87,7 +91,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // An instance of autofill::AutofillManager used for credit card unmasking. This // reference is not owned by this class. @@ -115,8 +119,12 @@ // The delegate to be notified when the user confirms or cancels the request. @property(nonatomic, weak) id<PaymentRequestCoordinatorDelegate> delegate; -// Initiates the UI that will process payment with a payment method. -- (void)sendPaymentResponse; +// Initiates the UI that will request card details from the user. +- (void) +requestFullCreditCard:(const autofill::CreditCard&)card + resultDelegate: + (base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>) + resultDelegate; // Updates the payment details of the PaymentRequest and updates the UI. - (void)updatePaymentDetails:(web::PaymentDetails)paymentDetails;
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm index f316eef..415e014 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator.mm
@@ -4,10 +4,14 @@ #import "ios/chrome/browser/ui/payments/payment_request_coordinator.h" +#include "base/json/json_reader.h" #include "base/memory/ptr_util.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" +#include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/payment_address.h" +#include "components/payments/core/payment_instrument.h" +#include "components/payments/core/payment_request_data_util.h" #include "components/strings/grit/components_strings.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/payments/payment_request.h" @@ -80,6 +84,9 @@ setModalTransitionStyle:UIModalTransitionStyleCoverVertical]; [_navigationController setNavigationBarHidden:YES]; + _fullCardRequester = base::MakeUnique<FullCardRequester>( + self, _navigationController, _browserState); + [[self baseViewController] presentViewController:_navigationController animated:YES completion:nil]; @@ -113,27 +120,27 @@ _navigationController = nil; } -- (void)sendPaymentResponse { - DCHECK(_paymentRequest->selected_credit_card()); - autofill::CreditCard* card = _paymentRequest->selected_credit_card(); - _fullCardRequester = base::MakeUnique<FullCardRequester>( - self, _navigationController, _browserState); - _fullCardRequester->GetFullCard(card, _autofillManager); +- (void) +requestFullCreditCard:(const autofill::CreditCard&)card + resultDelegate: + (base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>) + resultDelegate { + _fullCardRequester->GetFullCard(card, _autofillManager, resultDelegate); } #pragma mark - FullCardRequesterConsumer -- (void)fullCardRequestDidSucceedWithCard:(const autofill::CreditCard&)card - verificationCode: - (const base::string16&)verificationCode { +- (void)fullCardRequestDidSucceedWithMethodName:(const std::string&)methodName + stringifiedDetails: + (const std::string&)stringifiedDetails { _viewController.view.userInteractionEnabled = NO; [_viewController setPending:YES]; [_viewController loadModel]; [[_viewController collectionView] reloadData]; [_delegate paymentRequestCoordinator:self - didCompletePaymentRequestWithCard:card - verificationCode:verificationCode]; + didReceiveFullMethodName:methodName + stringifiedDetails:stringifiedDetails]; } #pragma mark - Public methods @@ -210,7 +217,9 @@ - (void)paymentRequestViewControllerDidConfirm: (PaymentRequestViewController*)controller { - [self sendPaymentResponse]; + DCHECK(_paymentRequest->selected_payment_method()); + _paymentRequest->selected_payment_method()->InvokePaymentApp( + _fullCardRequester.get()); } - (void)paymentRequestViewControllerDidSelectSettings: @@ -286,7 +295,7 @@ - (void)paymentRequestViewControllerDidSelectPaymentMethodItem: (PaymentRequestViewController*)controller { - if (_paymentRequest->credit_cards().empty()) { + if (_paymentRequest->payment_methods().empty()) { _creditCardEditCoordinator = [[CreditCardEditCoordinator alloc] initWithBaseViewController:_viewController]; [_creditCardEditCoordinator setPaymentRequest:_paymentRequest]; @@ -327,7 +336,9 @@ - (void)paymentItemsDisplayCoordinatorDidConfirm: (PaymentItemsDisplayCoordinator*)coordinator { - [self sendPaymentResponse]; + DCHECK(_paymentRequest->selected_payment_method()); + _paymentRequest->selected_payment_method()->InvokePaymentApp( + _fullCardRequester.get()); } #pragma mark - ContactInfoSelectionCoordinatorDelegate @@ -421,11 +432,11 @@ - (void)paymentMethodSelectionCoordinator: (PaymentMethodSelectionCoordinator*)coordinator - didSelectPaymentMethod:(autofill::CreditCard*)creditCard { - DCHECK(creditCard); - DCHECK(payment_request_util::IsCreditCardCompleteForPayment( - *creditCard, _paymentRequest->billing_profiles())); - _paymentRequest->set_selected_credit_card(creditCard); + didSelectPaymentMethod: + (payments::PaymentInstrument*)paymentMethod { + DCHECK(paymentMethod); + DCHECK(paymentMethod->IsCompleteForPayment()); + _paymentRequest->set_selected_payment_method(paymentMethod); [_viewController updatePaymentMethodSection]; [_methodSelectionCoordinator stop]; @@ -441,9 +452,11 @@ #pragma mark - CreditCardEditCoordinatorDelegate - (void)creditCardEditCoordinator:(CreditCardEditCoordinator*)coordinator - didFinishEditingCreditCard:(autofill::CreditCard*)creditCard { - DCHECK(creditCard); - _paymentRequest->set_selected_credit_card(creditCard); + didFinishEditingPaymentMethod: + (payments::AutofillPaymentInstrument*)paymentMethod { + DCHECK(paymentMethod); + DCHECK(paymentMethod->IsCompleteForPayment()); + _paymentRequest->set_selected_payment_method(paymentMethod); [_viewController updatePaymentMethodSection]; [_creditCardEditCoordinator stop];
diff --git a/ios/chrome/browser/ui/payments/payment_request_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_coordinator_unittest.mm index 1f6c030..f307efdb 100644 --- a/ios/chrome/browser/ui/payments/payment_request_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_request_coordinator_unittest.mm
@@ -4,15 +4,21 @@ #import "ios/chrome/browser/ui/payments/payment_request_coordinator.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" #include "base/mac/foundation_util.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/ios/wait_util.h" +#include "base/test/scoped_task_environment.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/payment_address.h" +#include "components/payments/core/payment_instrument.h" +#include "components/payments/core/payment_request_data_util.h" #include "components/payments/core/payments_test_util.h" #include "components/prefs/pref_service.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" @@ -43,8 +49,8 @@ typedef void (^mock_coordinator_cancel)(PaymentRequestCoordinator*); typedef void (^mock_coordinator_complete)(PaymentRequestCoordinator*, - const autofill::CreditCard&, - const base::string16&); + const std::string&, + const std::string&); typedef void (^mock_coordinator_select_shipping_address)( PaymentRequestCoordinator*, const autofill::AutofillProfile&); @@ -59,10 +65,10 @@ } - (void)paymentRequestCoordinator:(PaymentRequestCoordinator*)coordinator - didCompletePaymentRequestWithCard:(const autofill::CreditCard&)card - verificationCode:(const base::string16&)verificationCode { + didReceiveFullMethodName:(const std::string&)methodName + stringifiedDetails:(const std::string&)stringifiedDetails { return static_cast<mock_coordinator_complete>([self blockForSelector:_cmd])( - coordinator, card, verificationCode); + coordinator, methodName, stringifiedDetails); } - (void)paymentRequestCoordinator:(PaymentRequestCoordinator*)coordinator @@ -96,17 +102,19 @@ &ios::BuildFakeSigninManager); browser_state_ = test_cbs_builder.Build(); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), browser_state_.get(), &personal_data_manager_); payment_request_->SetPrefService(pref_service_.get()); } + base::test::ScopedTaskEnvironment scoped_task_evironment_; + autofill::AutofillProfile autofill_profile_; autofill::CreditCard credit_card_; std::unique_ptr<PrefService> pref_service_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; std::unique_ptr<ios::ChromeBrowserState> browser_state_; }; @@ -147,7 +155,7 @@ // Tests that calling the FullCardRequesterConsumer delegate method which // notifies the coordinator about successful unmasking of a credit card invokes // the appropriate coordinator delegate method with the expected information. -TEST_F(PaymentRequestCoordinatorTest, FullCardRequestDidSucceed) { +TEST_F(PaymentRequestCoordinatorTest, FullCardRequestDidSucceedWithMethodName) { UIViewController* base_view_controller = [[UIViewController alloc] init]; ScopedKeyWindow scoped_key_window_; [scoped_key_window_.Get() setRootViewController:base_view_controller]; @@ -160,22 +168,38 @@ mockForProtocol:@protocol(PaymentMethodSelectionCoordinatorDelegate)]; id delegate_mock([[PaymentRequestCoordinatorDelegateMock alloc] initWithRepresentedObject:delegate]); - SEL selector = - @selector(paymentRequestCoordinator:didCompletePaymentRequestWithCard - :verificationCode:); + SEL selector = @selector + (paymentRequestCoordinator:didReceiveFullMethodName:stringifiedDetails:); [delegate_mock onSelector:selector callBlockExpectation:^(PaymentRequestCoordinator* callerCoordinator, - const autofill::CreditCard& card, - const base::string16& verificationCode) { - EXPECT_EQ(credit_card_, card); - EXPECT_EQ(base::ASCIIToUTF16("123"), verificationCode); + const std::string& methodName, + const std::string& stringifiedDetails) { + EXPECT_EQ("visa", methodName); + + std::string cvc; + std::unique_ptr<base::DictionaryValue> detailsDict = + base::DictionaryValue::From( + base::JSONReader::Read(stringifiedDetails)); + detailsDict->GetString("cardSecurityCode", &cvc); + EXPECT_EQ("123", cvc); + EXPECT_EQ(coordinator, callerCoordinator); }]; [coordinator setDelegate:delegate_mock]; + std::string methodName = "visa"; + std::string appLocale = ""; + + std::unique_ptr<base::DictionaryValue> response_value = + payments::data_util::GetBasicCardResponseFromAutofillCreditCard( + credit_card_, base::ASCIIToUTF16("123"), autofill_profile_, appLocale) + .ToDictionaryValue(); + std::string stringifiedDetails; + base::JSONWriter::Write(*response_value, &stringifiedDetails); + // Call the card unmasking delegate method. - [coordinator fullCardRequestDidSucceedWithCard:credit_card_ - verificationCode:base::ASCIIToUTF16("123")]; + [coordinator fullCardRequestDidSucceedWithMethodName:methodName + stringifiedDetails:stringifiedDetails]; } // Tests that calling the ShippingAddressSelectionCoordinator delegate method
diff --git a/ios/chrome/browser/ui/payments/payment_request_manager.mm b/ios/chrome/browser/ui/payments/payment_request_manager.mm index 1a5be16f..c4c252b 100644 --- a/ios/chrome/browser/ui/payments/payment_request_manager.mm +++ b/ios/chrome/browser/ui/payments/payment_request_manager.mm
@@ -8,6 +8,7 @@ #include "base/ios/block_types.h" #include "base/ios/ios_util.h" +#include "base/json/json_reader.h" #import "base/mac/bind_objc_block.h" #include "base/mac/foundation_util.h" #include "base/memory/ptr_util.h" @@ -77,9 +78,8 @@ NSString* kCancelMessage = @"The payment request was canceled."; struct PendingPaymentResponse { - autofill::CreditCard creditCard; - base::string16 verificationCode; - autofill::AutofillProfile billingAddress; + std::string methodName; + std::string stringifiedDetails; autofill::AutofillProfile shippingAddress; autofill::AutofillProfile contactAddress; }; @@ -99,7 +99,7 @@ // invoking the PaymentRequest API. Also caches credit cards and addresses // provided by the _personalDataManager and manages selected ones for the // current PaymentRequest flow. - std::unique_ptr<PaymentRequest> _paymentRequest; + std::unique_ptr<payments::PaymentRequest> _paymentRequest; // WebState for the tab this object is attached to. web::WebState* _webState; @@ -409,7 +409,7 @@ return YES; } - _paymentRequest = base::MakeUnique<PaymentRequest>( + _paymentRequest = base::MakeUnique<payments::PaymentRequest>( webPaymentRequest, _browserState, _personalDataManager, self); return YES; @@ -658,8 +658,13 @@ #pragma mark - PaymentRequestUIDelegate -- (void)openFullCardRequestUI { - [_paymentRequestCoordinator sendPaymentResponse]; +- (void) +requestFullCreditCard:(const autofill::CreditCard&)creditCard + resultDelegate: + (base::WeakPtr<autofill::payments::FullCardRequest::ResultDelegate>) + resultDelegate { + [_paymentRequestCoordinator requestFullCreditCard:creditCard + resultDelegate:resultDelegate]; } #pragma mark - PaymentRequestCoordinatorDelegate methods @@ -683,19 +688,10 @@ } - (void)paymentRequestCoordinator:(PaymentRequestCoordinator*)coordinator - didCompletePaymentRequestWithCard:(const autofill::CreditCard&)card - verificationCode:(const base::string16&)verificationCode { - _pendingPaymentResponse.creditCard = card; - _pendingPaymentResponse.verificationCode = verificationCode; - - DCHECK(!card.billing_address_id().empty()); - autofill::AutofillProfile* billingAddress = - autofill::PersonalDataManager::GetProfileFromProfilesByGUID( - card.billing_address_id(), _paymentRequest->billing_profiles()); - DCHECK(billingAddress); - _pendingPaymentResponse.billingAddress = *billingAddress; - _addressNormalizationManager->StartNormalizingAddress( - &_pendingPaymentResponse.billingAddress); + didReceiveFullMethodName:(const std::string&)methodName + stringifiedDetails:(const std::string&)stringifiedDetails { + _pendingPaymentResponse.methodName = methodName; + _pendingPaymentResponse.stringifiedDetails = stringifiedDetails; if (_paymentRequest->request_shipping()) { // TODO(crbug.com/602666): User should get here only if they have selected @@ -729,24 +725,10 @@ - (void)paymentRequestAddressNormalizationDidComplete { web::PaymentResponse paymentResponse; - // If the merchant specified the card network as part of the "basic-card" - // payment method, return "basic-card" as the method_name. Otherwise, return - // the name of the network directly. - std::string issuer_network = autofill::data_util::GetPaymentRequestData( - _pendingPaymentResponse.creditCard.network()) - .basic_card_issuer_network; paymentResponse.method_name = - _paymentRequest->basic_card_specified_networks().find(issuer_network) != - _paymentRequest->basic_card_specified_networks().end() - ? base::ASCIIToUTF16("basic-card") - : base::ASCIIToUTF16(issuer_network); + base::ASCIIToUTF16(_pendingPaymentResponse.methodName); - paymentResponse.details = - payments::data_util::GetBasicCardResponseFromAutofillCreditCard( - _pendingPaymentResponse.creditCard, - _pendingPaymentResponse.verificationCode, - _pendingPaymentResponse.billingAddress, - GetApplicationContext()->GetApplicationLocale()); + paymentResponse.details = _pendingPaymentResponse.stringifiedDetails; if (_paymentRequest->request_shipping()) { paymentResponse.shipping_address =
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator.h b/ios/chrome/browser/ui/payments/payment_request_mediator.h index fc56af2..dc9cfdeda 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator.h +++ b/ios/chrome/browser/ui/payments/payment_request_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_request_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // A mediator object that provides data for a PaymentRequestViewController. @interface PaymentRequestMediator @@ -19,7 +21,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator.mm b/ios/chrome/browser/ui/payments/payment_request_mediator.mm index e9c2cb6..f760154 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator.mm +++ b/ios/chrome/browser/ui/payments/payment_request_mediator.mm
@@ -12,6 +12,7 @@ #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/field_types.h" +#include "components/payments/core/autofill_payment_instrument.h" #include "components/payments/core/currency_formatter.h" #include "components/payments/core/payment_prefs.h" #include "components/payments/core/strings_util.h" @@ -53,7 +54,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; @end @@ -62,7 +63,8 @@ @synthesize totalValueChanged = _totalValueChanged; @synthesize paymentRequest = _paymentRequest; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest; @@ -73,7 +75,7 @@ #pragma mark - PaymentRequestViewControllerDataSource - (BOOL)canPay { - return self.paymentRequest->selected_credit_card() != nullptr && + return self.paymentRequest->selected_payment_method() != nullptr && (self.paymentRequest->selected_shipping_option() != nullptr || ![self requestShipping]) && (self.paymentRequest->selected_shipping_profile() != nullptr || @@ -174,7 +176,7 @@ } - (CollectionViewItem*)paymentMethodSectionHeaderItem { - if (!self.paymentRequest->selected_credit_card()) + if (!self.paymentRequest->selected_payment_method()) return nil; PaymentsTextItem* item = [[PaymentsTextItem alloc] init]; item.text = @@ -183,18 +185,13 @@ } - (CollectionViewItem*)paymentMethodItem { - const autofill::CreditCard* creditCard = - self.paymentRequest->selected_credit_card(); - if (creditCard) { + const payments::PaymentInstrument* paymentMethod = + self.paymentRequest->selected_payment_method(); + if (paymentMethod) { PaymentMethodItem* item = [[PaymentMethodItem alloc] init]; - item.methodID = - base::SysUTF16ToNSString(creditCard->NetworkAndLastFourDigits()); - item.methodDetail = base::SysUTF16ToNSString( - creditCard->GetRawInfo(autofill::CREDIT_CARD_NAME_FULL)); - int issuerNetworkIconID = - autofill::data_util::GetPaymentRequestData(creditCard->network()) - .icon_resource_id; - item.methodTypeIcon = NativeImage(issuerNetworkIconID); + item.methodID = base::SysUTF16ToNSString(paymentMethod->GetLabel()); + item.methodDetail = base::SysUTF16ToNSString(paymentMethod->GetSublabel()); + item.methodTypeIcon = NativeImage(paymentMethod->icon_resource_id()); item.accessoryType = MDCCollectionViewCellAccessoryDisclosureIndicator; return item; } @@ -202,7 +199,7 @@ CollectionViewDetailItem* item = [[CollectionViewDetailItem alloc] init]; item.text = l10n_util::GetNSString(IDS_PAYMENT_REQUEST_PAYMENT_METHOD_SECTION_NAME); - if (self.paymentRequest->credit_cards().empty()) { + if (self.paymentRequest->payment_methods().empty()) { item.detailText = [l10n_util::GetNSString(IDS_ADD) uppercaseStringWithLocale:[NSLocale currentLocale]]; } else {
diff --git a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm index ca07b06..1533918 100644 --- a/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_request_mediator_unittest.mm
@@ -14,6 +14,7 @@ #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/test_personal_data_manager.h" +#include "components/payments/core/payment_instrument.h" #include "components/payments/core/payment_prefs.h" #include "components/payments/core/payments_test_util.h" #include "components/payments/core/strings_util.h" @@ -65,7 +66,7 @@ &ios::BuildFakeSigninManager); chrome_browser_state_ = test_cbs_builder.Build(); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), chrome_browser_state_.get(), &personal_data_manager_); payment_request_->SetPrefService(pref_service_.get()); @@ -82,27 +83,27 @@ autofill::CreditCard credit_card_; std::unique_ptr<PrefService> pref_service_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; std::unique_ptr<TestChromeBrowserState> chrome_browser_state_; PaymentRequestMediator* mediator_; }; // Tests whether payment can be completed when expected. TEST_F(PaymentRequestMediatorTest, TestCanPay) { - EXPECT_TRUE(payment_request_->selected_credit_card()); + EXPECT_TRUE(payment_request_->selected_payment_method()); EXPECT_TRUE(payment_request_->selected_shipping_profile()); EXPECT_TRUE(payment_request_->selected_shipping_option()); EXPECT_TRUE(payment_request_->selected_contact_profile()); EXPECT_TRUE([GetPaymentRequestMediator() canPay]); - // Payment cannot be completed if there is no selected credit card. - autofill::CreditCard* selected_credit_card = - payment_request_->selected_credit_card(); - payment_request_->set_selected_credit_card(nullptr); + // Payment cannot be completed if there is no selected payment method. + payments::PaymentInstrument* selected_payment_method = + payment_request_->selected_payment_method(); + payment_request_->set_selected_payment_method(nullptr); EXPECT_FALSE([GetPaymentRequestMediator() canPay]); - // Restore the selected credit card. - payment_request_->set_selected_credit_card(selected_credit_card); + // Restore the selected payment method. + payment_request_->set_selected_payment_method(selected_payment_method); EXPECT_TRUE([GetPaymentRequestMediator() canPay]); // Payment cannot be completed if there is no selected shipping profile, @@ -308,11 +309,11 @@ EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, payment_method_item.accessoryType); - // Reset the selected credit card. - payment_request_->set_selected_credit_card(nullptr); + // Reset the selected payment method. + payment_request_->set_selected_payment_method(nullptr); - // When there is no selected credit card, the Payment Method item should be of - // type CollectionViewDetailItem. + // When there is no selected payment method, the Payment Method item should be + // of type CollectionViewDetailItem. item = [GetPaymentRequestMediator() paymentMethodItem]; ASSERT_TRUE([item isMemberOfClass:[CollectionViewDetailItem class]]); CollectionViewDetailItem* add_payment_method_item = @@ -324,8 +325,8 @@ EXPECT_EQ(MDCCollectionViewCellAccessoryDisclosureIndicator, add_payment_method_item.accessoryType); - // Remove the credit cards. - payment_request_->ClearCreditCards(); + // Remove the payment methods. + payment_request_->ClearPaymentMethods(); // No accessory view indicates there are no payment methods to choose from. item = [GetPaymentRequestMediator() paymentMethodItem];
diff --git a/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm b/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm index d823ffe..42f7cbf5 100644 --- a/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/payments/payment_request_view_controller_unittest.mm
@@ -146,7 +146,7 @@ personal_data_manager_.AddTestingProfile(&autofill_profile_); personal_data_manager_.AddTestingCreditCard(&credit_card_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); @@ -170,7 +170,7 @@ autofill::AutofillProfile autofill_profile_; autofill::CreditCard credit_card_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; TestPaymentRequestMediator* mediator_; };
diff --git a/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator.h b/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator.h index f74c941c..91093fe 100644 --- a/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator.h +++ b/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator.h
@@ -12,12 +12,14 @@ #import "ios/chrome/browser/ui/payments/address_edit_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller.h" -class PaymentRequest; - namespace autofill { class AutofillProfile; } // namespace autofill +namespace payments { +class PaymentRequest; +} // namespace payments + @class ShippingAddressSelectionCoordinator; // Delegate protocol for ShippingAddressSelectionCoordinator. @@ -46,7 +48,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects a shipping address or // returns without selecting one.
diff --git a/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator_unittest.mm index de88c8e8..4eb6957 100644 --- a/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/shipping_address_selection_coordinator_unittest.mm
@@ -44,7 +44,7 @@ autofill::AutofillType(autofill::PHONE_HOME_WHOLE_NUMBER), base::string16(), "en-US"); personal_data_manager_.AddTestingProfile(&autofill_profile2_); - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); @@ -63,7 +63,7 @@ std::unique_ptr<PrefService> pref_service_; autofill::TestPersonalDataManager personal_data_manager_; autofill::TestRegionDataLoader test_region_data_loader_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses
diff --git a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.h b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.h index 9aeed36..bcec5314 100644 --- a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.h +++ b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // Serves as data source for PaymentRequestSelectorViewController. @interface ShippingAddressSelectionMediator @@ -29,7 +31,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm index 4132cc6..086c2d3a 100644 --- a/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/shipping_address_selection_mediator.mm
@@ -33,7 +33,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The selectable items to display in the collection. @property(nonatomic, strong) NSMutableArray<AutofillProfileItem*>* items; @@ -48,7 +48,8 @@ @synthesize paymentRequest = _paymentRequest; @synthesize items = _items; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest;
diff --git a/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator.h b/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator.h index 9d671e9..9a51b59 100644 --- a/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator.h +++ b/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator.h
@@ -11,7 +11,9 @@ #import "ios/chrome/browser/chrome_coordinator.h" #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller.h" +namespace payments { class PaymentRequest; +} // namespace payments namespace web { class PaymentShippingOption; @@ -44,7 +46,7 @@ // The PaymentRequest object having a copy of web::PaymentRequest as provided by // the page invoking the Payment Request API. This pointer is not owned by this // class and should outlive it. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The delegate to be notified when the user selects a shipping option or // returns without selecting one.
diff --git a/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator_unittest.mm b/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator_unittest.mm index 5afbc80..f11631f 100644 --- a/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/payments/shipping_option_selection_coordinator_unittest.mm
@@ -30,7 +30,7 @@ : public PlatformTest { protected: PaymentRequestShippingOptionSelectionCoordinatorTest() { - payment_request_ = base::MakeUnique<TestPaymentRequest>( + payment_request_ = base::MakeUnique<payments::TestPaymentRequest>( payment_request_test_util::CreateTestWebPaymentRequest(), &personal_data_manager_); } @@ -38,7 +38,7 @@ base::test::ScopedTaskEnvironment scoped_task_evironment_; autofill::TestPersonalDataManager personal_data_manager_; - std::unique_ptr<TestPaymentRequest> payment_request_; + std::unique_ptr<payments::TestPaymentRequest> payment_request_; }; // Tests that invoking start and stop on the coordinator presents and dismisses
diff --git a/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.h b/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.h index 6342c08..87bfd3e 100644 --- a/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.h +++ b/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.h
@@ -7,7 +7,9 @@ #import "ios/chrome/browser/ui/payments/payment_request_selector_view_controller_data_source.h" +namespace payments { class PaymentRequest; +} // namespace payments // Serves as data source for PaymentRequestSelectorViewController. @interface ShippingOptionSelectionMediator @@ -26,7 +28,7 @@ // Initializes this object with an instance of PaymentRequest which has a copy // of web::PaymentRequest as provided by the page invoking the Payment Request // API. This object will not take ownership of |paymentRequest|. -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest +- (instancetype)initWithPaymentRequest:(payments::PaymentRequest*)paymentRequest NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.mm b/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.mm index deda3a0c..e3bcaa20 100644 --- a/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.mm +++ b/ios/chrome/browser/ui/payments/shipping_option_selection_mediator.mm
@@ -24,7 +24,7 @@ // The PaymentRequest object owning an instance of web::PaymentRequest as // provided by the page invoking the Payment Request API. This is a weak // pointer and should outlive this class. -@property(nonatomic, assign) PaymentRequest* paymentRequest; +@property(nonatomic, assign) payments::PaymentRequest* paymentRequest; // The selectable items to display in the collection. @property(nonatomic, strong) NSMutableArray<PaymentsTextItem*>* items; @@ -42,7 +42,8 @@ @synthesize paymentRequest = _paymentRequest; @synthesize items = _items; -- (instancetype)initWithPaymentRequest:(PaymentRequest*)paymentRequest { +- (instancetype)initWithPaymentRequest: + (payments::PaymentRequest*)paymentRequest { self = [super init]; if (self) { _paymentRequest = paymentRequest;
diff --git a/ios/chrome/browser/ui/settings/accounts_collection_view_controller.mm b/ios/chrome/browser/ui/settings/accounts_collection_view_controller.mm index 54e7df65..bd7ceaa 100644 --- a/ios/chrome/browser/ui/settings/accounts_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/accounts_collection_view_controller.mm
@@ -646,7 +646,7 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { CollectionViewAccountItem* item = base::mac::ObjCCastStrict<CollectionViewAccountItem>( [_identityMap objectForKey:identity.gaiaID]); @@ -658,7 +658,7 @@ [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]]; } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm index b9271376..27f5628e 100644 --- a/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password_details_collection_view_controller.mm
@@ -144,6 +144,7 @@ CollectionViewTextItem* siteHeader = [[CollectionViewTextItem alloc] initWithType:ItemTypeHeader]; siteHeader.text = l10n_util::GetNSString(IDS_IOS_SHOW_PASSWORD_VIEW_SITE); + siteHeader.textColor = [[MDCPalette greyPalette] tint500]; [model setHeader:siteHeader forSectionWithIdentifier:SectionIdentifierSite]; PasswordDetailsItem* siteItem = [[PasswordDetailsItem alloc] initWithType:ItemTypeSite];
diff --git a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm index 501cb61b..a4f0a61 100644 --- a/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm +++ b/ios/chrome/browser/ui/settings/passwords_settings_egtest.mm
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <TargetConditionals.h> + #include "base/callback.h" #include "base/mac/foundation_util.h" #include "base/memory/ref_counted.h" @@ -124,14 +126,13 @@ // Matcher for the Copy site button in Password Details view. id<GREYMatcher> CopySiteButton() { return grey_allOf( - grey_interactable(), ButtonWithAccessibilityLabel( [NSString stringWithFormat:@"%@: %@", l10n_util::GetNSString( IDS_IOS_SHOW_PASSWORD_VIEW_SITE), l10n_util::GetNSString( IDS_IOS_SETTINGS_SITE_COPY_BUTTON)]), - grey_layout(@[ Below() ], SiteHeader()), + grey_interactable(), grey_layout(@[ Below() ], SiteHeader()), grey_layout(@[ Above() ], UsernameHeader()), grey_layout(@[ Above() ], PasswordHeader()), nullptr); } @@ -139,14 +140,13 @@ // Matcher for the Copy username button in Password Details view. id<GREYMatcher> CopyUsernameButton() { return grey_allOf( - grey_interactable(), ButtonWithAccessibilityLabel([NSString stringWithFormat:@"%@: %@", l10n_util::GetNSString( IDS_IOS_SHOW_PASSWORD_VIEW_USERNAME), l10n_util::GetNSString( IDS_IOS_SETTINGS_USERNAME_COPY_BUTTON)]), - grey_layout(@[ Below() ], SiteHeader()), + grey_interactable(), grey_layout(@[ Below() ], SiteHeader()), grey_layout(@[ Below() ], UsernameHeader()), grey_layout(@[ Above() ], PasswordHeader()), nullptr); } @@ -154,26 +154,25 @@ // Matcher for the Copy password button in Password Details view. id<GREYMatcher> CopyPasswordButton() { return grey_allOf( - grey_interactable(), ButtonWithAccessibilityLabel([NSString stringWithFormat:@"%@: %@", l10n_util::GetNSString( IDS_IOS_SHOW_PASSWORD_VIEW_PASSWORD), l10n_util::GetNSString( IDS_IOS_SETTINGS_PASSWORD_COPY_BUTTON)]), - grey_layout(@[ Below() ], SiteHeader()), + grey_interactable(), grey_layout(@[ Below() ], SiteHeader()), grey_layout(@[ Below() ], UsernameHeader()), grey_layout(@[ Below() ], PasswordHeader()), nullptr); } // Matcher for the Copy site button in Password Details view. id<GREYMatcher> DeleteButton() { - return grey_allOf(grey_interactable(), - ButtonWithAccessibilityLabel(l10n_util::GetNSString( - IDS_IOS_SETTINGS_PASSWORD_DELETE_BUTTON)), - grey_layout(@[ Below() ], SiteHeader()), - grey_layout(@[ Below() ], UsernameHeader()), - grey_layout(@[ Below() ], PasswordHeader()), nullptr); + return grey_allOf( + ButtonWithAccessibilityLabel( + l10n_util::GetNSString(IDS_IOS_SETTINGS_PASSWORD_DELETE_BUTTON)), + grey_interactable(), grey_layout(@[ Below() ], SiteHeader()), + grey_layout(@[ Below() ], UsernameHeader()), + grey_layout(@[ Below() ], PasswordHeader()), nullptr); } } // namespace @@ -298,9 +297,6 @@ performAction:grey_tap()]; [[EarlGrey selectElementWithMatcher:PasswordsButton()] performAction:grey_tap()]; - - // Wait for UI components to finish loading. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; } // Tap back arrow, to get one level higher in settings. @@ -311,26 +307,17 @@ grey_accessibilityTrait( UIAccessibilityTraitButton), nil)] performAction:grey_tap()]; - - // Wait for UI components to finish loading. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; } // Tap Edit in any settings view. - (void)tapEdit { [[EarlGrey selectElementWithMatcher:EditButton()] performAction:grey_tap()]; - - // Wait for UI components to finish loading. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; } // Tap Done in any settings view. - (void)tapDone { [[EarlGrey selectElementWithMatcher:NavigationBarDoneButton()] performAction:grey_tap()]; - - // Wait for UI components to finish loading. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; } // Verifies the UI elements are accessible on the Passwords page. @@ -398,14 +385,12 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + NSString* snackbarLabel = l10n_util::GetNSString(IDS_IOS_SETTINGS_PASSWORD_WAS_COPIED_MESSAGE); // The tap checks the existence of the snackbar and also closes it. [[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(snackbarLabel)] performAction:grey_tap()]; - // Wait until the fade-out animation completes. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; // Check the snackbar in case of failed reauthentication. mock_reauthentication_module.shouldSucceed = NO; @@ -415,14 +400,12 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + snackbarLabel = l10n_util::GetNSString(IDS_IOS_SETTINGS_PASSWORD_WAS_NOT_COPIED_MESSAGE); // The tap checks the existence of the snackbar and also closes it. [[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(snackbarLabel)] performAction:grey_tap()]; - // Wait until the fade-out animation completes. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [self tapBackArrow]; [self tapBackArrow]; @@ -449,14 +432,12 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + NSString* snackbarLabel = l10n_util::GetNSString(IDS_IOS_SETTINGS_USERNAME_WAS_COPIED_MESSAGE); // The tap checks the existence of the snackbar and also closes it. [[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(snackbarLabel)] performAction:grey_tap()]; - // Wait until the fade-out animation completes. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [self tapBackArrow]; [self tapBackArrow]; @@ -483,14 +464,12 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + NSString* snackbarLabel = l10n_util::GetNSString(IDS_IOS_SETTINGS_SITE_WAS_COPIED_MESSAGE); // The tap checks the existence of the snackbar and also closes it. [[EarlGrey selectElementWithMatcher:grey_accessibilityLabel(snackbarLabel)] performAction:grey_tap()]; - // Wait until the fade-out animation completes. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [self tapBackArrow]; [self tapBackArrow]; @@ -500,8 +479,12 @@ // Checks that deleting a password from password details view goes back to the // list-of-passwords view. -// TODO(crbug.com/739395): Fix. -- (void)DISABLED_testDeletion { +- (void)testDeletion { +// TODO(crbug.com/739395): Fix on device. +#if !TARGET_IPHONE_SIMULATOR + EARL_GREY_TEST_DISABLED(@"Test disabled on device, failed on iPad."); +#endif + [self scopedEnablePasswordManagementAndViewingUI]; // Save form to be deleted later. @@ -519,18 +502,16 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; // Tap the alert's Delete... button to confirm. [[EarlGrey selectElementWithMatcher:grey_allOf( - grey_interactable(), - grey_sufficientlyVisible(), ButtonWithAccessibilityLabel( l10n_util::GetNSString( IDS_IOS_CONFIRM_PASSWORD_DELETION)), - nullptr)] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + grey_interactable(), + grey_sufficientlyVisible(), nullptr)] + performAction:grey_tap()]; // Check that the current view is now the list view, by locating the header // of the list of passwords. @@ -541,7 +522,6 @@ nullptr)] assertWithMatcher:grey_notNil()]; // Also verify that the removed password is no longer in the list. - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; [[EarlGrey selectElementWithMatcher:Entry(@"https://example.com, user")] assertWithMatcher:grey_not(grey_sufficientlyVisible())]; @@ -551,8 +531,11 @@ } // Checks that deleting a password from password details can be cancelled. -// TODO(crbug.com/739395): Fix. -- (void)DISABLED_testCancelDeletion { +- (void)testCancelDeletion { +// TODO(crbug.com/739395): Fix on device. +#if !TARGET_IPHONE_SIMULATOR + EARL_GREY_TEST_DISABLED(@"Test disabled on device, failed on iPad."); +#endif [self scopedEnablePasswordManagementAndViewingUI]; // Save form to be deleted later. @@ -570,18 +553,16 @@ onElementWithMatcher:grey_accessibilityID( @"PasswordDetailsCollectionViewController")] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; // Tap the alert's Cancel button to cancel. [[EarlGrey selectElementWithMatcher:grey_allOf( - grey_interactable(), - grey_sufficientlyVisible(), ButtonWithAccessibilityLabel( l10n_util::GetNSString( IDS_IOS_CANCEL_PASSWORD_DELETION)), - nullptr)] performAction:grey_tap()]; - [[GREYUIThreadExecutor sharedInstance] drainUntilIdle]; + grey_interactable(), + grey_sufficientlyVisible(), nullptr)] + performAction:grey_tap()]; // Check that the current view is still the detail view, by locating the Copy // button. @@ -599,4 +580,29 @@ [self clearPasswordStore]; } +// Checks that if the list view is in edit mode, then the details password view +// is not accessible on tapping the entries. +- (void)testEditMode { + [self scopedEnablePasswordManagementAndViewingUI]; + + // Save a form to have something to tap on. + [self saveExamplePasswordForm]; + + [self openPasswordSettings]; + + [self tapEdit]; + + [[EarlGrey selectElementWithMatcher:Entry(@"https://example.com, user")] + performAction:grey_tap()]; + + // Check that the current view is not the detail view, by failing to locate + // the Copy button. + [[EarlGrey selectElementWithMatcher:CopyPasswordButton()] + assertWithMatcher:grey_nil()]; + + [self tapBackArrow]; + [self tapDone]; + [self clearPasswordStore]; +} + @end
diff --git a/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm b/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm index 3be5a483..d1a678d4 100644 --- a/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.mm
@@ -447,7 +447,7 @@ [super collectionView:collectionView didSelectItemAtIndexPath:indexPath]; // Actions should only take effect when not in editing mode. - if (self.editing) { + if ([self.editor isEditing]) { return; }
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm index 6be3942..2acbaba4 100644 --- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -1083,13 +1083,13 @@ #pragma mark ChromeIdentityServiceObserver -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { if (identity == _identity) { [self reloadAccountCell]; } } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm index b79c346..64d7070 100644 --- a/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm +++ b/ios/chrome/browser/ui/settings/sync_settings_collection_view_controller.mm
@@ -952,7 +952,7 @@ #pragma mark - ChromeIdentityServiceObserver -- (void)onProfileUpdate:(ChromeIdentity*)identity { +- (void)profileUpdate:(ChromeIdentity*)identity { CollectionViewAccountItem* item = base::mac::ObjCCastStrict<CollectionViewAccountItem>( [_identityMap objectForKey:identity.gaiaID]); @@ -964,7 +964,7 @@ [self reconfigureCellsForItems:@[ item ]]; } -- (void)onChromeIdentityServiceWillBeDestroyed { +- (void)chromeIdentityServiceWillBeDestroyed { _identityServiceObserver.reset(); }
diff --git a/ios/chrome/browser/ui/stack_view/BUILD.gn b/ios/chrome/browser/ui/stack_view/BUILD.gn index 4f510a2..2e21fc2 100644 --- a/ios/chrome/browser/ui/stack_view/BUILD.gn +++ b/ios/chrome/browser/ui/stack_view/BUILD.gn
@@ -2,55 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -bundle_data("resources") { - sources = [ - "resources/border_frame_bottom.png", - "resources/border_frame_bottom@2x.png", - "resources/border_frame_bottom@3x.png", - "resources/border_frame_incognito_bottom.png", - "resources/border_frame_incognito_bottom@2x.png", - "resources/border_frame_incognito_bottom@3x.png", - "resources/border_frame_incognito_left.png", - "resources/border_frame_incognito_left@2x.png", - "resources/border_frame_incognito_left@3x.png", - "resources/border_frame_incognito_right.png", - "resources/border_frame_incognito_right@2x.png", - "resources/border_frame_incognito_right@3x.png", - "resources/border_frame_incognito_top.png", - "resources/border_frame_incognito_top@2x.png", - "resources/border_frame_incognito_top@3x.png", - "resources/border_frame_left.png", - "resources/border_frame_left@2x.png", - "resources/border_frame_left@3x.png", - "resources/border_frame_right.png", - "resources/border_frame_right@2x.png", - "resources/border_frame_right@3x.png", - "resources/border_frame_top.png", - "resources/border_frame_top@2x.png", - "resources/border_frame_top@3x.png", - "resources/card_close_button.png", - "resources/card_close_button@2x.png", - "resources/card_close_button@3x.png", - "resources/card_close_button_incognito.png", - "resources/card_close_button_incognito@2x.png", - "resources/card_close_button_incognito@3x.png", - "resources/card_close_button_pressed.png", - "resources/card_close_button_pressed@2x.png", - "resources/card_close_button_pressed@3x.png", - "resources/card_frame_shadow.png", - "resources/card_frame_shadow@2x.png", - "resources/card_frame_shadow@3x.png", - "resources/stack_view_background_noise.jpg", - "resources/stack_view_background_noise@2x.jpg", - "resources/stack_view_background_noise@2x~ipad.jpg", - "resources/stack_view_background_noise@3x.jpg", - "resources/stack_view_background_noise~ipad.jpg", - ] - outputs = [ - "{{bundle_resources_dir}}/{{source_file_part}}", - ] -} - source_set("stack_view") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ @@ -77,7 +28,19 @@ "title_label.mm", ] deps = [ - ":resources", + "resources:border_frame_bottom", + "resources:border_frame_incognito_bottom", + "resources:border_frame_incognito_left", + "resources:border_frame_incognito_right", + "resources:border_frame_incognito_top", + "resources:border_frame_left", + "resources:border_frame_right", + "resources:border_frame_top", + "resources:card_close_button", + "resources:card_close_button_incognito", + "resources:card_close_button_pressed", + "resources:card_frame_shadow", + "resources:stack_view_background_noise", "//base", "//components/strings", "//ios/chrome/app/strings",
diff --git a/ios/chrome/browser/ui/stack_view/resources/BUILD.gn b/ios/chrome/browser/ui/stack_view/resources/BUILD.gn new file mode 100644 index 0000000..f324f55d --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/BUILD.gn
@@ -0,0 +1,124 @@ +# 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("//build/config/ios/imageset.gni") + +imageset("border_frame_bottom") { + sources = [ + "border_frame_bottom.imageset/Contents.json", + "border_frame_bottom.imageset/border_frame_bottom.png", + "border_frame_bottom.imageset/border_frame_bottom@2x.png", + "border_frame_bottom.imageset/border_frame_bottom@3x.png", + ] +} + +imageset("border_frame_incognito_bottom") { + sources = [ + "border_frame_incognito_bottom.imageset/Contents.json", + "border_frame_incognito_bottom.imageset/border_frame_incognito_bottom.png", + "border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@2x.png", + "border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@3x.png", + ] +} + +imageset("border_frame_incognito_left") { + sources = [ + "border_frame_incognito_left.imageset/Contents.json", + "border_frame_incognito_left.imageset/border_frame_incognito_left.png", + "border_frame_incognito_left.imageset/border_frame_incognito_left@2x.png", + "border_frame_incognito_left.imageset/border_frame_incognito_left@3x.png", + ] +} + +imageset("border_frame_incognito_right") { + sources = [ + "border_frame_incognito_right.imageset/Contents.json", + "border_frame_incognito_right.imageset/border_frame_incognito_right.png", + "border_frame_incognito_right.imageset/border_frame_incognito_right@2x.png", + "border_frame_incognito_right.imageset/border_frame_incognito_right@3x.png", + ] +} + +imageset("border_frame_incognito_top") { + sources = [ + "border_frame_incognito_top.imageset/Contents.json", + "border_frame_incognito_top.imageset/border_frame_incognito_top.png", + "border_frame_incognito_top.imageset/border_frame_incognito_top@2x.png", + "border_frame_incognito_top.imageset/border_frame_incognito_top@3x.png", + ] +} + +imageset("border_frame_left") { + sources = [ + "border_frame_left.imageset/Contents.json", + "border_frame_left.imageset/border_frame_left.png", + "border_frame_left.imageset/border_frame_left@2x.png", + "border_frame_left.imageset/border_frame_left@3x.png", + ] +} + +imageset("border_frame_right") { + sources = [ + "border_frame_right.imageset/Contents.json", + "border_frame_right.imageset/border_frame_right.png", + "border_frame_right.imageset/border_frame_right@2x.png", + "border_frame_right.imageset/border_frame_right@3x.png", + ] +} + +imageset("border_frame_top") { + sources = [ + "border_frame_top.imageset/Contents.json", + "border_frame_top.imageset/border_frame_top.png", + "border_frame_top.imageset/border_frame_top@2x.png", + "border_frame_top.imageset/border_frame_top@3x.png", + ] +} + +imageset("card_close_button") { + sources = [ + "card_close_button.imageset/Contents.json", + "card_close_button.imageset/card_close_button.png", + "card_close_button.imageset/card_close_button@2x.png", + "card_close_button.imageset/card_close_button@3x.png", + ] +} + +imageset("card_close_button_incognito") { + sources = [ + "card_close_button_incognito.imageset/Contents.json", + "card_close_button_incognito.imageset/card_close_button_incognito.png", + "card_close_button_incognito.imageset/card_close_button_incognito@2x.png", + "card_close_button_incognito.imageset/card_close_button_incognito@3x.png", + ] +} + +imageset("card_close_button_pressed") { + sources = [ + "card_close_button_pressed.imageset/Contents.json", + "card_close_button_pressed.imageset/card_close_button_pressed.png", + "card_close_button_pressed.imageset/card_close_button_pressed@2x.png", + "card_close_button_pressed.imageset/card_close_button_pressed@3x.png", + ] +} + +imageset("card_frame_shadow") { + sources = [ + "card_frame_shadow.imageset/Contents.json", + "card_frame_shadow.imageset/card_frame_shadow.png", + "card_frame_shadow.imageset/card_frame_shadow@2x.png", + "card_frame_shadow.imageset/card_frame_shadow@3x.png", + ] +} + +imageset("stack_view_background_noise") { + sources = [ + "stack_view_background_noise.imageset/Contents.json", + "stack_view_background_noise.imageset/stack_view_background_noise.jpg", + "stack_view_background_noise.imageset/stack_view_background_noise@2x.jpg", + "stack_view_background_noise.imageset/stack_view_background_noise@2x~ipad.jpg", + "stack_view_background_noise.imageset/stack_view_background_noise@3x.jpg", + "stack_view_background_noise.imageset/stack_view_background_noise~ipad.jpg", + ] +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/Contents.json new file mode 100644 index 0000000..e1e3477 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_bottom.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_bottom@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_bottom@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_bottom@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_bottom@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_bottom.imageset/border_frame_bottom@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/Contents.json new file mode 100644 index 0000000..94f5bd2 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_incognito_bottom.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_incognito_bottom@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_incognito_bottom@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_bottom.imageset/border_frame_incognito_bottom@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/Contents.json new file mode 100644 index 0000000..e7b64d6 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_incognito_left.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_incognito_left@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_incognito_left@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_left.imageset/border_frame_incognito_left@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/Contents.json new file mode 100644 index 0000000..5ad683b9 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_incognito_right.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_incognito_right@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_incognito_right@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_right.imageset/border_frame_incognito_right@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/Contents.json new file mode 100644 index 0000000..f649811a7 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_incognito_top.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_incognito_top@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_incognito_top@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_incognito_top.imageset/border_frame_incognito_top@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/Contents.json new file mode 100644 index 0000000..1997020a --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_left.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_left@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_left@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_left.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_left.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_left@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_left@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_left@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_left@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_left.imageset/border_frame_left@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/Contents.json new file mode 100644 index 0000000..fd83c9b --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_right.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_right@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_right@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_right.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_right.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_right@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_right@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_right@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_right@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_right.imageset/border_frame_right@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/Contents.json new file mode 100644 index 0000000..8c62a22 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "border_frame_top.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "border_frame_top@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "border_frame_top@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_top.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_top.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_top@2x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_top@2x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/border_frame_top@3x.png b/ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/border_frame_top@3x.png rename to ios/chrome/browser/ui/stack_view/resources/border_frame_top.imageset/border_frame_top@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/Contents.json new file mode 100644 index 0000000..de1a30b --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "card_close_button.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "card_close_button@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "card_close_button@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button@2x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button@2x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button@3x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button@3x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button.imageset/card_close_button@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/Contents.json new file mode 100644 index 0000000..ae98b5d1 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "card_close_button_incognito.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "card_close_button_incognito@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "card_close_button_incognito@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito@2x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito@2x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito@3x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito@3x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_incognito.imageset/card_close_button_incognito@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/Contents.json new file mode 100644 index 0000000..7ac7e714 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "card_close_button_pressed.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "card_close_button_pressed@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "card_close_button_pressed@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed@2x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed@2x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed@3x.png b/ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed@3x.png rename to ios/chrome/browser/ui/stack_view/resources/card_close_button_pressed.imageset/card_close_button_pressed@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/Contents.json new file mode 100644 index 0000000..ce4612b1 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/Contents.json
@@ -0,0 +1,23 @@ +{ + "images": [ + { + "idiom": "universal", + "scale": "1x", + "filename": "card_frame_shadow.png" + }, + { + "idiom": "universal", + "scale": "2x", + "filename": "card_frame_shadow@2x.png" + }, + { + "idiom": "universal", + "scale": "3x", + "filename": "card_frame_shadow@3x.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.png b/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.png rename to ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow@2x.png b/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow@2x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_frame_shadow@2x.png rename to ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow@2x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow@3x.png b/ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow@3x.png similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/card_frame_shadow@3x.png rename to ios/chrome/browser/ui/stack_view/resources/card_frame_shadow.imageset/card_frame_shadow@3x.png Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/Contents.json b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/Contents.json new file mode 100644 index 0000000..2dfdd06 --- /dev/null +++ b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/Contents.json
@@ -0,0 +1,33 @@ +{ + "images": [ + { + "idiom": "iphone", + "scale": "1x", + "filename": "stack_view_background_noise.jpg" + }, + { + "idiom": "iphone", + "scale": "2x", + "filename": "stack_view_background_noise@2x.jpg" + }, + { + "idiom": "ipad", + "scale": "2x", + "filename": "stack_view_background_noise@2x~ipad.jpg" + }, + { + "idiom": "iphone", + "scale": "3x", + "filename": "stack_view_background_noise@3x.jpg" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "stack_view_background_noise~ipad.jpg" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.jpg b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise.jpg similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.jpg rename to ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise.jpg Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@2x.jpg b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@2x.jpg similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@2x.jpg rename to ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@2x.jpg Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@2x~ipad.jpg b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@2x~ipad.jpg similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@2x~ipad.jpg rename to ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@2x~ipad.jpg Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@3x.jpg b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@3x.jpg similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise@3x.jpg rename to ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise@3x.jpg Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise~ipad.jpg b/ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise~ipad.jpg similarity index 100% rename from ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise~ipad.jpg rename to ios/chrome/browser/ui/stack_view/resources/stack_view_background_noise.imageset/stack_view_background_noise~ipad.jpg Binary files differ
diff --git a/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm b/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm index 8960e4f9..357dd92 100644 --- a/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm +++ b/ios/chrome/browser/ui/stack_view/stack_view_toolbar_controller.mm
@@ -30,7 +30,7 @@ } - (instancetype)initWithStackViewToolbar { - self = [super initWithStyle:ToolbarControllerStyleDarkMode]; + self = [super initWithStyle:ToolbarControllerStyleDarkMode dispatcher:nil]; if (self) { _stackViewToolbar = [[UIView alloc] initWithFrame:[self specificControlsArea]];
diff --git a/ios/chrome/browser/ui/tabs/BUILD.gn b/ios/chrome/browser/ui/tabs/BUILD.gn index 4141a2f..5f90849ff 100644 --- a/ios/chrome/browser/ui/tabs/BUILD.gn +++ b/ios/chrome/browser/ui/tabs/BUILD.gn
@@ -2,41 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -bundle_data("resources") { - sources = [ - "resources/tabstrip_background_tab@2x~ipad.png", - "resources/tabstrip_background_tab~ipad.png", - "resources/tabstrip_foreground_tab@2x~ipad.png", - "resources/tabstrip_foreground_tab~ipad.png", - "resources/tabstrip_incognito_background_tab@2x~ipad.png", - "resources/tabstrip_incognito_background_tab~ipad.png", - "resources/tabstrip_incognito_foreground_tab@2x~ipad.png", - "resources/tabstrip_incognito_foreground_tab~ipad.png", - "resources/tabstrip_new_tab@2x~ipad.png", - "resources/tabstrip_new_tab_incognito@2x~ipad.png", - "resources/tabstrip_new_tab_incognito_pressed@2x~ipad.png", - "resources/tabstrip_new_tab_incognito_pressed~ipad.png", - "resources/tabstrip_new_tab_incognito~ipad.png", - "resources/tabstrip_new_tab_pressed@2x~ipad.png", - "resources/tabstrip_new_tab_pressed~ipad.png", - "resources/tabstrip_new_tab~ipad.png", - "resources/tabstrip_tab_close@2x~ipad.png", - "resources/tabstrip_tab_close_incognito@2x~ipad.png", - "resources/tabstrip_tab_close_incognito_pressed@2x~ipad.png", - "resources/tabstrip_tab_close_incognito_pressed~ipad.png", - "resources/tabstrip_tab_close_incognito~ipad.png", - "resources/tabstrip_tab_close_pressed@2x~ipad.png", - "resources/tabstrip_tab_close_pressed~ipad.png", - "resources/tabstrip_tab_close~ipad.png", - "resources/tabstrip_toggle_button_gradient@2x~ipad.png", - "resources/tabstrip_toggle_button_gradient@3x~ipad.png", - "resources/tabstrip_toggle_button_gradient~ipad.png", - ] - outputs = [ - "{{bundle_resources_dir}}/{{source_file_part}}", - ] -} - source_set("tabs") { configs += [ "//build/config/compiler:enable_arc" ] sources = [ @@ -55,7 +20,19 @@ "//ios/chrome/browser/tabs", ] deps = [ - ":resources", + "resources:tabstrip_background_tab", + "resources:tabstrip_foreground_tab", + "resources:tabstrip_incognito_background_tab", + "resources:tabstrip_incognito_foreground_tab", + "resources:tabstrip_new_tab", + "resources:tabstrip_new_tab_incognito", + "resources:tabstrip_new_tab_incognito_pressed", + "resources:tabstrip_new_tab_pressed", + "resources:tabstrip_tab_close", + "resources:tabstrip_tab_close_incognito", + "resources:tabstrip_tab_close_incognito_pressed", + "resources:tabstrip_tab_close_pressed", + "resources:tabstrip_toggle_button_gradient", "//base", "//base:i18n", "//ios/chrome/app/strings",
diff --git a/ios/chrome/browser/ui/tabs/resources/BUILD.gn b/ios/chrome/browser/ui/tabs/resources/BUILD.gn new file mode 100644 index 0000000..5dac694c --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/BUILD.gn
@@ -0,0 +1,109 @@ +# 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("//build/config/ios/imageset.gni") + +imageset("tabstrip_background_tab") { + sources = [ + "tabstrip_background_tab.imageset/Contents.json", + "tabstrip_background_tab.imageset/tabstrip_background_tab@2x~ipad.png", + "tabstrip_background_tab.imageset/tabstrip_background_tab~ipad.png", + ] +} + +imageset("tabstrip_foreground_tab") { + sources = [ + "tabstrip_foreground_tab.imageset/Contents.json", + "tabstrip_foreground_tab.imageset/tabstrip_foreground_tab@2x~ipad.png", + "tabstrip_foreground_tab.imageset/tabstrip_foreground_tab~ipad.png", + ] +} + +imageset("tabstrip_incognito_background_tab") { + sources = [ + "tabstrip_incognito_background_tab.imageset/Contents.json", + "tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab@2x~ipad.png", + "tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab~ipad.png", + ] +} + +imageset("tabstrip_incognito_foreground_tab") { + sources = [ + "tabstrip_incognito_foreground_tab.imageset/Contents.json", + "tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab@2x~ipad.png", + "tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab~ipad.png", + ] +} + +imageset("tabstrip_new_tab") { + sources = [ + "tabstrip_new_tab.imageset/Contents.json", + "tabstrip_new_tab.imageset/tabstrip_new_tab@2x~ipad.png", + "tabstrip_new_tab.imageset/tabstrip_new_tab~ipad.png", + ] +} + +imageset("tabstrip_new_tab_incognito") { + sources = [ + "tabstrip_new_tab_incognito.imageset/Contents.json", + "tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito@2x~ipad.png", + "tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito~ipad.png", + ] +} + +imageset("tabstrip_new_tab_incognito_pressed") { + sources = [ + "tabstrip_new_tab_incognito_pressed.imageset/Contents.json", + "tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed@2x~ipad.png", + "tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed~ipad.png", + ] +} + +imageset("tabstrip_new_tab_pressed") { + sources = [ + "tabstrip_new_tab_pressed.imageset/Contents.json", + "tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed@2x~ipad.png", + "tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed~ipad.png", + ] +} + +imageset("tabstrip_tab_close") { + sources = [ + "tabstrip_tab_close.imageset/Contents.json", + "tabstrip_tab_close.imageset/tabstrip_tab_close@2x~ipad.png", + "tabstrip_tab_close.imageset/tabstrip_tab_close~ipad.png", + ] +} + +imageset("tabstrip_tab_close_incognito") { + sources = [ + "tabstrip_tab_close_incognito.imageset/Contents.json", + "tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito@2x~ipad.png", + "tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito~ipad.png", + ] +} + +imageset("tabstrip_tab_close_incognito_pressed") { + sources = [ + "tabstrip_tab_close_incognito_pressed.imageset/Contents.json", + "tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed@2x~ipad.png", + "tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed~ipad.png", + ] +} + +imageset("tabstrip_tab_close_pressed") { + sources = [ + "tabstrip_tab_close_pressed.imageset/Contents.json", + "tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed@2x~ipad.png", + "tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed~ipad.png", + ] +} + +imageset("tabstrip_toggle_button_gradient") { + sources = [ + "tabstrip_toggle_button_gradient.imageset/Contents.json", + "tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient@2x~ipad.png", + "tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient~ipad.png", + ] +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/Contents.json new file mode 100644 index 0000000..a2758fc --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_background_tab@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_background_tab~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/tabstrip_background_tab@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/tabstrip_background_tab@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/tabstrip_background_tab~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_background_tab.imageset/tabstrip_background_tab~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/Contents.json new file mode 100644 index 0000000..e634944 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_foreground_tab@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_foreground_tab~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/tabstrip_foreground_tab@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/tabstrip_foreground_tab@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/tabstrip_foreground_tab~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_foreground_tab.imageset/tabstrip_foreground_tab~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/Contents.json new file mode 100644 index 0000000..6afb423 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_incognito_background_tab@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_incognito_background_tab~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_background_tab.imageset/tabstrip_incognito_background_tab~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/Contents.json new file mode 100644 index 0000000..de4c499 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_incognito_foreground_tab@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_incognito_foreground_tab~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_incognito_foreground_tab.imageset/tabstrip_incognito_foreground_tab~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/Contents.json new file mode 100644 index 0000000..2e858e9 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_new_tab@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_new_tab~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/tabstrip_new_tab@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/tabstrip_new_tab@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/tabstrip_new_tab~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab.imageset/tabstrip_new_tab~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/Contents.json new file mode 100644 index 0000000..69a44e1 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_new_tab_incognito@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_new_tab_incognito~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito.imageset/tabstrip_new_tab_incognito~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/Contents.json new file mode 100644 index 0000000..ce746087 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_new_tab_incognito_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_new_tab_incognito_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_incognito_pressed.imageset/tabstrip_new_tab_incognito_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/Contents.json new file mode 100644 index 0000000..0e1b733 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_new_tab_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_new_tab_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_new_tab_pressed.imageset/tabstrip_new_tab_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/Contents.json new file mode 100644 index 0000000..ee084f7 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_tab_close@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_tab_close~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/tabstrip_tab_close@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/tabstrip_tab_close@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/tabstrip_tab_close~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close.imageset/tabstrip_tab_close~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/Contents.json new file mode 100644 index 0000000..50331861 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_tab_close_incognito@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_tab_close_incognito~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito.imageset/tabstrip_tab_close_incognito~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/Contents.json new file mode 100644 index 0000000..3276afd --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_tab_close_incognito_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_tab_close_incognito_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_incognito_pressed.imageset/tabstrip_tab_close_incognito_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/Contents.json new file mode 100644 index 0000000..359c0694 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_tab_close_pressed@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_tab_close_pressed~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_tab_close_pressed.imageset/tabstrip_tab_close_pressed~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/Contents.json b/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/Contents.json new file mode 100644 index 0000000..94601f0 --- /dev/null +++ b/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/Contents.json
@@ -0,0 +1,18 @@ +{ + "images": [ + { + "idiom": "ipad", + "scale": "2x", + "filename": "tabstrip_toggle_button_gradient@2x~ipad.png" + }, + { + "idiom": "ipad", + "scale": "1x", + "filename": "tabstrip_toggle_button_gradient~ipad.png" + } + ], + "info": { + "version": 1, + "author": "xcode" + } +}
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient@2x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient@2x~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient@2x~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient@2x~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient~ipad.png similarity index 100% rename from ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient~ipad.png rename to ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient.imageset/tabstrip_toggle_button_gradient~ipad.png Binary files differ
diff --git a/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient@3x~ipad.png b/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient@3x~ipad.png deleted file mode 100644 index b1acfd1..0000000 --- a/ios/chrome/browser/ui/tabs/resources/tabstrip_toggle_button_gradient@3x~ipad.png +++ /dev/null Binary files differ
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_controller.h b/ios/chrome/browser/ui/toolbar/toolbar_controller.h index fd9c388..d85fca6 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_controller.h +++ b/ios/chrome/browser/ui/toolbar/toolbar_controller.h
@@ -18,6 +18,7 @@ #include "ios/chrome/browser/ui/ui_util.h" #import "ios/chrome/browser/ui/util/relaxed_bounds_constraints_hittest.h" +@protocol BrowserCommands; class ReadingListModel; @class ToolsMenuConfiguration; @@ -134,8 +135,15 @@ // The reading list model reflected by the toolbar. @property(nonatomic, readwrite, assign) ReadingListModel* readingListModel; -// Designated initializer. |style| determines how the toolbar draws itself. +// The command dispatcher this and any subordinate objects should use. +@property(nonatomic, readonly, weak) id<BrowserCommands> dispatcher; + +// Designated initializer. +// |style| determines how the toolbar draws itself. +// |dispatcher| is is the dispatcher for calling methods handled in other +// parts of the app. - (instancetype)initWithStyle:(ToolbarControllerStyle)style + dispatcher:(id<BrowserCommands>)dispatcher NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE;
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_controller.mm b/ios/chrome/browser/ui/toolbar/toolbar_controller.mm index 9ceeae4..d3cdf8d1 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_controller.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_controller.mm
@@ -249,6 +249,7 @@ @synthesize shadowView = shadowView_; @synthesize toolsPopupController = toolsPopupController_; @synthesize style = style_; +@synthesize dispatcher = dispatcher_; - (void)setReadingListModel:(ReadingListModel*)readingListModel { readingListModel_ = readingListModel; @@ -259,10 +260,12 @@ } } -- (instancetype)initWithStyle:(ToolbarControllerStyle)style { +- (instancetype)initWithStyle:(ToolbarControllerStyle)style + dispatcher:(id<BrowserCommands>)dispatcher { self = [super init]; if (self) { style_ = style; + dispatcher_ = dispatcher; DCHECK_LT(style_, ToolbarControllerStyleMaxStyles); InterfaceIdiom idiom = IsIPadIdiom() ? IPAD_IDIOM : IPHONE_IDIOM; @@ -558,9 +561,12 @@ [button addTarget:self action:@selector(recordUserMetrics:) forControlEvents:UIControlEventTouchUpInside]; - [button addTarget:button - action:@selector(chromeExecuteCommand:) - forControlEvents:UIControlEventTouchUpInside]; + // Only register buttons with defined tags for -chromeExecuteCommand:. + if (button.tag) { + [button addTarget:button + action:@selector(chromeExecuteCommand:) + forControlEvents:UIControlEventTouchUpInside]; + } } - (CGRect)shareButtonAnchorRect {
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_controller_unittest.mm b/ios/chrome/browser/ui/toolbar/toolbar_controller_unittest.mm index 06979e0..6064f5c 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_controller_unittest.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_controller_unittest.mm
@@ -35,8 +35,9 @@ protected: void SetUp() override { PlatformTest::SetUp(); - toolbarController_ = [[ToolbarController alloc] - initWithStyle:ToolbarControllerStyleLightMode]; + toolbarController_ = + [[ToolbarController alloc] initWithStyle:ToolbarControllerStyleLightMode + dispatcher:nil]; } ToolbarController* toolbarController_;
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_egtest.mm b/ios/chrome/browser/ui/toolbar/toolbar_egtest.mm index 9322f86..239dcf9 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_egtest.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_egtest.mm
@@ -380,7 +380,7 @@ if (IsIPadIdiom()) { EARL_GREY_TEST_DISABLED(@"Disabled for iPad due to a simulator bug."); } - SelectNewTabPagePanel(NewTabPage::kMostVisitedPanel); + SelectNewTabPagePanel(NewTabPage::kHomePanel); id<GREYMatcher> locationbarButton = grey_allOf( grey_accessibilityLabel(l10n_util::GetNSString(IDS_OMNIBOX_EMPTY_HINT)), @@ -469,7 +469,7 @@ [[EarlGrey selectElementWithMatcher:chrome_test_util::Omnibox()] assertWithMatcher:chrome_test_util::OmniboxText("")]; - SelectNewTabPagePanel(NewTabPage::kMostVisitedPanel); + SelectNewTabPagePanel(NewTabPage::kHomePanel); } // Tests typing in the omnibox using the keyboard accessory view.
diff --git a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.h b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.h index 38f3812..4ae4ce5 100644 --- a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.h +++ b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.h
@@ -13,6 +13,7 @@ #include "ios/public/provider/chrome/browser/voice/voice_search_controller_delegate.h" #include "ios/web/public/navigation_item_list.h" +@protocol BrowserCommands; @protocol PreloadProvider; @class Tab; @protocol ToolbarFrameDelegate; @@ -88,7 +89,8 @@ @property(nonatomic, weak, readonly) id<UrlLoader> urlLoader; // Mark inherited initializer as unavailable. -- (instancetype)initWithStyle:(ToolbarControllerStyle)style NS_UNAVAILABLE; +- (instancetype)initWithStyle:(ToolbarControllerStyle)style + dispatcher:(id<BrowserCommands>)dispatcher NS_UNAVAILABLE; // Create a new web toolbar controller whose omnibox is backed by // |browserState|. @@ -96,6 +98,7 @@ urlLoader:(id<UrlLoader>)urlLoader browserState:(ios::ChromeBrowserState*)browserState preloadProvider:(id<PreloadProvider>)preloader + dispatcher:(id<BrowserCommands>)dispatcher NS_DESIGNATED_INITIALIZER; // Called when the browser state this object was initialized with is being
diff --git a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm index bedfe15b..40883a1 100644 --- a/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm +++ b/ios/chrome/browser/ui/toolbar/web_toolbar_controller.mm
@@ -37,6 +37,7 @@ #import "ios/chrome/browser/ui/animation_util.h" #import "ios/chrome/browser/ui/colors/MDCPalette+CrAdditions.h" #import "ios/chrome/browser/ui/commands/UIKit+ChromeExecuteCommand.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/generic_chrome_command.h" #include "ios/chrome/browser/ui/commands/ios_command_ids.h" #import "ios/chrome/browser/ui/history/tab_history_popup_controller.h" @@ -369,7 +370,8 @@ - (instancetype)initWithDelegate:(id<WebToolbarDelegate>)delegate urlLoader:(id<UrlLoader>)urlLoader browserState:(ios::ChromeBrowserState*)browserState - preloadProvider:(id<PreloadProvider>)preloader { + preloadProvider:(id<PreloadProvider>)preloader + dispatcher:(id<BrowserCommands>)dispatcher { DCHECK(delegate); DCHECK(urlLoader); DCHECK(browserState); @@ -377,8 +379,10 @@ _urlLoader = urlLoader; _browserState = browserState; _incognito = browserState->IsOffTheRecord(); - self = [super initWithStyle:(_incognito ? ToolbarControllerStyleIncognitoMode - : ToolbarControllerStyleLightMode)]; + ToolbarControllerStyle style = + (_incognito ? ToolbarControllerStyleIncognitoMode + : ToolbarControllerStyleLightMode); + self = [super initWithStyle:style dispatcher:dispatcher]; if (!self) return nil; @@ -479,6 +483,13 @@ [_backButton setEnabled:NO]; [_forwardButton setEnabled:NO]; + // Assign tags before calling -setUpButton, since only buttons with tags + // have -chromeExecuteCommand added as a target. + [_reloadButton setTag:IDC_RELOAD]; + [_stopButton setTag:IDC_STOP]; + [_starButton setTag:IDC_BOOKMARK_PAGE]; + [_voiceSearchButton setTag:IDC_VOICE_SEARCH]; + if (idiom == IPAD_IDIOM) { // Note that the reload button gets repositioned when -layoutOmnibox is // called. @@ -542,6 +553,14 @@ hasDisabledImage:YES synchronously:NO]; + // Assign targets for buttons using the dispatcher. + [_backButton addTarget:self.dispatcher + action:@selector(goBack) + forControlEvents:UIControlEventTouchUpInside]; + [_forwardButton addTarget:self.dispatcher + action:@selector(goForward) + forControlEvents:UIControlEventTouchUpInside]; + _backButtonMode = ToolbarButtonModeNormal; _forwardButtonMode = ToolbarButtonModeNormal; UILongPressGestureRecognizer* backLongPress = @@ -569,13 +588,6 @@ action:@selector(cancelOmniboxEdit) forControlEvents:UIControlEventTouchUpInside]; - [_backButton setTag:IDC_BACK]; - [_forwardButton setTag:IDC_FORWARD]; - [_reloadButton setTag:IDC_RELOAD]; - [_stopButton setTag:IDC_STOP]; - [_starButton setTag:IDC_BOOKMARK_PAGE]; - [_voiceSearchButton setTag:IDC_VOICE_SEARCH]; - SetA11yLabelAndUiAutomationName(_backButton, IDS_ACCNAME_BACK, @"Back"); SetA11yLabelAndUiAutomationName(_forwardButton, IDS_ACCNAME_FORWARD, @"Forward");
diff --git a/ios/chrome/browser/ui/toolbar/web_toolbar_controller_unittest.mm b/ios/chrome/browser/ui/toolbar/web_toolbar_controller_unittest.mm index 500e4b24..163ecf7 100644 --- a/ios/chrome/browser/ui/toolbar/web_toolbar_controller_unittest.mm +++ b/ios/chrome/browser/ui/toolbar/web_toolbar_controller_unittest.mm
@@ -77,7 +77,8 @@ initWithDelegate:delegate urlLoader:urlLoader browserState:chrome_browser_state_.get() - preloadProvider:nil]; + preloadProvider:nil + dispatcher:nil]; [web_toolbar_controller_ setUnitTesting:YES]; } void TearDown() override {
diff --git a/ios/chrome/browser/ui/webui/net_export/net_export_ui.cc b/ios/chrome/browser/ui/webui/net_export/net_export_ui.cc index cf1a6fd..d5358ea 100644 --- a/ios/chrome/browser/ui/webui/net_export/net_export_ui.cc +++ b/ios/chrome/browser/ui/webui/net_export/net_export_ui.cc
@@ -17,8 +17,8 @@ #include "base/values.h" #include "components/grit/components_resources.h" #include "components/net_log/chrome_net_log.h" +#include "components/net_log/net_export_file_writer.h" #include "components/net_log/net_export_ui_constants.h" -#include "components/net_log/net_log_file_writer.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_url_constants.h" @@ -51,7 +51,7 @@ class NetExportMessageHandler : public web::WebUIIOSMessageHandler, public base::SupportsWeakPtr<NetExportMessageHandler>, - public net_log::NetLogFileWriter::StateObserver { + public net_log::NetExportFileWriter::StateObserver { public: NetExportMessageHandler(); ~NetExportMessageHandler() override; @@ -65,7 +65,7 @@ void OnStopNetLog(const base::ListValue* list); void OnSendNetLog(const base::ListValue* list); - // net_log::NetLogFileWriter::StateObserver implementation. + // net_log::NetExportFileWriter::StateObserver implementation. void OnNewState(const base::DictionaryValue& state) override; private: @@ -75,12 +75,12 @@ void NotifyUIWithState( std::unique_ptr<base::DictionaryValue> file_writer_state); - // Cache of GetApplicationContex()->GetNetLog()->net_log_file_writer(). This - // is owned by ChromeNetLog which is owned by BrowserProcessImpl. - net_log::NetLogFileWriter* file_writer_; + // Cache of GetApplicationContex()->GetNetLog()->net_export_file_writer(). + // This is owned by ChromeNetLog which is owned by BrowserProcessImpl. + net_log::NetExportFileWriter* file_writer_; - ScopedObserver<net_log::NetLogFileWriter, - net_log::NetLogFileWriter::StateObserver> + ScopedObserver<net_log::NetExportFileWriter, + net_log::NetExportFileWriter::StateObserver> state_observer_manager_; base::WeakPtrFactory<NetExportMessageHandler> weak_ptr_factory_; @@ -89,7 +89,8 @@ }; NetExportMessageHandler::NetExportMessageHandler() - : file_writer_(GetApplicationContext()->GetNetLog()->net_log_file_writer()), + : file_writer_( + GetApplicationContext()->GetNetLog()->net_export_file_writer()), state_observer_manager_(this), weak_ptr_factory_(this) { file_writer_->Initialize( @@ -139,7 +140,7 @@ DCHECK(result); net::NetLogCaptureMode capture_mode = - net_log::NetLogFileWriter::CaptureModeFromString(capture_mode_string); + net_log::NetExportFileWriter::CaptureModeFromString(capture_mode_string); file_writer_->StartNetLog( base::FilePath(), capture_mode, base::CommandLine::ForCurrentProcess()->GetCommandLineString(),
diff --git a/ios/chrome/browser/web/cache_egtest.mm b/ios/chrome/browser/web/cache_egtest.mm index 69e1eaa9..8926dc1 100644 --- a/ios/chrome/browser/web/cache_egtest.mm +++ b/ios/chrome/browser/web/cache_egtest.mm
@@ -170,9 +170,7 @@ // Navigates back to the previous webpage. // TODO(crbug.com/638674): Evaluate if this can move to shared code. - (void)goBack { - GenericChromeCommand* backCommand = - [[GenericChromeCommand alloc] initWithTag:IDC_BACK]; - chrome_test_util::RunCommandWithActiveViewController(backCommand); + [chrome_test_util::BrowserCommandDispatcherForMainBVC() goBack]; [ChromeEarlGrey waitForPageToFinishLoading]; }
diff --git a/ios/chrome/browser/web/progress_indicator_egtest.mm b/ios/chrome/browser/web/progress_indicator_egtest.mm index 5f5daf7..f82a548e 100644 --- a/ios/chrome/browser/web/progress_indicator_egtest.mm +++ b/ios/chrome/browser/web/progress_indicator_egtest.mm
@@ -160,8 +160,7 @@ // Tests that the progress indicator is shown and has expected progress value // after a form is submitted, and the toolbar is visible. -// TODO(crbug.com/734874): Reenable test when fixed. -- (void)DISABLED_testProgressIndicatorShownOnFormSubmit { +- (void)testProgressIndicatorShownOnFormSubmit { if (IsIPadIdiom()) { EARL_GREY_TEST_SKIPPED(@"Skipped for iPad (no progress view in tablet)"); }
diff --git a/ios/chrome/browser/web/visible_url_egtest.mm b/ios/chrome/browser/web/visible_url_egtest.mm index c83999d..70ac2a1 100644 --- a/ios/chrome/browser/web/visible_url_egtest.mm +++ b/ios/chrome/browser/web/visible_url_egtest.mm
@@ -519,12 +519,9 @@ performAction:grey_tap()]; [ChromeEarlGrey waitForWebViewContainingText:kTestPage1]; - // Quickly (using chrome command) navigate forward twice and wait for - // kChromeUIVersionURL to load. - GenericChromeCommand* forwardCommand = - [[GenericChromeCommand alloc] initWithTag:IDC_FORWARD]; - chrome_test_util::RunCommandWithActiveViewController(forwardCommand); - chrome_test_util::RunCommandWithActiveViewController(forwardCommand); + // Quickly navigate forward twice and wait for kChromeUIVersionURL to load. + [chrome_test_util::BrowserCommandDispatcherForMainBVC() goForward]; + [chrome_test_util::BrowserCommandDispatcherForMainBVC() goForward]; const std::string version = version_info::GetVersionNumber(); [ChromeEarlGrey waitForWebViewContainingText:version];
diff --git a/ios/chrome/test/app/chrome_test_util.h b/ios/chrome/test/app/chrome_test_util.h index 3aa6108d..2dda8a4 100644 --- a/ios/chrome/test/app/chrome_test_util.h +++ b/ios/chrome/test/app/chrome_test_util.h
@@ -6,6 +6,7 @@ #define IOS_CHROME_TEST_APP_CHROME_TEST_UTIL_H_ #import "base/ios/block_types.h" +#import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/web/public/web_state/web_state.h" namespace ios { @@ -41,6 +42,9 @@ // Returns the number of key commands currently registered with the main BVC. NSUInteger GetRegisteredKeyCommandsCount(); +// Returns the dispatcher for the main BVC. +id<BrowserCommands> BrowserCommandDispatcherForMainBVC(); + // Runs |command| using the active view controller. void RunCommandWithActiveViewController(GenericChromeCommand* command);
diff --git a/ios/chrome/test/app/chrome_test_util.mm b/ios/chrome/test/app/chrome_test_util.mm index 32d669f..3a14989 100644 --- a/ios/chrome/test/app/chrome_test_util.mm +++ b/ios/chrome/test/app/chrome_test_util.mm
@@ -133,6 +133,12 @@ return mainBVC.keyCommands.count; } +id<BrowserCommands> BrowserCommandDispatcherForMainBVC() { + BrowserViewController* mainBVC = + GetMainController().browserViewInformation.mainBVC; + return mainBVC.dispatcher; +} + void RunCommandWithActiveViewController(GenericChromeCommand* command) { [GetActiveViewController() chromeExecuteCommand:command]; }
diff --git a/ios/chrome/test/earl_grey/chrome_earl_grey.mm b/ios/chrome/test/earl_grey/chrome_earl_grey.mm index af378f1..71b4eaf5 100644 --- a/ios/chrome/test/earl_grey/chrome_earl_grey.mm +++ b/ios/chrome/test/earl_grey/chrome_earl_grey.mm
@@ -122,16 +122,14 @@ } + (void)goBack { - base::scoped_nsobject<GenericChromeCommand> reloadCommand( - [[GenericChromeCommand alloc] initWithTag:IDC_BACK]); - chrome_test_util::RunCommandWithActiveViewController(reloadCommand); + [chrome_test_util::BrowserCommandDispatcherForMainBVC() goBack]; + [ChromeEarlGrey waitForPageToFinishLoading]; } + (void)goForward { - base::scoped_nsobject<GenericChromeCommand> reloadCommand( - [[GenericChromeCommand alloc] initWithTag:IDC_FORWARD]); - chrome_test_util::RunCommandWithActiveViewController(reloadCommand); + [chrome_test_util::BrowserCommandDispatcherForMainBVC() goForward]; + [ChromeEarlGrey waitForPageToFinishLoading]; }
diff --git a/ios/clean/chrome/browser/ui/ntp/ntp_mediator.mm b/ios/clean/chrome/browser/ui/ntp/ntp_mediator.mm index 042540b2..70794555 100644 --- a/ios/clean/chrome/browser/ui/ntp/ntp_mediator.mm +++ b/ios/clean/chrome/browser/ui/ntp/ntp_mediator.mm
@@ -43,7 +43,7 @@ NewTabPageBarItem* mostVisitedItem = [NewTabPageBarItem newTabPageBarItemWithTitle:mostVisited - identifier:NewTabPage::kMostVisitedPanel + identifier:NewTabPage::kHomePanel image:[UIImage imageNamed:@"ntp_mv_search"]]; NewTabPageBarItem* bookmarksItem = [NewTabPageBarItem newTabPageBarItemWithTitle:bookmarks
diff --git a/ios/clean/chrome/browser/ui/ntp/ntp_view_controller.mm b/ios/clean/chrome/browser/ui/ntp/ntp_view_controller.mm index 8493d29..4d026aa68 100644 --- a/ios/clean/chrome/browser/ui/ntp/ntp_view_controller.mm +++ b/ios/clean/chrome/browser/ui/ntp/ntp_view_controller.mm
@@ -153,7 +153,7 @@ if (item.identifier == NewTabPage::kBookmarksPanel && !self.bookmarksViewController) [self.dispatcher showNTPBookmarksPanel]; - else if (item.identifier == NewTabPage::kMostVisitedPanel && + else if (item.identifier == NewTabPage::kHomePanel && !self.homeViewController) [self.dispatcher showNTPHomePanel]; else if (item.identifier == NewTabPage::kOpenTabsPanel &&
diff --git a/ios/clean/chrome/browser/ui/tools/tools_mediator_unittest.mm b/ios/clean/chrome/browser/ui/tools/tools_mediator_unittest.mm index 06e1434..d73097b 100644 --- a/ios/clean/chrome/browser/ui/tools/tools_mediator_unittest.mm +++ b/ios/clean/chrome/browser/ui/tools/tools_mediator_unittest.mm
@@ -28,9 +28,8 @@ ToolsMediatorTest() : consumer_(OCMProtocolMock(@protocol(ToolsConsumer))), configuration_( - [[ToolsMenuConfiguration alloc] initWithDisplayView:nil]), - navigation_manager(base::MakeUnique<ToolbarTestNavigationManager>()) { - navigation_manager_ = navigation_manager.get(); + [[ToolsMenuConfiguration alloc] initWithDisplayView:nil]) { + auto navigation_manager = base::MakeUnique<ToolbarTestNavigationManager>(); test_web_state_.SetNavigationManager(std::move(navigation_manager)); } @@ -39,10 +38,6 @@ id consumer_; ToolsMenuConfiguration* configuration_; ToolbarTestWebState test_web_state_; - ToolbarTestNavigationManager* navigation_manager_; - - private: - std::unique_ptr<ToolbarTestNavigationManager> navigation_manager; }; TEST_F(ToolsMediatorTest, TestShowOverFlowControls) {
diff --git a/ios/shared/chrome/browser/ui/commands/command_dispatcher.mm b/ios/shared/chrome/browser/ui/commands/command_dispatcher.mm index 461edefa..62ae8548 100644 --- a/ios/shared/chrome/browser/ui/commands/command_dispatcher.mm +++ b/ios/shared/chrome/browser/ui/commands/command_dispatcher.mm
@@ -80,4 +80,13 @@ return [super forwardingTargetForSelector:selector]; } +// Overriden to return YES for any registered method. +- (BOOL)respondsToSelector:(SEL)selector { + auto target = _forwardingTargets.find(selector); + if (target != _forwardingTargets.end()) { + return YES; + } + return [super respondsToSelector:selector]; +} + @end
diff --git a/ios/shared/chrome/browser/ui/commands/command_dispatcher_unittest.mm b/ios/shared/chrome/browser/ui/commands/command_dispatcher_unittest.mm index adbda24..58353dc7 100644 --- a/ios/shared/chrome/browser/ui/commands/command_dispatcher_unittest.mm +++ b/ios/shared/chrome/browser/ui/commands/command_dispatcher_unittest.mm
@@ -338,3 +338,27 @@ EXPECT_TRUE(exception_caught); } + +// Tests that -respondsToSelector returns YES for methods once they are +// dispatched for. +// Tests handler methods with no arguments. +TEST(CommandDispatcherTest, RespondsToSelector) { + id dispatcher = [[CommandDispatcher alloc] init]; + + EXPECT_FALSE([dispatcher respondsToSelector:@selector(show)]); + CommandDispatcherTestSimpleTarget* target = + [[CommandDispatcherTestSimpleTarget alloc] init]; + + [dispatcher startDispatchingToTarget:target forSelector:@selector(show)]; + EXPECT_TRUE([dispatcher respondsToSelector:@selector(show)]); + + [dispatcher stopDispatchingForSelector:@selector(show)]; + EXPECT_FALSE([dispatcher respondsToSelector:@selector(show)]); + + // Actual dispatcher methods should still always advertise that they are + // responded to. + EXPECT_TRUE([dispatcher + respondsToSelector:@selector(startDispatchingToTarget:forSelector:)]); + EXPECT_TRUE( + [dispatcher respondsToSelector:@selector(stopDispatchingForSelector:)]); +}
diff --git a/ios/web/payments/payment_request.cc b/ios/web/payments/payment_request.cc index 8b6d3b2..7798b25 100644 --- a/ios/web/payments/payment_request.cc +++ b/ios/web/payments/payment_request.cc
@@ -362,7 +362,7 @@ result->SetString(kPaymentRequestId, this->payment_request_id); result->SetString(kPaymentResponseMethodName, this->method_name); - result->Set(kPaymentResponseDetails, this->details.ToDictionaryValue()); + result->SetString(kPaymentResponseDetails, this->details); if (!this->shipping_address.ToDictionaryValue()->empty()) { result->Set(kPaymentResponseShippingAddress, this->shipping_address.ToDictionaryValue());
diff --git a/ios/web/payments/payment_request_unittest.cc b/ios/web/payments/payment_request_unittest.cc index 3aeaee1..c80ccc4 100644 --- a/ios/web/payments/payment_request_unittest.cc +++ b/ios/web/payments/payment_request_unittest.cc
@@ -6,6 +6,7 @@ #include <vector> +#include "base/json/json_writer.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "components/payments/core/basic_card_response.h" @@ -263,9 +264,7 @@ TEST(PaymentRequestTest, EmptyResponseDictionary) { base::DictionaryValue expected_value; - std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue); - details->SetString("cardNumber", ""); - expected_value.Set("details", std::move(details)); + expected_value.SetString("details", ""); expected_value.SetString("paymentRequestID", ""); expected_value.SetString("methodName", ""); @@ -289,7 +288,9 @@ new base::DictionaryValue); billing_address->SetString("postalCode", "90210"); details->Set("billingAddress", std::move(billing_address)); - expected_value.Set("details", std::move(details)); + std::string stringified_details; + base::JSONWriter::Write(*details, &stringified_details); + expected_value.SetString("details", stringified_details); expected_value.SetString("paymentRequestID", "12345"); expected_value.SetString("methodName", "American Express"); std::unique_ptr<base::DictionaryValue> shipping_address( @@ -304,14 +305,23 @@ PaymentResponse payment_response; payment_response.payment_request_id = base::ASCIIToUTF16("12345"); payment_response.method_name = base::ASCIIToUTF16("American Express"); - payment_response.details.card_number = + + payments::BasicCardResponse payment_response_details; + payment_response_details.card_number = base::ASCIIToUTF16("1111-1111-1111-1111"); - payment_response.details.cardholder_name = base::ASCIIToUTF16("Jon Doe"); - payment_response.details.expiry_month = base::ASCIIToUTF16("02"); - payment_response.details.expiry_year = base::ASCIIToUTF16("2090"); - payment_response.details.card_security_code = base::ASCIIToUTF16("111"); - payment_response.details.billing_address.postal_code = + payment_response_details.cardholder_name = base::ASCIIToUTF16("Jon Doe"); + payment_response_details.expiry_month = base::ASCIIToUTF16("02"); + payment_response_details.expiry_year = base::ASCIIToUTF16("2090"); + payment_response_details.card_security_code = base::ASCIIToUTF16("111"); + payment_response_details.billing_address.postal_code = base::ASCIIToUTF16("90210"); + std::unique_ptr<base::DictionaryValue> response_value = + payment_response_details.ToDictionaryValue(); + std::string payment_response_stringified_details; + base::JSONWriter::Write(*response_value, + &payment_response_stringified_details); + payment_response.details = payment_response_stringified_details; + payment_response.shipping_address.postal_code = base::ASCIIToUTF16("94115"); payment_response.shipping_option = base::ASCIIToUTF16("666"); payment_response.payer_name = base::ASCIIToUTF16("Jane Doe"); @@ -630,13 +640,21 @@ payments::BasicCardResponse card_response1; card_response1.card_number = base::ASCIIToUTF16("1234"); + std::unique_ptr<base::DictionaryValue> response_value1 = + card_response1.ToDictionaryValue(); + std::string stringified_card_response1; + base::JSONWriter::Write(*response_value1, &stringified_card_response1); payments::BasicCardResponse card_response2; card_response2.card_number = base::ASCIIToUTF16("8888"); - response1.details = card_response1; + std::unique_ptr<base::DictionaryValue> response_value2 = + card_response2.ToDictionaryValue(); + std::string stringified_card_response2; + base::JSONWriter::Write(*response_value2, &stringified_card_response2); + response1.details = stringified_card_response1; EXPECT_NE(response1, response2); - response2.details = card_response2; + response2.details = stringified_card_response2; EXPECT_NE(response1, response2); - response2.details = card_response1; + response2.details = stringified_card_response1; EXPECT_EQ(response1, response2); }
diff --git a/ios/web/public/payments/payment_request.h b/ios/web/public/payments/payment_request.h index 4452690..76e80fe2 100644 --- a/ios/web/public/payments/payment_request.h +++ b/ios/web/public/payments/payment_request.h
@@ -264,7 +264,7 @@ // A credit card response object used by the merchant to process the // transaction and determine successful fund transfer. - payments::BasicCardResponse details; + std::string details; // If request_shipping was set to true in the PaymentOptions passed to the // PaymentRequest constructor, this will be the full and final shipping
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 87e56e2..a81541eb 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -684,6 +684,14 @@ - (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange sameDocumentNavigation:(BOOL)sameDocumentNavigation; +// WKNavigation objects are used as a weak key to store web::NavigationContext. +// WKWebView manages WKNavigation lifetime and destroys them after the +// navigation is finished. However for window opening navigations WKWebView +// passes null WKNavigation to WKNavigationDelegate callbacks and strong key is +// used to store web::NavigationContext. Those "null" navigations have to be +// cleaned up manually by calling this method. +- (void)forgetNullWKNavigation:(WKNavigation*)navigation; + - (BOOL)isLoaded; // Extracts the current page's viewport tag information and calls |completion|. // If the page has changed before the viewport tag is successfully extracted, @@ -3450,6 +3458,11 @@ return currentItem ? currentItem->GetHttpRequestHeaders() : nil; } +- (void)forgetNullWKNavigation:(WKNavigation*)navigation { + if (!navigation) + [_navigationStates removeNavigation:navigation]; +} + #pragma mark - #pragma mark CRWWebViewScrollViewProxyObserver @@ -4501,7 +4514,7 @@ // the pending load. _pendingNavigationInfo.reset(); _certVerificationErrors->Clear(); - [_navigationStates removeNavigation:navigation]; + [self forgetNullWKNavigation:navigation]; } - (void)webView:(WKWebView*)webView @@ -4605,9 +4618,9 @@ if (navigationFinished) { // webView:didFinishNavigation: was called before - // webView:didCommitNavigation:, so remove the navigation now and signal + // webView:didCommitNavigation:, so forget null navigation now and signal // that navigation was finished. - [_navigationStates removeNavigation:navigation]; + [self forgetNullWKNavigation:navigation]; [self didFinishNavigation:navigation]; } } @@ -4628,10 +4641,10 @@ web::ExecuteJavaScript(webView, @"__gCrWeb.didFinishNavigation()", nil); [self didFinishNavigation:navigation]; - // Remove navigation only if it has been committed. Otherwise it will be - // removed in webView:didCommitNavigation: callback. + // Forget null navigation only if it has been committed. Otherwise it will be + // forgotten in webView:didCommitNavigation: callback. if (navigationCommitted) { - [_navigationStates removeNavigation:navigation]; + [self forgetNullWKNavigation:navigation]; } } @@ -4645,7 +4658,7 @@ inMainFrame:YES forNavigation:navigation]; _certVerificationErrors->Clear(); - [_navigationStates removeNavigation:navigation]; + [self forgetNullWKNavigation:navigation]; } - (void)webView:(WKWebView*)webView
diff --git a/ios/web/web_state/ui/crw_wk_navigation_states.h b/ios/web/web_state/ui/crw_wk_navigation_states.h index 35731ec..f544c7fc 100644 --- a/ios/web/web_state/ui/crw_wk_navigation_states.h +++ b/ios/web/web_state/ui/crw_wk_navigation_states.h
@@ -60,7 +60,11 @@ - (web::WKNavigationState)stateForNavigation:(WKNavigation*)navigation; // Removes given |navigation|. Fails if |navigation| does not exist. -// |navigation| can be null. +// |navigation| can be null. Cliens don't have to call this method for non-null +// navigations because non-null navigations are weak and will be automatically +// removed when system releases finished navigaitons. This method must always be +// called for completed null navigations because they are not removed +// automatically. - (void)removeNavigation:(WKNavigation*)navigation; // Adds a new navigation if it was not added yet. If navigation was already
diff --git a/ios/web_view/internal/app/application_context.cc b/ios/web_view/internal/app/application_context.cc index bc3b2033..9e0e539e 100644 --- a/ios/web_view/internal/app/application_context.cc +++ b/ios/web_view/internal/app/application_context.cc
@@ -32,11 +32,7 @@ : local_state_task_runner_(JsonPrefStore::GetTaskRunnerForFile( GetLocalStatePath(), web::WebThread::GetBlockingPool())) { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - - net_log_ = base::MakeUnique<net_log::ChromeNetLog>( - base::FilePath(), net::NetLogCaptureMode::Default(), - command_line->GetCommandLineString(), std::string()); + net_log_ = base::MakeUnique<net_log::ChromeNetLog>(); SetApplicationLocale(l10n_util::GetLocaleOverride()); }
diff --git a/ios/web_view/internal/translate/cwv_translation_controller.mm b/ios/web_view/internal/translate/cwv_translation_controller.mm index ac61509..c62a868 100644 --- a/ios/web_view/internal/translate/cwv_translation_controller.mm +++ b/ios/web_view/internal/translate/cwv_translation_controller.mm
@@ -134,6 +134,10 @@ #pragma mark - Public Methods +- (NSSet*)supportedLanguages { + return [NSSet setWithArray:self.supportedLanguagesByCode.allValues]; +} + - (void)translatePageFromLanguage:(CWVTranslationLanguage*)sourceLanguage toLanguage:(CWVTranslationLanguage*)targetLanguage userInitiated:(BOOL)userInitiated { @@ -225,15 +229,6 @@ #pragma mark - Private Methods -- (NSArray*)supportedLanguages { - return [self.supportedLanguagesByCode.allValues - sortedArrayUsingComparator:^NSComparisonResult( - CWVTranslationLanguage* languageA, - CWVTranslationLanguage* languageB) { - return [languageA.languageName compare:languageB.languageName]; - }]; -} - - (NSDictionary<NSString*, CWVTranslationLanguage*>*)supportedLanguagesByCode { if (!_supportedLanguagesByCode) { NSMutableDictionary<NSString*, CWVTranslationLanguage*>* @@ -243,11 +238,14 @@ std::string locale = translate::TranslateDownloadManager::GetInstance() ->application_locale(); for (const std::string& languageCode : languageCodes) { - base::string16 languageName = + base::string16 localizedName = l10n_util::GetDisplayNameForLocale(languageCode, locale, true); + base::string16 nativeName = + l10n_util::GetDisplayNameForLocale(languageCode, languageCode, true); CWVTranslationLanguage* language = [[CWVTranslationLanguage alloc] initWithLanguageCode:languageCode - languageName:languageName]; + localizedName:localizedName + nativeName:nativeName]; supportedLanguagesByCode[language.languageCode] = language; }
diff --git a/ios/web_view/internal/translate/cwv_translation_language.mm b/ios/web_view/internal/translate/cwv_translation_language.mm index 2118ac6..13062c70 100644 --- a/ios/web_view/internal/translate/cwv_translation_language.mm +++ b/ios/web_view/internal/translate/cwv_translation_language.mm
@@ -14,21 +14,25 @@ @implementation CWVTranslationLanguage @synthesize languageCode = _languageCode; -@synthesize languageName = _languageName; +@synthesize localizedName = _localizedName; +@synthesize nativeName = _nativeName; - (instancetype)initWithLanguageCode:(const std::string&)languageCode - languageName:(const base::string16&)languageName { + localizedName:(const base::string16&)localizedName + nativeName:(const base::string16&)nativeName { self = [super init]; if (self) { _languageCode = base::SysUTF8ToNSString(languageCode); - _languageName = base::SysUTF16ToNSString(languageName); + _localizedName = base::SysUTF16ToNSString(localizedName); + _nativeName = base::SysUTF16ToNSString(nativeName); } return self; } - (NSString*)description { - return [NSString stringWithFormat:@"%@ name:%@ code:%@", [super description], - _languageName, _languageCode]; + return + [NSString stringWithFormat:@"%@ name:%@(%@) code:%@", [super description], + _localizedName, _nativeName, _languageCode]; } @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 index f4d8cda..0ae71828 100644 --- a/ios/web_view/internal/translate/cwv_translation_language_internal.h +++ b/ios/web_view/internal/translate/cwv_translation_language_internal.h
@@ -16,7 +16,8 @@ @interface CWVTranslationLanguage () - (instancetype)initWithLanguageCode:(const std::string&)languageCode - languageName:(const base::string16&)languageName + localizedName:(const base::string16&)localizedName + nativeName:(const base::string16&)nativeName NS_DESIGNATED_INITIALIZER; @end
diff --git a/ios/web_view/public/cwv_translation_controller.h b/ios/web_view/public/cwv_translation_controller.h index 51e33a2..ee31066 100644 --- a/ios/web_view/public/cwv_translation_controller.h +++ b/ios/web_view/public/cwv_translation_controller.h
@@ -48,9 +48,9 @@ @property(nullable, nonatomic, weak) id<CWVTranslationControllerDelegate> delegate; -// A sorted list of supported languages for translation. +// The set of supported languages for translation. @property(nonatomic, readonly) - NSArray<CWVTranslationLanguage*>* supportedLanguages; + NSSet<CWVTranslationLanguage*>* supportedLanguages; // Begins translation on the current page from |sourceLanguage| to // |targetLanguage|. These language parameters must be chosen from
diff --git a/ios/web_view/public/cwv_translation_language.h b/ios/web_view/public/cwv_translation_language.h index 58808ae1..2879b05 100644 --- a/ios/web_view/public/cwv_translation_language.h +++ b/ios/web_view/public/cwv_translation_language.h
@@ -21,8 +21,11 @@ // https://cloud.google.com/translate/docs/languages @property(nonatomic, copy, readonly) NSString* languageCode; -// The localized language name. -@property(nonatomic, copy, readonly) NSString* languageName; +// The language name in the current user locale. Ex: "German". +@property(nonatomic, copy, readonly) NSString* localizedName; + +// The language name in the native language. Ex: "Deutsch". +@property(nonatomic, copy, readonly) NSString* nativeName; @end
diff --git a/ipc/OWNERS b/ipc/OWNERS index b8baa34..0617e7bf 100644 --- a/ipc/OWNERS +++ b/ipc/OWNERS
@@ -8,6 +8,8 @@ # new sandbox escapes. per-file ipc_message_start.h=set noparent per-file ipc_message_start.h=file://ipc/SECURITY_OWNERS +per-file *_messages*.h=set noparent +per-file *_messages*.h=file://ipc/SECURITY_OWNERS per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS per-file *_param_traits*.*=set noparent
diff --git a/ipc/README.md b/ipc/README.md index 2b1f9f2..be5624d 100644 --- a/ipc/README.md +++ b/ipc/README.md
@@ -604,7 +604,7 @@ to define the mapping: ``` -mojom = "//content/common/url_loader.mojom" +mojom = "//content/public/common/url_loader.mojom" public_headers = [ "//content/common/resource_request.h" ] traits_headers = [ "//content/common/resource_messages.h" ] ...
diff --git a/ipc/ipc_channel_proxy_unittest.cc b/ipc/ipc_channel_proxy_unittest.cc index f059099..01b8955 100644 --- a/ipc/ipc_channel_proxy_unittest.cc +++ b/ipc/ipc_channel_proxy_unittest.cc
@@ -90,7 +90,7 @@ IPC_BEGIN_MESSAGE_MAP(ChannelReflectorListener, message) IPC_MESSAGE_HANDLER(TestMsg_Bounce, OnTestBounce) IPC_MESSAGE_HANDLER(TestMsg_SendBadMessage, OnSendBadMessage) - IPC_MESSAGE_HANDLER(UtilityMsg_Bounce, OnUtilityBounce) + IPC_MESSAGE_HANDLER(AutomationMsg_Bounce, OnAutomationBounce) IPC_MESSAGE_HANDLER(WorkerMsg_Bounce, OnBounce) IPC_MESSAGE_HANDLER(WorkerMsg_Quit, OnQuit) IPC_END_MESSAGE_MAP() @@ -105,9 +105,7 @@ channel_->Send(new TestMsg_BadMessage(BadType())); } - void OnUtilityBounce() { - channel_->Send(new UtilityMsg_Bounce()); - } + void OnAutomationBounce() { channel_->Send(new AutomationMsg_Bounce()); } void OnBounce() { channel_->Send(new WorkerMsg_Bounce()); @@ -282,17 +280,17 @@ TEST_F(IPCChannelProxyTest, MessageClassFilters) { // Construct a filter per message class. - std::vector<scoped_refptr<MessageCountFilter> > class_filters; - class_filters.push_back(make_scoped_refptr( - new MessageCountFilter(TestMsgStart))); - class_filters.push_back(make_scoped_refptr( - new MessageCountFilter(UtilityMsgStart))); + std::vector<scoped_refptr<MessageCountFilter>> class_filters; + class_filters.push_back( + make_scoped_refptr(new MessageCountFilter(TestMsgStart))); + class_filters.push_back( + make_scoped_refptr(new MessageCountFilter(AutomationMsgStart))); for (size_t i = 0; i < class_filters.size(); ++i) channel_proxy()->AddFilter(class_filters[i].get()); // Send a message for each class; each filter should receive just one message. - sender()->Send(new TestMsg_Bounce()); - sender()->Send(new UtilityMsg_Bounce()); + sender()->Send(new TestMsg_Bounce); + sender()->Send(new AutomationMsg_Bounce); // Send some messages not assigned to a specific or valid message class. sender()->Send(new WorkerMsg_Bounce); @@ -320,7 +318,7 @@ sender()->Send(new TestMsg_Bounce); // A message of a different class should be seen only by the global filter. - sender()->Send(new UtilityMsg_Bounce); + sender()->Send(new AutomationMsg_Bounce); // Flush all messages. SendQuitMessageAndWaitForIdle(); @@ -347,7 +345,7 @@ // Send some messages; they should not be seen by either filter. sender()->Send(new TestMsg_Bounce); - sender()->Send(new UtilityMsg_Bounce); + sender()->Send(new AutomationMsg_Bounce); // Ensure that the filters were removed and did not receive any messages. SendQuitMessageAndWaitForIdle();
diff --git a/ipc/ipc_channel_proxy_unittest_messages.h b/ipc/ipc_channel_proxy_unittest_messages.h index 288ce53..ae45059 100644 --- a/ipc/ipc_channel_proxy_unittest_messages.h +++ b/ipc/ipc_channel_proxy_unittest_messages.h
@@ -30,15 +30,15 @@ #endif // IPC_CHANNEL_PROXY_UNITTEST_MESSAGES_H_ - +#undef IPC_MESSAGE_START #define IPC_MESSAGE_START TestMsgStart IPC_MESSAGE_CONTROL0(TestMsg_Bounce) IPC_MESSAGE_CONTROL0(TestMsg_SendBadMessage) IPC_MESSAGE_CONTROL1(TestMsg_BadMessage, BadType) #undef IPC_MESSAGE_START -#define IPC_MESSAGE_START UtilityMsgStart -IPC_MESSAGE_CONTROL0(UtilityMsg_Bounce) +#define IPC_MESSAGE_START AutomationMsgStart +IPC_MESSAGE_CONTROL0(AutomationMsg_Bounce) #undef IPC_MESSAGE_START #define IPC_MESSAGE_START WorkerMsgStart
diff --git a/ipc/ipc_message_start.h b/ipc/ipc_message_start.h index 7b5935e..dba1acb4 100644 --- a/ipc/ipc_message_start.h +++ b/ipc/ipc_message_start.h
@@ -19,7 +19,6 @@ DevToolsMsgStart, WorkerMsgStart, NaClMsgStart, - UtilityMsgStart, GpuChannelMsgStart, MediaMsgStart, ServiceMsgStart,
diff --git a/ipc/ipc_sync_channel_unittest.cc b/ipc/ipc_sync_channel_unittest.cc index 63d5e46..5d6588fcee 100644 --- a/ipc/ipc_sync_channel_unittest.cc +++ b/ipc/ipc_sync_channel_unittest.cc
@@ -81,8 +81,6 @@ // Shutdown() must be called before destruction. CHECK(is_shutdown_); } - void AddRef() { } - void Release() { } bool Send(Message* msg) override { return channel_->Send(msg); } void WaitForChannelCreation() { channel_created_->Wait(); } void CloseChannel() { @@ -92,7 +90,7 @@ void Start() { StartThread(&listener_thread_, base::MessageLoop::TYPE_DEFAULT); ListenerThread()->task_runner()->PostTask( - FROM_HERE, base::Bind(&Worker::OnStart, this)); + FROM_HERE, base::Bind(&Worker::OnStart, base::Unretained(this))); } void Shutdown() { // The IPC thread needs to outlive SyncChannel. We can't do this in @@ -104,8 +102,9 @@ ipc_done(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); ListenerThread()->task_runner()->PostTask( - FROM_HERE, base::Bind(&Worker::OnListenerThreadShutdown1, this, - &listener_done, &ipc_done)); + FROM_HERE, + base::Bind(&Worker::OnListenerThreadShutdown1, base::Unretained(this), + &listener_done, &ipc_done)); listener_done.Wait(); ipc_done.Wait(); ipc_thread_.Stop(); @@ -207,8 +206,9 @@ base::RunLoop().RunUntilIdle(); ipc_thread_.task_runner()->PostTask( - FROM_HERE, base::Bind(&Worker::OnIPCThreadShutdown, this, - listener_event, ipc_event)); + FROM_HERE, + base::Bind(&Worker::OnIPCThreadShutdown, base::Unretained(this), + listener_event, ipc_event)); } void OnIPCThreadShutdown(WaitableEvent* listener_event, @@ -217,8 +217,8 @@ ipc_event->Signal(); listener_thread_.task_runner()->PostTask( - FROM_HERE, - base::Bind(&Worker::OnListenerThreadShutdown2, this, listener_event)); + FROM_HERE, base::Bind(&Worker::OnListenerThreadShutdown2, + base::Unretained(this), listener_event)); } void OnListenerThreadShutdown2(WaitableEvent* listener_event) { @@ -1018,7 +1018,7 @@ void Run() override { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(&NestedCallback, this)); + FROM_HERE, base::Bind(&NestedCallback, base::Unretained(this))); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&TimeoutCallback), base::TimeDelta::FromSeconds(9)); @@ -1117,8 +1117,9 @@ bool SendDummy() { ListenerThread()->task_runner()->PostTask( - FROM_HERE, base::Bind(base::IgnoreResult(&ServerSendAfterClose::Send), - this, new SyncChannelTestMsg_NoArgs)); + FROM_HERE, + base::Bind(base::IgnoreResult(&ServerSendAfterClose::Send), + base::Unretained(this), new SyncChannelTestMsg_NoArgs)); return true; } @@ -1186,7 +1187,8 @@ // Signal the event after the message has been sent on the channel, on the // IPC thread. ipc_thread().task_runner()->PostTask( - FROM_HERE, base::Bind(&RestrictedDispatchServer::OnPingSent, this)); + FROM_HERE, base::Bind(&RestrictedDispatchServer::OnPingSent, + base::Unretained(this))); } void OnPingTTL(int ping, int* out) { @@ -1267,7 +1269,8 @@ channel()->SetRestrictDispatchChannelGroup(1); server_->ListenerThread()->task_runner()->PostTask( - FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 1)); + FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, + base::Unretained(server_), 1)); sent_ping_event_->Wait(); Send(new SyncChannelTestMsg_NoArgs); if (ping_ == 1) @@ -1280,7 +1283,8 @@ this, ipc_thread().task_runner(), true, shutdown_event()); server_->ListenerThread()->task_runner()->PostTask( - FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, server_, 2)); + FROM_HERE, base::Bind(&RestrictedDispatchServer::OnDoPing, + base::Unretained(server_), 2)); sent_ping_event_->Wait(); // Check that the incoming message is *not* dispatched when sending on the // non restricted channel. @@ -1305,8 +1309,8 @@ // Check that the incoming message on the non-restricted channel is // dispatched when sending on the restricted channel. server2_->ListenerThread()->task_runner()->PostTask( - FROM_HERE, - base::Bind(&NonRestrictedDispatchServer::OnDoPingTTL, server2_, 3)); + FROM_HERE, base::Bind(&NonRestrictedDispatchServer::OnDoPingTTL, + base::Unretained(server2_), 3)); int value = 0; Send(new SyncChannelTestMsg_PingTTL(4, &value)); if (ping_ == 3 && value == 4) @@ -1539,11 +1543,12 @@ void Run() override { server_ready_event_->Wait(); server_->ListenerThread()->task_runner()->PostTask( - FROM_HERE, - base::Bind(&RestrictedDispatchDeadlockServer::OnDoServerTask, server_)); + FROM_HERE, base::Bind(&RestrictedDispatchDeadlockServer::OnDoServerTask, + base::Unretained(server_))); peer_->ListenerThread()->task_runner()->PostTask( FROM_HERE, - base::Bind(&RestrictedDispatchDeadlockClient2::OnDoClient2Task, peer_)); + base::Bind(&RestrictedDispatchDeadlockClient2::OnDoClient2Task, + base::Unretained(peer_))); events_[0]->Wait(); events_[1]->Wait(); DCHECK(received_msg_ == false);
diff --git a/mash/catalog_viewer/catalog_viewer.cc b/mash/catalog_viewer/catalog_viewer.cc index c3ca399..ccaca82 100644 --- a/mash/catalog_viewer/catalog_viewer.cc +++ b/mash/catalog_viewer/catalog_viewer.cc
@@ -222,9 +222,11 @@ } void CatalogViewer::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) + context()->QuitNow(); } void CatalogViewer::OnBindInterface(
diff --git a/mash/example/views_examples/views_examples.cc b/mash/example/views_examples/views_examples.cc index e559bf9..da9a8a50 100644 --- a/mash/example/views_examples/views_examples.cc +++ b/mash/example/views_examples/views_examples.cc
@@ -31,10 +31,12 @@ private: // service_manager::Service: void OnStart() override { - aura_init_ = base::MakeUnique<views::AuraInit>( - context()->connector(), context()->identity(), - "views_mus_resources.pak", std::string(), nullptr, - views::AuraInit::Mode::AURA_MUS); + aura_init_ = + views::AuraInit::Create(context()->connector(), context()->identity(), + "views_mus_resources.pak", std::string(), + nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) + context()->QuitNow(); } void OnBindInterface(const service_manager::BindSourceInfo& source_info, const std::string& interface_name,
diff --git a/mash/example/window_type_launcher/window_type_launcher.cc b/mash/example/window_type_launcher/window_type_launcher.cc index 021135e4..078005b9 100644 --- a/mash/example/window_type_launcher/window_type_launcher.cc +++ b/mash/example/window_type_launcher/window_type_launcher.cc
@@ -453,9 +453,11 @@ } void WindowTypeLauncher::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) + context()->QuitNow(); } void WindowTypeLauncher::OnBindInterface(
diff --git a/mash/quick_launch/quick_launch.cc b/mash/quick_launch/quick_launch.cc index a9f51a0f..1a5dafa 100644 --- a/mash/quick_launch/quick_launch.cc +++ b/mash/quick_launch/quick_launch.cc
@@ -171,14 +171,13 @@ } void QuickLaunch::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( - context()->connector(), context()->identity(), "views_mus_resources.pak", - std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); - // If AuraInit was unable to initialize there is no longer a peer connection. // The ServiceManager is in the process of shutting down, however we haven't // been notified yet. Close our ServiceContext and shutdown. - if (!aura_init_->initialized()) { + aura_init_ = views::AuraInit::Create( + context()->connector(), context()->identity(), "views_mus_resources.pak", + std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) { context()->QuitNow(); return; }
diff --git a/mash/simple_wm/simple_wm.cc b/mash/simple_wm/simple_wm.cc index 8850a38..26ba8465 100644 --- a/mash/simple_wm/simple_wm.cc +++ b/mash/simple_wm/simple_wm.cc
@@ -364,9 +364,13 @@ started_ = true; screen_ = base::MakeUnique<display::ScreenBase>(); display::Screen::SetScreenInstance(screen_.get()); - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS_WINDOW_MANAGER); + if (!aura_init_) { + context()->QuitNow(); + return; + } window_tree_client_ = base::MakeUnique<aura::WindowTreeClient>( context()->connector(), this, this); aura::Env::GetInstance()->SetWindowTreeClient(window_tree_client_.get());
diff --git a/mash/task_viewer/task_viewer.cc b/mash/task_viewer/task_viewer.cc index cdc03e76..d932576 100644 --- a/mash/task_viewer/task_viewer.cc +++ b/mash/task_viewer/task_viewer.cc
@@ -294,9 +294,11 @@ } void TaskViewer::OnStart() { - aura_init_ = base::MakeUnique<views::AuraInit>( + aura_init_ = views::AuraInit::Create( context()->connector(), context()->identity(), "views_mus_resources.pak", std::string(), nullptr, views::AuraInit::Mode::AURA_MUS); + if (!aura_init_) + context()->QuitNow(); } void TaskViewer::OnBindInterface(
diff --git a/media/BUILD.gn b/media/BUILD.gn index bd12c8a..5436d6f3 100644 --- a/media/BUILD.gn +++ b/media/BUILD.gn
@@ -594,13 +594,6 @@ "base/vector_math.h", "base/vector_math_testing.h", ] - if (is_mac) { - # These need to be included here because audio_latency.cc depends on them. - sources += [ - "base/mac/audio_latency_mac.cc", - "base/mac/audio_latency_mac.h", - ] - } configs += [ ":media_config", ":media_implementation",
diff --git a/media/audio/audio_input_controller.cc b/media/audio/audio_input_controller.cc index c048bf3..5ba8ebf 100644 --- a/media/audio/audio_input_controller.cc +++ b/media/audio/audio_input_controller.cc
@@ -397,7 +397,7 @@ if (!stream_) return; - check_muted_state_timer_.Stop(); + check_muted_state_timer_.AbandonAndStop(); std::string log_string; static const char kLogStringPrefix[] = "AIC::DoClose:";
diff --git a/media/audio/audio_manager_unittest.cc b/media/audio/audio_manager_unittest.cc index db92da8..904ee12 100644 --- a/media/audio/audio_manager_unittest.cc +++ b/media/audio/audio_manager_unittest.cc
@@ -26,7 +26,6 @@ #include "media/audio/fake_audio_log_factory.h" #include "media/audio/fake_audio_manager.h" #include "media/audio/test_audio_thread.h" -#include "media/base/limits.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -34,11 +33,6 @@ #include "media/audio/alsa/audio_manager_alsa.h" #endif // defined(USE_ALSA) -#if defined(OS_MACOSX) -#include "media/audio/mac/audio_manager_mac.h" -#include "media/base/mac/audio_latency_mac.h" -#endif - #if defined(OS_WIN) #include "base/win/scoped_com_initializer.h" #include "media/audio/win/audio_manager_win.h" @@ -683,102 +677,4 @@ audio_manager_->DisableOutputDebugRecording(); } -#if defined(OS_MACOSX) || defined(USE_CRAS) || defined(USE_PULSEAUDIO) -class TestAudioSourceCallback : public AudioOutputStream::AudioSourceCallback { - public: - TestAudioSourceCallback(int expected_frames_per_buffer, - base::WaitableEvent* event) - : expected_frames_per_buffer_(expected_frames_per_buffer), - event_(event){}; - ~TestAudioSourceCallback() override{}; - - int OnMoreData(base::TimeDelta, - base::TimeTicks, - int, - AudioBus* dest) override { - EXPECT_EQ(dest->frames(), expected_frames_per_buffer_); - event_->Signal(); - return 0; - } - - void OnError() override { FAIL(); } - - private: - DISALLOW_COPY_AND_ASSIGN(TestAudioSourceCallback); - - const int expected_frames_per_buffer_; - base::WaitableEvent* event_; -}; - -// Test that we can create an AudioOutputStream with kMinAudioBufferSize and -// kMaxAudioBufferSize and that the callback AudioBus is the expected size. -TEST_F(AudioManagerTest, CheckMinimumAudioBufferSizesCallbacks) { - ABORT_AUDIO_TEST_IF_NOT(OutputDevicesAvailable()); - -#if defined(OS_MACOSX) - CreateAudioManagerForTesting<AudioManagerMac>(); -#elif defined(USE_CRAS) - CreateAudioManagerForTesting<AudioManagerCras>(); -#elif defined(USE_PULSEAUDIO) - CreateAudioManagerForTesting<AudioManagerPulse>(); -#endif - - DCHECK(audio_manager_); - - AudioParameters default_params; - GetDefaultOutputStreamParameters(&default_params); - ASSERT_LT(default_params.frames_per_buffer(), - media::limits::kMaxAudioBufferSize); - -#if defined(OS_MACOSX) - // On OSX the preferred output buffer size is higher than the minimum - // but users may request the minimum size explicitly. - ASSERT_GT(default_params.frames_per_buffer(), - GetMinAudioBufferSizeMacOS(media::limits::kMinAudioBufferSize, - default_params.sample_rate())); -#elif defined(USE_CRAS) - // On CRAS the preferred output buffer size varies per board and may be as low - // as the minimum for some boards. - ASSERT_GE(default_params.frames_per_buffer(), - media::limits::kMinAudioBufferSize); -#elif defined(USE_PULSEAUDIO) - ASSERT_EQ(default_params.frames_per_buffer(), - media::limits::kMinAudioBufferSize); -#else - NOTREACHED(); -#endif - - AudioOutputStream* stream; - base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED); - - // Create an output stream with the minimum buffer size parameters and ensure - // that no errors are returned. - AudioParameters min_params = default_params; - min_params.set_frames_per_buffer(media::limits::kMinAudioBufferSize); - stream = audio_manager_->MakeAudioOutputStreamProxy(min_params, ""); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - event.Reset(); - TestAudioSourceCallback min_source(min_params.frames_per_buffer(), &event); - stream->Start(&min_source); - event.Wait(); - stream->Stop(); - stream->Close(); - - // Verify the same for the maximum buffer size. - AudioParameters max_params = default_params; - max_params.set_frames_per_buffer(media::limits::kMaxAudioBufferSize); - stream = audio_manager_->MakeAudioOutputStreamProxy(max_params, ""); - ASSERT_TRUE(stream); - EXPECT_TRUE(stream->Open()); - event.Reset(); - TestAudioSourceCallback max_source(max_params.frames_per_buffer(), &event); - stream->Start(&max_source); - event.Wait(); - stream->Stop(); - stream->Close(); -} -#endif - } // namespace media
diff --git a/media/audio/cras/audio_manager_cras.cc b/media/audio/cras/audio_manager_cras.cc index f3beab2..2e6d346 100644 --- a/media/audio/cras/audio_manager_cras.cc +++ b/media/audio/cras/audio_manager_cras.cc
@@ -24,7 +24,6 @@ #include "media/audio/cras/cras_input.h" #include "media/audio/cras/cras_unified.h" #include "media/base/channel_layout.h" -#include "media/base/limits.h" #include "media/base/localized_strings.h" // cras_util.h headers pull in min/max macros... @@ -41,6 +40,10 @@ // Default sample rate for input and output streams. const int kDefaultSampleRate = 48000; +// Define bounds for the output buffer size. +const int kMinimumOutputBufferSize = 512; +const int kMaximumOutputBufferSize = 8192; + // Default input buffer size. const int kDefaultInputBufferSize = 1024; @@ -305,7 +308,7 @@ return 768; else if (board == "samus") return 256; - return 512; + return kMinimumOutputBufferSize; } AudioParameters AudioManagerCras::GetPreferredOutputStreamParameters( @@ -320,9 +323,8 @@ bits_per_sample = input_params.bits_per_sample(); channel_layout = input_params.channel_layout(); buffer_size = - std::min(static_cast<int>(limits::kMaxAudioBufferSize), - std::max(static_cast<int>(limits::kMinAudioBufferSize), - input_params.frames_per_buffer())); + std::min(kMaximumOutputBufferSize, + std::max(buffer_size, input_params.frames_per_buffer())); } int user_buffer_size = GetUserBufferSize();
diff --git a/media/audio/mac/audio_manager_mac.cc b/media/audio/mac/audio_manager_mac.cc index 8478e0f..09b6433 100644 --- a/media/audio/mac/audio_manager_mac.cc +++ b/media/audio/mac/audio_manager_mac.cc
@@ -27,7 +27,6 @@ #include "media/base/bind_to_current_loop.h" #include "media/base/channel_layout.h" #include "media/base/limits.h" -#include "media/base/mac/audio_latency_mac.h" #include "media/base/media_switches.h" namespace media { @@ -35,6 +34,10 @@ // Maximum number of output streams that can be open simultaneously. static const int kMaxOutputStreams = 50; +// Define bounds for for low-latency input and output streams. +static const int kMinimumInputOutputBufferSize = 128; +static const int kMaximumInputOutputBufferSize = 4096; + // Default sample-rate on most Apple hardware. static const int kFallbackSampleRate = 44100; @@ -833,17 +836,11 @@ // Allow pass through buffer sizes. If concurrent input and output streams // exist, they will use the smallest buffer size amongst them. As such, each // stream must be able to FIFO requests appropriately when this happens. - int buffer_size; + int buffer_size = ChooseBufferSize(false, hardware_sample_rate); if (has_valid_input_params) { - // If passed in via the input_params we allow buffer sizes to go as - // low as the the kMinAudioBufferSize, ignoring what - // ChooseBufferSize() normally returns. buffer_size = - std::min(static_cast<int>(limits::kMaxAudioBufferSize), - std::max(input_params.frames_per_buffer(), - static_cast<int>(limits::kMinAudioBufferSize))); - } else { - buffer_size = ChooseBufferSize(false, hardware_sample_rate); + std::min(kMaximumInputOutputBufferSize, + std::max(input_params.frames_per_buffer(), buffer_size)); } int hardware_channels; @@ -890,7 +887,7 @@ } int AudioManagerMac::ChooseBufferSize(bool is_input, int sample_rate) { - // kMinAudioBufferSize is too small for the output side because + // kMinimumInputOutputBufferSize is too small for the output side because // CoreAudio can get into under-run if the renderer fails delivering data // to the browser within the allowed time by the OS. The workaround is to // use 256 samples as the default output buffer size for sample rates @@ -898,12 +895,20 @@ // TODO(xians): Remove this workaround after WebAudio supports user defined // buffer size. See https://github.com/WebAudio/web-audio-api/issues/348 // for details. - int buffer_size = - is_input ? limits::kMinAudioBufferSize : 2 * limits::kMinAudioBufferSize; + int buffer_size = is_input ? + kMinimumInputOutputBufferSize : 2 * kMinimumInputOutputBufferSize; const int user_buffer_size = GetUserBufferSize(); - buffer_size = user_buffer_size - ? user_buffer_size - : GetMinAudioBufferSizeMacOS(buffer_size, sample_rate); + if (user_buffer_size) { + buffer_size = user_buffer_size; + } else if (sample_rate > 48000) { + // The default buffer size is too small for higher sample rates and may lead + // to glitching. Adjust upwards by multiples of the default size. + if (sample_rate <= 96000) + buffer_size = 2 * kMinimumInputOutputBufferSize; + else if (sample_rate <= 192000) + buffer_size = 4 * kMinimumInputOutputBufferSize; + } + return buffer_size; }
diff --git a/media/audio/pulse/audio_manager_pulse.cc b/media/audio/pulse/audio_manager_pulse.cc index e1ea89a..6fa330f0 100644 --- a/media/audio/pulse/audio_manager_pulse.cc +++ b/media/audio/pulse/audio_manager_pulse.cc
@@ -18,7 +18,6 @@ #include "media/audio/pulse/pulse_util.h" #include "media/base/audio_parameters.h" #include "media/base/channel_layout.h" -#include "media/base/limits.h" namespace media { @@ -28,6 +27,10 @@ // Maximum number of output streams that can be open simultaneously. static const int kMaxOutputStreams = 50; +// Define bounds for the output buffer size. +static const int kMinimumOutputBufferSize = 512; +static const int kMaximumOutputBufferSize = 8192; + // Default input buffer size. static const int kDefaultInputBufferSize = 1024; @@ -161,7 +164,7 @@ // TODO(tommi): Support |output_device_id|. VLOG_IF(0, !output_device_id.empty()) << "Not implemented!"; - int buffer_size = limits::kMinAudioBufferSize; + int buffer_size = kMinimumOutputBufferSize; int bits_per_sample = 16; // Query native parameters where applicable; Pulse does not require these to @@ -174,7 +177,7 @@ bits_per_sample = input_params.bits_per_sample(); channel_layout = input_params.channel_layout(); buffer_size = - std::min(static_cast<int>(limits::kMaxAudioBufferSize), + std::min(kMaximumOutputBufferSize, std::max(buffer_size, input_params.frames_per_buffer())); }
diff --git a/media/base/audio_latency.cc b/media/base/audio_latency.cc index d0988faa..61b3724 100644 --- a/media/base/audio_latency.cc +++ b/media/base/audio_latency.cc
@@ -11,11 +11,6 @@ #include "base/logging.h" #include "base/time/time.h" #include "build/build_config.h" -#include "media/base/limits.h" - -#if defined(OS_MACOSX) -#include "media/base/mac/audio_latency_mac.h" -#endif namespace media { @@ -135,32 +130,16 @@ int AudioLatency::GetExactBufferSize(base::TimeDelta duration, int sample_rate, int hardware_buffer_size) { - DCHECK_NE(0, hardware_buffer_size); - -// Other platforms do not currently support custom buffer sizes. -#if !defined(OS_MACOSX) && !defined(USE_CRAS) && !defined(USE_PULSE) - return hardware_buffer_size; -#else const double requested_buffer_size = duration.InSecondsF() * sample_rate; - int minimum_buffer_size = hardware_buffer_size; -// On OSX and CRAS the preferred buffer size is larger than the minimum, -// however we allow values down to the minimum if requested explicitly. -#if defined(OS_MACOSX) - minimum_buffer_size = - GetMinAudioBufferSizeMacOS(limits::kMinAudioBufferSize, sample_rate); -#elif defined(USE_CRAS) - minimum_buffer_size = limits::kMinAudioBufferSize; -#endif + DCHECK_NE(0, hardware_buffer_size); // Round the requested size to the nearest multiple of the hardware size const int buffer_size = std::round(std::max(requested_buffer_size, 1.0) / hardware_buffer_size) * hardware_buffer_size; - return std::min(static_cast<int>(limits::kMaxAudioBufferSize), - std::max(buffer_size, minimum_buffer_size)); -#endif + return std::max(buffer_size, hardware_buffer_size); } } // namespace media
diff --git a/media/base/limits.h b/media/base/limits.h index 0853b58a..f936c8b 100644 --- a/media/base/limits.h +++ b/media/base/limits.h
@@ -7,8 +7,6 @@ #ifndef MEDIA_BASE_LIMITS_H_ #define MEDIA_BASE_LIMITS_H_ -#include "build/build_config.h" - namespace media { namespace limits { @@ -60,20 +58,6 @@ kMaxInitDataLength = 64 * 1024, // 64 KB kMaxSessionResponseLength = 64 * 1024, // 64 KB kMaxKeySystemLength = 256, - -// Minimum and maximum buffer sizes for certain audio platforms. -#if defined(OS_MACOSX) - kMinAudioBufferSize = 128, - kMaxAudioBufferSize = 4096, -#elif defined(USE_PULSEAUDIO) - kMinAudioBufferSize = 512, - kMaxAudioBufferSize = 8192, -#elif defined(USE_CRAS) - // Though CRAS has different per-board defaults, allow explicitly requesting - // this buffer size on any board. - kMinAudioBufferSize = 256, - kMaxAudioBufferSize = 8192, -#endif }; } // namespace limits
diff --git a/media/base/mac/audio_latency_mac.cc b/media/base/mac/audio_latency_mac.cc deleted file mode 100644 index 223e3ad..0000000 --- a/media/base/mac/audio_latency_mac.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/base/mac/audio_latency_mac.h" -#include "media/base/limits.h" - -namespace media { - -int GetMinAudioBufferSizeMacOS(int min_buffer_size, int sample_rate) { - int buffer_size = min_buffer_size; - if (sample_rate > 48000) { - // The default buffer size is too small for higher sample rates and may lead - // to glitching. Adjust upwards by multiples of the default size. - if (sample_rate <= 96000) - buffer_size = 2 * limits::kMinAudioBufferSize; - else if (sample_rate <= 192000) - buffer_size = 4 * limits::kMinAudioBufferSize; - } - return buffer_size; -} - -} // namespace media
diff --git a/media/base/mac/audio_latency_mac.h b/media/base/mac/audio_latency_mac.h deleted file mode 100644 index e6ad4ef7..0000000 --- a/media/base/mac/audio_latency_mac.h +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_BASE_MAC_AUDIO_LATENCY_MAC_H_ -#define MEDIA_BASE_MAC_AUDIO_LATENCY_MAC_H_ - -#include "base/macros.h" -#include "media/base/media_export.h" - -namespace media { - -MEDIA_EXPORT int GetMinAudioBufferSizeMacOS(int min_buffer_size, - int sample_rate); - -} // namespace media - -#endif // MEDIA_BASE_MAC_AUDIO_LATENCY_MAC_H_
diff --git a/media/capture/video_capturer_source.cc b/media/capture/video_capturer_source.cc index 7ff9915..bafdf42 100644 --- a/media/capture/video_capturer_source.cc +++ b/media/capture/video_capturer_source.cc
@@ -13,12 +13,4 @@ // to generate symbols across linking units. VideoCapturerSource::~VideoCapturerSource() {} -void VideoCapturerSource::GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback) { - callback.Run(GetPreferredFormats()); -} - } // namespace media
diff --git a/media/capture/video_capturer_source.h b/media/capture/video_capturer_source.h index 2cb9c02c..c4cc854 100644 --- a/media/capture/video_capturer_source.h +++ b/media/capture/video_capturer_source.h
@@ -50,18 +50,6 @@ using RunningCallback = base::Callback<void(bool)>; - // Collects the formats that can currently be used. - // |max_requested_height|, |max_requested_width|, and - // |max_requested_frame_rate| is used by Tab and Screen capture to decide what - // resolution/framerate to generate. |callback| is triggered when the formats - // have been collected. - // TODO(guidou): Remove this method. http://crbug.com/706408 - virtual void GetCurrentSupportedFormats( - int max_requested_width, - int max_requested_height, - double max_requested_frame_rate, - const VideoCaptureDeviceFormatsCB& callback); - // Returns formats that are preferred and can currently be used. May be empty // if no formats are available or known. virtual VideoCaptureFormats GetPreferredFormats() = 0;
diff --git a/media/filters/frame_processor.cc b/media/filters/frame_processor.cc index 6bb03a0..41d79c8 100644 --- a/media/filters/frame_processor.cc +++ b/media/filters/frame_processor.cc
@@ -58,6 +58,10 @@ needs_random_access_point_ = needs_random_access_point; } + DecodeTimestamp last_processed_decode_timestamp() const { + return last_processed_decode_timestamp_; + } + // Gets a pointer to this track's ChunkDemuxerStream. ChunkDemuxerStream* stream() const { return stream_; } @@ -82,11 +86,24 @@ // |processed_frames_| is cleared in both cases. bool FlushProcessedFrames(); + // Signals this track buffer's stream that a coded frame group is starting + // with decode timestamp |start_timestamp|. + void NotifyStartOfCodedFrameGroup(DecodeTimestamp start_time); + private: // The decode timestamp of the last coded frame appended in the current coded // frame group. Initially kNoTimestamp, meaning "unset". DecodeTimestamp last_decode_timestamp_; + // On signalling the stream of a new coded frame group start time, this is + // reset to that start time. Any buffers subsequently enqueued for emission to + // the stream update this. This is managed separately from + // |last_decode_timestamp_| because |last_processed_decode_timestamp_| is not + // reset during Reset(), to especially be able to track the need to signal + // coded frame group start time for muxed post-discontiuity edge cases. See + // also FrameProcessor::ProcessFrame(). + DecodeTimestamp last_processed_decode_timestamp_; + // The coded frame duration of the last coded frame appended in the current // coded frame group. Initially kNoTimestamp, meaning "unset". base::TimeDelta last_frame_duration_; @@ -116,6 +133,7 @@ MseTrackBuffer::MseTrackBuffer(ChunkDemuxerStream* stream) : last_decode_timestamp_(kNoDecodeTimestamp()), + last_processed_decode_timestamp_(DecodeTimestamp()), last_frame_duration_(kNoTimestamp), highest_presentation_timestamp_(kNoTimestamp), needs_random_access_point_(true), @@ -146,6 +164,7 @@ void MseTrackBuffer::EnqueueProcessedFrame( const scoped_refptr<StreamParserBuffer>& frame) { + last_processed_decode_timestamp_ = frame->GetDecodeTimestamp(); processed_frames_.push_back(frame); } @@ -162,6 +181,11 @@ return result; } +void MseTrackBuffer::NotifyStartOfCodedFrameGroup(DecodeTimestamp start_time) { + last_processed_decode_timestamp_ = start_time; + stream_->OnStartOfCodedFrameGroup(start_time); +} + FrameProcessor::FrameProcessor(const UpdateDurationCB& update_duration_cb, MediaLog* media_log) : group_start_timestamp_(kNoTimestamp), @@ -188,7 +212,7 @@ } else if (sequence_mode_) { // We're switching from 'sequence' to 'segments' mode. Be safe and signal a // new coded frame group on the next frame emitted. - coded_frame_group_last_dts_ = kNoDecodeTimestamp(); + pending_notify_all_group_start_ = true; } // Step 8: Update the attribute to new mode. @@ -314,13 +338,13 @@ itr->second->Reset(); } - // Maintain current |coded_frame_group_last_dts_| state for Reset() during + // Maintain current |pending_notify_all_group_start_| state for Reset() during // sequence mode. Reset it here only if in segments mode. In sequence mode, // the current coded frame group may be continued across Reset() operations to // allow the stream to coalesce what might otherwise be gaps in the buffered - // ranges. See also the declaration for |coded_frame_group_last_dts_|. + // ranges. See also the declaration for |pending_notify_all_group_start_|. if (!sequence_mode_) { - coded_frame_group_last_dts_ = kNoDecodeTimestamp(); + pending_notify_all_group_start_ = true; return; } @@ -357,7 +381,7 @@ DVLOG(2) << __func__ << "(" << start_timestamp.InSecondsF() << ")"; for (auto itr = track_buffers_.begin(); itr != track_buffers_.end(); ++itr) { - itr->second->stream()->OnStartOfCodedFrameGroup(start_timestamp); + itr->second->NotifyStartOfCodedFrameGroup(start_timestamp); } } @@ -610,7 +634,7 @@ decode_timestamp - track_last_decode_timestamp; if (track_dts_delta < base::TimeDelta() || track_dts_delta > 2 * track_buffer->last_frame_duration()) { - DCHECK(coded_frame_group_last_dts_ != kNoDecodeTimestamp()); + DCHECK(!pending_notify_all_group_start_); // 6.1. If mode equals "segments": Set group end timestamp to // presentation timestamp. // If mode equals "sequence": Set group start timestamp equal to @@ -619,8 +643,8 @@ group_end_timestamp_ = presentation_timestamp; // This triggers a discontinuity so we need to treat the next frames // appended within the append window as if they were the beginning of - // a new coded frame group. |coded_frame_group_last_dts_| is reset in - // Reset(), below, for "segments" mode. + // a new coded frame group. |pending_notify_all_group_start_| is reset + // in Reset(), below, for "segments" mode. } else { DVLOG(3) << __func__ << " : Sequence mode discontinuity, GETS: " << group_end_timestamp_.InSecondsF(); @@ -711,33 +735,43 @@ // We now have a processed buffer to append to the track buffer's stream. // If it is the first in a new coded frame group (such as following a - // discontinuity), notify all the track buffers' streams that a coded frame - // group is starting. - // If in 'sequence' appendMode, also check to make sure we don't need to - // signal the start of a new coded frame group in the case where - // timestampOffset adjustments by the app may cause this coded frame to be - // in the timeline prior to the last frame processed. - if (coded_frame_group_last_dts_ == kNoDecodeTimestamp() || - (sequence_mode_ && coded_frame_group_last_dts_ > decode_timestamp)) { + // segments append mode discontinuity, or following a switch to segments + // append mode from sequence append mode), notify all the track buffers + // that a coded frame group is starting. + // + // Otherwise, if the buffer's DTS indicates that a new coded frame group + // needs signalling, signal just the buffer's track buffer. This can + // happen in both sequence and segments append modes when the first + // processed track's frame following a discontinuity has a higher DTS than + // this later processed track's first frame following that discontinuity. + if (pending_notify_all_group_start_ || + track_buffer->last_processed_decode_timestamp() > decode_timestamp) { + DCHECK(frame->is_key_frame()); + // First, complete the append to track buffer streams of the previous // coded frame group's frames, if any. if (!FlushProcessedFrames()) return false; - // TODO(wolenetz): This should be changed to a presentation timestamp. See - // http://crbug.com/402502 - NotifyStartOfCodedFrameGroup(decode_timestamp); + if (pending_notify_all_group_start_) { + // TODO(wolenetz): This should be changed to a presentation timestamp. + // See http://crbug.com/402502 + NotifyStartOfCodedFrameGroup(decode_timestamp); + pending_notify_all_group_start_ = false; + } else { + // TODO(wolenetz): This should be changed to a presentation timestamp. + // See http://crbug.com/402502 + track_buffer->NotifyStartOfCodedFrameGroup(decode_timestamp); + } } - coded_frame_group_last_dts_ = decode_timestamp; - DVLOG(3) << __func__ << ": Sending processed frame to stream, " << "PTS=" << presentation_timestamp.InSecondsF() << ", DTS=" << decode_timestamp.InSecondsF(); // Steps 11-16: Note, we optimize by appending groups of contiguous // processed frames for each track buffer at end of ProcessFrames() or prior - // to NotifyStartOfCodedFrameGroup(). + // to signalling coded frame group starts. track_buffer->EnqueueProcessedFrame(frame); // 17. Set last decode timestamp for track buffer to decode timestamp.
diff --git a/media/filters/frame_processor.h b/media/filters/frame_processor.h index cd8d662..2a7d33d 100644 --- a/media/filters/frame_processor.h +++ b/media/filters/frame_processor.h
@@ -145,17 +145,14 @@ // set to false ("segments"). bool sequence_mode_ = false; - // Tracks whether or not the next processed frame is a continuation of a coded - // frame group (see https://w3c.github.io/media-source/#coded-frame-group). - // Resets to kNoDecodeTimestamp() upon detection of 'segments' mode - // discontinuity, parser reset during 'segments' mode, or switching from - // 'sequence' to 'segments' mode. - // Once a processed coded frame is emitted for the current coded frame group, - // tracks the decode timestamp of the last frame emitted. - // Explicit setting of timestampOffset will trigger subsequent notification of - // a new coded frame start to the tracks' streams, even in 'sequence' mode, if - // the resulting frame has a DTS less than this. - DecodeTimestamp coded_frame_group_last_dts_ = kNoDecodeTimestamp(); + // Tracks whether or not we need to notify all track buffers of a new coded + // frame group (see https://w3c.github.io/media-source/#coded-frame-group) + // upon the next successfully processed frame. Set true initially and upon + // detection of 'segments' mode discontinuity, parser reset during 'segments' + // mode, or switching from 'sequence' to 'segments' mode. Individual track + // buffers can also be notified of an updated coded frame group start in edge + // cases. See further comments in ProcessFrame(). + bool pending_notify_all_group_start_ = true; // Tracks the MSE coded frame processing variable of same name. // Initially kNoTimestamp, meaning "unset".
diff --git a/media/filters/frame_processor_unittest.cc b/media/filters/frame_processor_unittest.cc index 679a6f4..7c5fb88 100644 --- a/media/filters/frame_processor_unittest.cc +++ b/media/filters/frame_processor_unittest.cc
@@ -253,8 +253,7 @@ // thereof of new coded frame group by the FrameProcessor. See // https://crbug.com/580613. bool in_coded_frame_group() { - return frame_processor_->coded_frame_group_last_dts_ != - kNoDecodeTimestamp(); + return !frame_processor_->pending_notify_all_group_start_; } void seek(ChunkDemuxerStream* stream, base::TimeDelta seek_time) { @@ -652,7 +651,15 @@ // This causes [55,85) to merge with [100,230) here for audio, and similar // for video. See also https://crbug.com/620523. CheckExpectedRangesByTimestamp(audio_.get(), "{ [55,230) }"); - CheckExpectedRangesByTimestamp(video_.get(), "{ [55,240) }"); + // Note that 'sequence' mode group start signalling (if the decode time goes + // into the past) is per-track after the first frame has been processed. + // Hence 65, not 55 here. Similarly, 'segments' mode muxed tracks where + // discontinuity is followed by tracks whose first frames decrease in DTS + // relative to each other (allowed since media segments are not required to + // contain frames for every track) could result in decreasing range start + // times for those later tracks. See + // AudioVideo_OutOfSequence_After_Discontinuity for deeper verification. + CheckExpectedRangesByTimestamp(video_.get(), "{ [65,240) }"); } else { CheckExpectedRangesByTimestamp(audio_.get(), "{ [55,85) [100,130) [200,230) }"); @@ -691,6 +698,124 @@ } } +TEST_P(FrameProcessorTest, AudioVideo_OutOfSequence_After_Discontinuity) { + // Once a discontinuity is detected (and all tracks drop everything until the + // next keyframe per each track), we should gracefully handle the case where + // some tracks' first keyframe after the discontinuity are appended after, but + // end up earlier in timeline than some other track(s). In particular, we + // shouldn't notify all tracks that a new coded frame group is starting and + // begin dropping leading non-keyframes from all tracks. Rather, we should + // notify just the track encountering this new type of discontinuity. Since + // MSE doesn't require all media segments to contain media from every track, + // these append sequences can occur. + InSequence s; + AddTestTracks(HAS_AUDIO | HAS_VIDEO); + bool using_sequence_mode = GetParam(); + frame_processor_->SetSequenceMode(using_sequence_mode); + + // Begin with a simple set of appends for all tracks. + if (using_sequence_mode) { + // Allow room in the timeline for the last audio append (50K, below) in this + // test to remain within default append window [0, +Infinity]. Moving the + // sequence mode appends to begin at time 100ms, the same time as the first + // append, below, results in a -20ms offset (instead of a -120ms offset) + // applied to frames beginning at the first frame after the discontinuity + // caused by the video append at 160K, below. + SetTimestampOffset(frame_duration_ * 10); + } + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 14)); + ProcessFrames("100K 110K 120K", "110K 120K 130K"); + EXPECT_TRUE(in_coded_frame_group()); + EXPECT_EQ(base::TimeDelta(), timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,130) }"); + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) }"); + + // Trigger (normal) discontinuity with one track (video). + if (using_sequence_mode) + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 15)); + else + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 17)); + + ProcessFrames("", "160K"); + EXPECT_TRUE(in_coded_frame_group()); + + if (using_sequence_mode) { + // The new video buffer is relocated into [140,150). + EXPECT_EQ(frame_duration_ * -2, timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,130) }"); + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,150) }"); + } else { + // The new video buffer is at [160,170). + EXPECT_EQ(base::TimeDelta(), timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [100,130) }"); + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) [160,170) }"); + } + + // Append to the other track (audio) with lower time than the video frame we + // just appended. Append with a timestamp such that segments mode demonstrates + // we don't retroactively extend the new video buffer appended above's range + // start back to this audio start time. + if (using_sequence_mode) + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 15)); + else + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 17)); + + ProcessFrames("50K", ""); + EXPECT_TRUE(in_coded_frame_group()); + + // Because this is the first audio buffer appended following the discontinuity + // detected while appending the video frame, above, a new coded frame group + // for video is not triggered. + if (using_sequence_mode) { + // The new audio buffer is relocated into [30,40). Note the muxed 'sequence' + // mode append mode results in a buffered range gap in this case. + EXPECT_EQ(frame_duration_ * -2, timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [30,40) [100,130) }"); + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,150) }"); + } else { + EXPECT_EQ(base::TimeDelta(), timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [50,60) [100,130) }"); + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) [160,170) }"); + } + + // Finally, append a non-keyframe to the first track (video), to continue the + // GOP that started the normal discontinuity on the previous video append. + if (using_sequence_mode) + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 16)); + else + EXPECT_CALL(callbacks_, PossibleDurationIncrease(frame_duration_ * 18)); + + ProcessFrames("", "170"); + EXPECT_TRUE(in_coded_frame_group()); + + // Verify the final buffers. First, re-seek audio since we appended data + // earlier than what already satisfied our initial seek to start. We satisfy + // the seek with the first buffer in [0,1000). + seek(audio_.get(), base::TimeDelta()); + if (using_sequence_mode) { + // The new video buffer is relocated into [150,160). + EXPECT_EQ(frame_duration_ * -2, timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [30,40) [100,130) }"); + CheckReadsThenReadStalls(audio_.get(), "30:50"); + seek(audio_.get(), 10 * frame_duration_); + CheckReadsThenReadStalls(audio_.get(), "100 110 120"); + + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,160) }"); + CheckReadsThenReadStalls(video_.get(), "110 120 130 140:160 150:170"); + } else { + EXPECT_EQ(base::TimeDelta(), timestamp_offset_); + CheckExpectedRangesByTimestamp(audio_.get(), "{ [50,60) [100,130) }"); + CheckReadsThenReadStalls(audio_.get(), "50"); + seek(audio_.get(), 10 * frame_duration_); + CheckReadsThenReadStalls(audio_.get(), "100 110 120"); + + CheckExpectedRangesByTimestamp(video_.get(), "{ [100,140) [160,180) }"); + CheckReadsThenReadStalls(video_.get(), "110 120 130"); + seek(video_.get(), 16 * frame_duration_); + CheckReadsThenReadStalls(video_.get(), "160 170"); + } +} + TEST_P(FrameProcessorTest, AppendWindowFilterOfNegativeBufferTimestampsWithPrerollDiscard) { InSequence s;
diff --git a/media/gpu/android/media_codec_video_decoder.cc b/media/gpu/android/media_codec_video_decoder.cc index 5e3ff87..e0595c6 100644 --- a/media/gpu/android/media_codec_video_decoder.cc +++ b/media/gpu/android/media_codec_video_decoder.cc
@@ -95,12 +95,14 @@ MediaCodecVideoDecoder::MediaCodecVideoDecoder( scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, base::Callback<gpu::GpuCommandBufferStub*()> get_stub_cb, + VideoFrameFactory::OutputWithReleaseMailboxCB output_cb, DeviceInfo* device_info, AVDACodecAllocator* codec_allocator, std::unique_ptr<AndroidVideoSurfaceChooser> surface_chooser, std::unique_ptr<VideoFrameFactory> video_frame_factory) : state_(State::kBeforeSurfaceInit), lazy_init_pending_(true), + output_cb_(output_cb), gpu_task_runner_(gpu_task_runner), get_stub_cb_(get_stub_cb), codec_allocator_(codec_allocator), @@ -146,8 +148,6 @@ codec_config_->initial_expected_coded_size = config.coded_size(); // TODO(watk): Parse config.extra_data(). - output_cb_ = output_cb; - // We defer initialization of the Surface and MediaCodec until we // receive a Decode() call to avoid consuming those resources in cases where // we'll be destructed before getting a Decode(). Failure to initialize those
diff --git a/media/gpu/android/media_codec_video_decoder.h b/media/gpu/android/media_codec_video_decoder.h index ff18af8..dce855f77 100644 --- a/media/gpu/android/media_codec_video_decoder.h +++ b/media/gpu/android/media_codec_video_decoder.h
@@ -56,6 +56,7 @@ MediaCodecVideoDecoder( scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, base::Callback<gpu::GpuCommandBufferStub*()> get_stub_cb, + VideoFrameFactory::OutputWithReleaseMailboxCB output_cb, DeviceInfo* device_info, AVDACodecAllocator* codec_allocator, std::unique_ptr<AndroidVideoSurfaceChooser> surface_chooser, @@ -138,7 +139,7 @@ State state_; bool lazy_init_pending_; std::deque<PendingDecode> pending_decodes_; - OutputCB output_cb_; + VideoFrameFactory::OutputWithReleaseMailboxCB output_cb_; // The ongoing drain operation, if any. base::Optional<DrainType> drain_type_;
diff --git a/media/gpu/android/video_frame_factory.h b/media/gpu/android/video_frame_factory.h index 8bebbd1..ec5b150 100644 --- a/media/gpu/android/video_frame_factory.h +++ b/media/gpu/android/video_frame_factory.h
@@ -29,7 +29,11 @@ public: using GetStubCb = base::Callback<gpu::GpuCommandBufferStub*()>; using InitCb = base::Callback<void(scoped_refptr<SurfaceTextureGLOwner>)>; - using FrameCreatedCb = base::Callback<void(const scoped_refptr<VideoFrame>&)>; + + // These mirror types from MojoVideoDecoderService. + using ReleaseMailboxCB = base::Callback<void(const gpu::SyncToken&)>; + using OutputWithReleaseMailboxCB = + base::Callback<void(ReleaseMailboxCB, const scoped_refptr<VideoFrame>&)>; VideoFrameFactory() = default; virtual ~VideoFrameFactory() = default; @@ -50,7 +54,7 @@ scoped_refptr<SurfaceTextureGLOwner> surface_texture, base::TimeDelta timestamp, gfx::Size natural_size, - FrameCreatedCb frame_created_cb) = 0; + OutputWithReleaseMailboxCB output_cb) = 0; }; } // namespace media
diff --git a/media/gpu/android/video_frame_factory_impl.cc b/media/gpu/android/video_frame_factory_impl.cc index efa7b847..1b5f34f1 100644 --- a/media/gpu/android/video_frame_factory_impl.cc +++ b/media/gpu/android/video_frame_factory_impl.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/memory/ref_counted.h" +#include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/task_runner_util.h" #include "gpu/command_buffer/common/constants.h" @@ -15,6 +16,7 @@ #include "gpu/command_buffer/service/texture_manager.h" #include "gpu/ipc/service/gpu_channel.h" #include "gpu/ipc/service/gpu_command_buffer_stub.h" +#include "media/base/bind_to_current_loop.h" #include "media/base/video_frame.h" #include "media/gpu//android/codec_image.h" #include "media/gpu/android/codec_wrapper.h" @@ -25,6 +27,10 @@ namespace media { namespace { +bool MakeContextCurrent(gpu::GpuCommandBufferStub* stub) { + return stub && stub->decoder()->MakeCurrent(); +} + // Creates a new EXTERNAL_OES Texture with |image| attached, and returns the // TextureRef. // TODO(watk): Refactor this when CommandBufferHelper lands @@ -116,60 +122,96 @@ scoped_refptr<SurfaceTextureGLOwner> surface_texture, base::TimeDelta timestamp, gfx::Size natural_size, - FrameCreatedCb frame_created_cb) { - base::PostTaskAndReplyWithResult( - gpu_task_runner_.get(), FROM_HERE, - base::Bind(&GpuVideoFrameFactory::CreateVideoFrame, - base::Unretained(gpu_video_frame_factory_.get()), - base::Passed(&output_buffer), surface_texture, timestamp, - natural_size), - std::move(frame_created_cb)); + OutputWithReleaseMailboxCB output_cb) { + gpu_task_runner_->PostTask( + FROM_HERE, base::Bind(&GpuVideoFrameFactory::CreateVideoFrame, + base::Unretained(gpu_video_frame_factory_.get()), + base::Passed(&output_buffer), surface_texture, + timestamp, natural_size, std::move(output_cb), + base::ThreadTaskRunnerHandle::Get())); } GpuVideoFrameFactory::GpuVideoFrameFactory() : weak_factory_(this) {} -GpuVideoFrameFactory::~GpuVideoFrameFactory() = default; +GpuVideoFrameFactory::~GpuVideoFrameFactory() { + if (stub_) + stub_->RemoveDestructionObserver(this); + ClearTextureRefs(); +} scoped_refptr<SurfaceTextureGLOwner> GpuVideoFrameFactory::Initialize( VideoFrameFactoryImpl::GetStubCb get_stub_cb) { - auto* stub = std::move(get_stub_cb).Run(); - if (!stub) + stub_ = get_stub_cb.Run(); + if (!MakeContextCurrent(stub_)) return nullptr; - stub_ = stub->AsWeakPtr(); - - auto* decoder = stub_->decoder(); - if (!decoder || !decoder->MakeCurrent()) - return nullptr; + stub_->AddDestructionObserver(this); return SurfaceTextureGLOwnerImpl::Create(); } -scoped_refptr<VideoFrame> GpuVideoFrameFactory::CreateVideoFrame( +void GpuVideoFrameFactory::CreateVideoFrame( std::unique_ptr<CodecOutputBuffer> output_buffer, scoped_refptr<SurfaceTextureGLOwner> surface_texture, base::TimeDelta timestamp, - gfx::Size natural_size) { - if (!stub_) - return nullptr; + gfx::Size natural_size, + VideoFrameFactory::OutputWithReleaseMailboxCB output_cb, + scoped_refptr<base::SingleThreadTaskRunner> task_runner) { + scoped_refptr<VideoFrame> frame; + scoped_refptr<gpu::gles2::TextureRef> texture_ref; + CreateVideoFrameInternal(std::move(output_buffer), std::move(surface_texture), + timestamp, natural_size, &frame, &texture_ref); + if (!frame || !texture_ref) + return; + + // TODO(sandersd, watk): The VideoFrame release callback will not be called + // after MojoVideoDecoderService is destructed, so we have to release all + // our TextureRefs when |this| is destructed. This can unback outstanding + // VideoFrames (e.g., the current frame when the player is suspended). The + // release callback lifetime should be separate from MCVD or + // MojoVideoDecoderService (http://crbug.com/737220). + texture_refs_[texture_ref.get()] = texture_ref; + auto release_cb = BindToCurrentLoop(base::Bind( + &GpuVideoFrameFactory::DropTextureRef, weak_factory_.GetWeakPtr(), + base::Unretained(texture_ref.get()))); + task_runner->PostTask(FROM_HERE, base::Bind(output_cb, std::move(release_cb), + std::move(frame))); +} + +void GpuVideoFrameFactory::CreateVideoFrameInternal( + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<SurfaceTextureGLOwner> surface_texture, + base::TimeDelta timestamp, + gfx::Size natural_size, + scoped_refptr<VideoFrame>* video_frame_out, + scoped_refptr<gpu::gles2::TextureRef>* texture_ref_out) { + if (!MakeContextCurrent(stub_)) + return; // TODO(watk): Which of these null checks are unnecessary? - gpu::gles2::GLES2Decoder* decoder = stub_->decoder(); - if (!decoder->MakeCurrent()) - return nullptr; - gpu::gles2::ContextGroup* group = decoder->GetContextGroup(); + gpu::gles2::ContextGroup* group = stub_->decoder()->GetContextGroup(); if (!group) - return nullptr; + return; gpu::gles2::TextureManager* texture_manager = group->texture_manager(); if (!texture_manager) - return nullptr; + return; gpu::GpuChannel* channel = stub_->channel(); if (!channel) - return nullptr; + return; gpu::SyncPointManager* sync_point_manager = channel->sync_point_manager(); if (!sync_point_manager) - return nullptr; + return; gpu::gles2::MailboxManager* mailbox_manager = group->mailbox_manager(); if (!mailbox_manager) - return nullptr; + return; + + gfx::Size size = output_buffer->size(); + gfx::Rect visible_rect(size); + // Check that we can create a VideoFrame for this config before creating the + // TextureRef so that we don't have to clean up the TextureRef if creating the + // frame fails. + if (!VideoFrame::IsValidConfig(PIXEL_FORMAT_ARGB, VideoFrame::STORAGE_OPAQUE, + size, visible_rect, natural_size)) { + return; + } // Create a new CodecImage to back the video frame and try to render it early. auto image = make_scoped_refptr( @@ -180,30 +222,55 @@ internal::MaybeRenderEarly(&images_); // Create a new Texture with the image attached and put it into a mailbox - gfx::Size size = output_buffer->size(); auto texture_ref = - CreateTexture(decoder, texture_manager, std::move(image), size); - // TODO(watk): The TextureRef will be deleted at the end of this scope because - // mailboxes don't keep a strong ref. A coming change to - // MojoVideoDecoderService will deliver a callback when the VideoFrame is - // destroyed by the client. So we can simply bind the ref into the callback, - // along with a thread hop to ensure the ref is dropped on this thread. + CreateTexture(stub_->decoder(), texture_manager, std::move(image), size); gpu::Mailbox mailbox = gpu::Mailbox::Generate(); mailbox_manager->ProduceTexture(mailbox, texture_ref->texture()); - gpu::SyncToken sync_token( - gpu::CommandBufferNamespace::GPU_IO, // TODO(sandersd): Is this right? - stub_->stream_id(), stub_->command_buffer_id(), - 0); // TODO(sandersd): Current release count? + // TODO(watk): Remove this once it's possible to leave the mailbox + // sync token empty (http://crrev.com/c/548973). + gpu::SyncToken sync_token(gpu::CommandBufferNamespace::GPU_IO, + stub_->stream_id(), stub_->command_buffer_id(), 0); gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes]; mailbox_holders[0] = gpu::MailboxHolder(mailbox, sync_token, GL_TEXTURE_EXTERNAL_OES); - gfx::Rect visible_rect(size); // Note: The pixel format doesn't matter. - return VideoFrame::WrapNativeTextures(PIXEL_FORMAT_ARGB, mailbox_holders, - VideoFrame::ReleaseMailboxCB(), size, - visible_rect, natural_size, timestamp); + auto frame = VideoFrame::WrapNativeTextures( + PIXEL_FORMAT_ARGB, mailbox_holders, VideoFrame::ReleaseMailboxCB(), size, + visible_rect, natural_size, timestamp); + + *video_frame_out = std::move(frame); + *texture_ref_out = std::move(texture_ref); +} + +void GpuVideoFrameFactory::OnWillDestroyStub() { + DCHECK(stub_); + ClearTextureRefs(); + stub_ = nullptr; +} + +void GpuVideoFrameFactory::ClearTextureRefs() { + DCHECK(stub_ || texture_refs_.empty()); + // If we fail to make the context current, we have to notify the TextureRefs + // so they don't try to delete textures without a context. + if (!MakeContextCurrent(stub_)) { + for (const auto& kv : texture_refs_) + kv.first->ForceContextLost(); + } + texture_refs_.clear(); +} + +void GpuVideoFrameFactory::DropTextureRef(gpu::gles2::TextureRef* ref, + const gpu::SyncToken& token) { + auto it = texture_refs_.find(ref); + if (it == texture_refs_.end()) + return; + // If we fail to make the context current, we have to notify the TextureRef + // so it doesn't try to delete a texture without a context. + if (!MakeContextCurrent(stub_)) + ref->ForceContextLost(); + texture_refs_.erase(it); } void GpuVideoFrameFactory::OnImageDestructed(CodecImage* image) {
diff --git a/media/gpu/android/video_frame_factory_impl.h b/media/gpu/android/video_frame_factory_impl.h index 2ba3e3cf4..32c9dd98 100644 --- a/media/gpu/android/video_frame_factory_impl.h +++ b/media/gpu/android/video_frame_factory_impl.h
@@ -37,7 +37,7 @@ scoped_refptr<SurfaceTextureGLOwner> surface_texture, base::TimeDelta timestamp, gfx::Size natural_size, - FrameCreatedCb frame_created_cb) override; + OutputWithReleaseMailboxCB output_cb) override; private: scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_; @@ -48,29 +48,57 @@ // GpuVideoFrameFactory is an implementation detail of VideoFrameFactoryImpl. It // may be created on any thread but only accessed on the gpu thread thereafter. -class GpuVideoFrameFactory { +class GpuVideoFrameFactory + : public gpu::GpuCommandBufferStub::DestructionObserver { public: GpuVideoFrameFactory(); - ~GpuVideoFrameFactory(); + ~GpuVideoFrameFactory() override; scoped_refptr<SurfaceTextureGLOwner> Initialize( VideoFrameFactory::GetStubCb get_stub_cb); - scoped_refptr<VideoFrame> CreateVideoFrame( + + // Creates a VideoFrame and returns it via posting |output_cb| to + // |task_runner|. + void CreateVideoFrame( std::unique_ptr<CodecOutputBuffer> output_buffer, scoped_refptr<SurfaceTextureGLOwner> surface_texture, base::TimeDelta timestamp, - gfx::Size natural_size); + gfx::Size natural_size, + VideoFrameFactory::OutputWithReleaseMailboxCB output_cb, + scoped_refptr<base::SingleThreadTaskRunner> task_runner); private: + // Creates a TextureRef and VideoFrame. + void CreateVideoFrameInternal( + std::unique_ptr<CodecOutputBuffer> output_buffer, + scoped_refptr<SurfaceTextureGLOwner> surface_texture, + base::TimeDelta timestamp, + gfx::Size natural_size, + scoped_refptr<VideoFrame>* video_frame_out, + scoped_refptr<gpu::gles2::TextureRef>* texture_ref_out); + // Removes |image| from |images_|. void OnImageDestructed(CodecImage* image); - // Tries to render the first renderable image from |images_|. - void MaybeRenderEarly(); + void OnWillDestroyStub() override; + + // Clears |texture_refs_|. Makes the gl context current. + void ClearTextureRefs(); + + // Removes |ref| from texture_refs_. Makes the gl context current. + // |token| is ignored because MojoVideoDecoderService guarantees that it has + // already passed by the time we get the callback. + void DropTextureRef(gpu::gles2::TextureRef* ref, const gpu::SyncToken& token); // Outstanding images that should be considered for early rendering. std::vector<CodecImage*> images_; - base::WeakPtr<gpu::GpuCommandBufferStub> stub_; + + // Outstanding TextureRefs that are still referenced by a mailbox VideoFrame. + // They're kept alive until their mailboxes are released (or |this| is + // destructed). + std::map<gpu::gles2::TextureRef*, scoped_refptr<gpu::gles2::TextureRef>> + texture_refs_; + gpu::GpuCommandBufferStub* stub_; base::WeakPtrFactory<GpuVideoFrameFactory> weak_factory_; DISALLOW_COPY_AND_ASSIGN(GpuVideoFrameFactory);
diff --git a/media/gpu/avda_surface_bundle.cc b/media/gpu/avda_surface_bundle.cc index 8ccf550..a134748 100644 --- a/media/gpu/avda_surface_bundle.cc +++ b/media/gpu/avda_surface_bundle.cc
@@ -24,9 +24,16 @@ surface_texture_surface = gl::ScopedJavaSurface(); // Also release the back buffers. - if (surface_texture) - surface_texture->ReleaseBackBuffers(); - surface_texture = nullptr; + if (surface_texture) { + auto task_runner = surface_texture->task_runner(); + if (task_runner->RunsTasksOnCurrentThread()) { + surface_texture->ReleaseBackBuffers(); + } else { + task_runner->PostTask( + FROM_HERE, base::Bind(&SurfaceTextureGLOwner::ReleaseBackBuffers, + surface_texture)); + } + } } const base::android::JavaRef<jobject>& AVDASurfaceBundle::GetJavaSurface()
diff --git a/media/gpu/surface_texture_gl_owner.cc b/media/gpu/surface_texture_gl_owner.cc index 36f6b18..dda8cd75 100644 --- a/media/gpu/surface_texture_gl_owner.cc +++ b/media/gpu/surface_texture_gl_owner.cc
@@ -32,7 +32,10 @@ SurfaceTextureGLOwner::SurfaceTextureGLOwner() : base::RefCountedDeleteOnSequence<SurfaceTextureGLOwner>( - base::ThreadTaskRunnerHandle::Get()) {} + base::ThreadTaskRunnerHandle::Get()), + task_runner_(base::ThreadTaskRunnerHandle::Get()) {} + +SurfaceTextureGLOwner::~SurfaceTextureGLOwner() = default; scoped_refptr<SurfaceTextureGLOwner> SurfaceTextureGLOwnerImpl::Create() { GLuint texture_id; @@ -89,7 +92,6 @@ } gl::ScopedJavaSurface SurfaceTextureGLOwnerImpl::CreateJavaSurface() const { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); return gl::ScopedJavaSurface(surface_texture_.get()); }
diff --git a/media/gpu/surface_texture_gl_owner.h b/media/gpu/surface_texture_gl_owner.h index f24fe37c..475d353 100644 --- a/media/gpu/surface_texture_gl_owner.h +++ b/media/gpu/surface_texture_gl_owner.h
@@ -35,6 +35,10 @@ public: SurfaceTextureGLOwner(); + scoped_refptr<base::SingleThreadTaskRunner> task_runner() { + return task_runner_; + } + // Returns the GL texture id that the SurfaceTexture is attached to. virtual GLuint GetTextureId() const = 0; virtual gl::GLContext* GetContext() const = 0; @@ -71,9 +75,11 @@ protected: friend class base::RefCountedDeleteOnSequence<SurfaceTextureGLOwner>; friend class base::DeleteHelper<SurfaceTextureGLOwner>; - virtual ~SurfaceTextureGLOwner() = default; + virtual ~SurfaceTextureGLOwner(); private: + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + DISALLOW_COPY_AND_ASSIGN(SurfaceTextureGLOwner); };
diff --git a/media/mojo/interfaces/BUILD.gn b/media/mojo/interfaces/BUILD.gn index 88e8bcb..0d98b3c 100644 --- a/media/mojo/interfaces/BUILD.gn +++ b/media/mojo/interfaces/BUILD.gn
@@ -46,6 +46,12 @@ use_once_callback = false } +mojom("constants") { + sources = [ + "constants.mojom", + ] +} + mojom("remoting") { sources = [ "remoting.mojom",
diff --git a/media/mojo/interfaces/constants.mojom b/media/mojo/interfaces/constants.mojom new file mode 100644 index 0000000..79208ace --- /dev/null +++ b/media/mojo/interfaces/constants.mojom
@@ -0,0 +1,10 @@ +// 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. + +module media.mojom; + +// The default service name for MediaService running the process specified by +// the |mojo_media_host| gn variable. This must match the name in +// media/mojo/services/media_manifest.json +const string kMediaServiceName = "media";
diff --git a/media/mojo/services/BUILD.gn b/media/mojo/services/BUILD.gn index 8c9a379e..87b60ed 100644 --- a/media/mojo/services/BUILD.gn +++ b/media/mojo/services/BUILD.gn
@@ -146,6 +146,7 @@ "//media/mojo/clients", "//media/mojo/common", "//media/mojo/interfaces", + "//media/mojo/interfaces:constants", "//services/service_manager/public/cpp:service_test_support", "//testing/gmock", "//testing/gtest",
diff --git a/media/mojo/services/media_service_unittest.cc b/media/mojo/services/media_service_unittest.cc index a4cdebf..83d0cc0 100644 --- a/media/mojo/services/media_service_unittest.cc +++ b/media/mojo/services/media_service_unittest.cc
@@ -18,6 +18,7 @@ #include "media/mojo/clients/mojo_demuxer_stream_impl.h" #include "media/mojo/common/media_type_converters.h" #include "media/mojo/features.h" +#include "media/mojo/interfaces/constants.mojom.h" #include "media/mojo/interfaces/content_decryption_module.mojom.h" #include "media/mojo/interfaces/decryptor.mojom.h" #include "media/mojo/interfaces/interface_factory.mojom.h" @@ -79,7 +80,7 @@ ServiceTest::SetUp(); media::mojom::MediaServicePtr media_service; - connector()->BindInterface("media", &media_service); + connector()->BindInterface(media::mojom::kMediaServiceName, &media_service); service_manager::mojom::InterfaceProviderPtr interfaces; auto provider = base::MakeUnique<MediaInterfaceProvider>( @@ -200,7 +201,7 @@ // live InterfaceFactory impls, not MediaService impls, so this pipe should // be closed when the last InterfaceFactory is destroyed. media::mojom::MediaServicePtr media_service; - connector()->BindInterface("media", &media_service); + connector()->BindInterface(media::mojom::kMediaServiceName, &media_service); media_service.set_connection_error_handler( base::Bind(&MediaServiceTest::ConnectionClosed, base::Unretained(this)));
diff --git a/mojo/public/js/new_bindings/base.js b/mojo/public/js/new_bindings/base.js index 911d476..65f6c05 100644 --- a/mojo/public/js/new_bindings/base.js +++ b/mojo/public/js/new_bindings/base.js
@@ -99,12 +99,20 @@ mojomRegistry.set(id, LoadState.LOADED); } - function loadMojomIfNecessary(id, url) { + function loadMojomIfNecessary(id, relativePath) { if (mojomRegistry.has(id)) { return; } + if (internal.global.document === undefined) { + throw new Error( + 'Mojom dependency autoloading is not implemented in workers. ' + + 'Please see config variable mojo.config.autoLoadMojomDeps for more ' + + 'details.'); + } + markMojomPendingLoad(id); + var url = new URL(relativePath, document.currentScript.src).href; internal.global.document.write('<script type="text/javascript" src="' + url + '"><' + '/script>'); }
diff --git a/mojo/public/tools/bindings/chromium_bindings_configuration.gni b/mojo/public/tools/bindings/chromium_bindings_configuration.gni index faaef88..42b107d 100644 --- a/mojo/public/tools/bindings/chromium_bindings_configuration.gni +++ b/mojo/public/tools/bindings/chromium_bindings_configuration.gni
@@ -19,7 +19,6 @@ "//content/public/common/typemaps.gni", "//device/bluetooth/public/interfaces/typemaps.gni", "//device/gamepad/public/interfaces/typemaps.gni", - "//device/generic_sensor/public/interfaces/typemaps.gni", "//extensions/common/typemaps.gni", "//gpu/ipc/common/typemaps.gni", "//media/capture/mojo/typemaps.gni", @@ -28,6 +27,7 @@ "//mojo/common/typemaps.gni", "//mojo/public/cpp/bindings/tests/chromium_typemaps.gni", "//net/interfaces/typemaps.gni", + "//services/device/public/interfaces/typemaps.gni", "//services/identity/public/cpp/typemaps.gni", "//services/preferences/public/cpp/typemaps.gni", "//services/resource_coordinator/public/cpp/typemaps.gni",
diff --git a/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl b/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl index 7772b20..d280176 100644 --- a/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl +++ b/mojo/public/tools/bindings/generators/js_templates/module.amd.tmpl
@@ -33,9 +33,7 @@ mojo.internal.exposeNamespace('{{import.namespace}}'); if (mojo.config.autoLoadMojomDeps) { mojo.internal.loadMojomIfNecessary( - '{{import.path}}', - new URL('{{import|get_relative_url(module)}}.js', - document.currentScript.src).href); + '{{import.path}}', '{{import|get_relative_url(module)}}.js'); } {%- endfor %}
diff --git a/net/cert/cert_verify_proc_android.cc b/net/cert/cert_verify_proc_android.cc index 7d1fa28a..28082f8 100644 --- a/net/cert/cert_verify_proc_android.cc +++ b/net/cert/cert_verify_proc_android.cc
@@ -34,7 +34,9 @@ base::LazyInstance<scoped_refptr<CertNetFetcher>>::Leaky g_cert_net_fetcher = LAZY_INSTANCE_INITIALIZER; -// TODO(joth): Fetch the authentication type from SSL rather than hardcode. +// Android ignores the authType parameter to +// X509TrustManager.checkServerTrusted, so pass in a dummy value. See +// https://crbug.com/627154. const char kAuthType[] = "RSA"; // The maximum number of AIA fetches that TryVerifyWithAIAFetching() will
diff --git a/net/http/http_cache.cc b/net/http/http_cache.cc index 88a4e52..c196e68 100644 --- a/net/http/http_cache.cc +++ b/net/http/http_cache.cc
@@ -952,6 +952,32 @@ ProcessQueuedTransactions(entry); } +void HttpCache::DoomEntryValidationNoMatch(ActiveEntry* entry) { + // Validating transaction received a non-matching response. + DCHECK(entry->headers_transaction); + + entry->headers_transaction = nullptr; + if (entry->HasNoTransactions() && !entry->will_process_queued_transactions) { + entry->disk_entry->Doom(); + DestroyEntry(entry); + return; + } + + DoomActiveEntry(entry->disk_entry->GetKey()); + + // Restart only add_to_entry_queue transactions. + // Post task here to avoid a race in creating the entry between |transaction| + // and the add_to_entry_queue transactions. Reset the queued transaction's + // cache pending state so that in case it's destructor is invoked, it's ok + // for the transaction to not be found in this entry. + for (auto* transaction : entry->add_to_entry_queue) { + transaction->ResetCachePendingState(); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(transaction->io_callback(), net::ERR_CACHE_RACE)); + } + entry->add_to_entry_queue.clear(); +} + void HttpCache::RemoveAllQueuedTransactions(ActiveEntry* entry, TransactionList* list) { // Process done_headers_queue before add_to_entry_queue to maintain FIFO @@ -968,8 +994,8 @@ void HttpCache::ProcessEntryFailure(ActiveEntry* entry, Transaction* transaction) { - // Failure case is either writer failing to completely write the response to - // the cache or validating transaction received a non-304 response. + // The writer failed to completely write the response to + // the cache. if (entry->headers_transaction && transaction != entry->headers_transaction) RestartHeadersTransaction(entry);
diff --git a/net/http/http_cache.h b/net/http/http_cache.h index e420c72..c2221cc 100644 --- a/net/http/http_cache.h +++ b/net/http/http_cache.h
@@ -424,6 +424,11 @@ // Called when the transaction has finished reading from this entry. void DoneReadingFromEntry(ActiveEntry* entry, Transaction* transaction); + // Called when the transaction has received a non-matching response to + // validation and it's not the transaction responsible for writing the + // response body. + void DoomEntryValidationNoMatch(ActiveEntry* entry); + // Removes and returns all queued transactions in |entry| in FIFO order. This // includes transactions that have completed the headers phase and those that // have not been added to the entry yet in that order. |list| is the output @@ -431,8 +436,7 @@ void RemoveAllQueuedTransactions(ActiveEntry* entry, TransactionList* list); // Processes either writer's failure to write response body or - // headers_transactions's failure to write headers. Also invoked when headers - // transaction's validation result is not a match. + // headers_transactions's failure to write headers. void ProcessEntryFailure(ActiveEntry* entry, Transaction* transaction); // Restarts headers_transaction and done_headers_queue transactions.
diff --git a/net/http/http_cache_transaction.cc b/net/http/http_cache_transaction.cc index a2d536b0..10b6d91 100644 --- a/net/http/http_cache_transaction.cc +++ b/net/http/http_cache_transaction.cc
@@ -165,6 +165,7 @@ handling_206_(false), cache_pending_(false), done_reading_(false), + done_headers_create_new_entry_(false), vary_mismatch_(false), couldnt_conditionalize_request_(false), bypass_lock_for_test_(false), @@ -760,6 +761,9 @@ case STATE_ADD_TO_ENTRY_COMPLETE: rv = DoAddToEntryComplete(rv); break; + case STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE: + rv = DoDoneHeadersAddToEntryComplete(rv); + break; case STATE_CACHE_READ_RESPONSE: DCHECK_EQ(OK, rv); rv = DoCacheReadResponse(); @@ -1119,10 +1123,23 @@ // already created the entry. If we want to eliminate this issue, we // need an atomic OpenOrCreate() method exposed by the disk cache. DLOG(WARNING) << "Unable to create cache entry"; + + // Set the mode to NONE in order to bypass the cache entry and read from + // the network directly. mode_ = NONE; - if (partial_) - partial_->RestoreHeaders(&custom_request_->extra_headers); - TransitionToState(STATE_SEND_REQUEST); + if (!done_headers_create_new_entry_) { + if (partial_) + partial_->RestoreHeaders(&custom_request_->extra_headers); + TransitionToState(STATE_SEND_REQUEST); + return OK; + } + // The headers have already been received as a result of validation, + // triggering the doom of the old entry. So no network request needs to + // be sent. Note that since mode_ is NONE, the response won't be written + // to cache. Transition to STATE_CACHE_WRITE_RESPONSE as that's the state + // the transaction left off on when it tried to create the new entry. + done_headers_create_new_entry_ = false; + TransitionToState(STATE_CACHE_WRITE_RESPONSE); } return OK; } @@ -1131,13 +1148,25 @@ TRACE_EVENT0("io", "HttpCacheTransaction::DoAddToEntry"); DCHECK(new_entry_); cache_pending_ = true; - TransitionToState(STATE_ADD_TO_ENTRY_COMPLETE); net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_ADD_TO_ENTRY); DCHECK(entry_lock_waiting_since_.is_null()); - entry_lock_waiting_since_ = TimeTicks::Now(); int rv = cache_->AddTransactionToEntry(new_entry_, this); - if (rv == ERR_IO_PENDING) - AddCacheLockTimeoutHandler(new_entry_); + DCHECK_EQ(rv, ERR_IO_PENDING); + + // If headers phase is already done then we are here because of validation not + // matching and creating a new entry. This transaction should be the + // first transaction of that new entry and thus it should not be subject + // to any cache lock delays, thus returning early from here. + if (done_headers_create_new_entry_) { + DCHECK_EQ(mode_, WRITE); + TransitionToState(STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE); + return rv; + } + + TransitionToState(STATE_ADD_TO_ENTRY_COMPLETE); + + entry_lock_waiting_since_ = TimeTicks::Now(); + AddCacheLockTimeoutHandler(new_entry_); return rv; } @@ -1154,7 +1183,6 @@ } else { int timeout_milliseconds = 20 * 1000; if (partial_ && entry->writer && entry->writer->range_requested_) { - // Quickly timeout and bypass the cache if we're a range request and // we're blocked by the reader/writer lock. Doing so eliminates a long // running issue, http://crbug.com/31014, where two of the same media // resources could not be played back simultaneously due to one locking @@ -1242,6 +1270,26 @@ return OK; } +int HttpCache::Transaction::DoDoneHeadersAddToEntryComplete(int result) { + // This transaction's response headers did not match its ActiveEntry so it + // created a new ActiveEntry (new_entry_) to write to (and doomed the old + // one). Now that the new entry has been created, start writing the response. + + DCHECK_EQ(result, OK); + DCHECK_EQ(mode_, WRITE); + DCHECK(new_entry_); + DCHECK(response_.headers); + + cache_pending_ = false; + entry_ = new_entry_; + done_headers_create_new_entry_ = false; + DCHECK_NE(response_.headers->response_code(), 304); + DCHECK(cache_->CanTransactionWriteResponseHeaders( + entry_, this, partial_ != nullptr, false)); + TransitionToState(STATE_CACHE_WRITE_RESPONSE); + return OK; +} + int HttpCache::Transaction::DoCacheReadResponse() { TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadResponse"); DCHECK(entry_); @@ -1727,7 +1775,6 @@ int HttpCache::Transaction::DoCacheWriteResponse() { TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteResponse"); - TransitionToState(STATE_CACHE_WRITE_RESPONSE_COMPLETE); // Invalidate any current entry with a successful response if this transaction // cannot write to this entry. This transaction then continues to read from @@ -1736,12 +1783,21 @@ if (entry_ && response_.headers && !cache_->CanTransactionWriteResponseHeaders( entry_, this, partial_ != nullptr, is_match)) { - cache_->DoneWritingToEntry(entry_, false, this); + done_headers_create_new_entry_ = true; + + // The transaction needs to overwrite this response. Doom the current entry, + // create a new one (by going to STATE_INIT_ENTRY), and then jump straight + // to writing out the response, bypassing the headers checks. The mode_ is + // set to WRITE in order to doom any other existing entries that might exist + // so that this transaction can go straight to writing a response. + mode_ = WRITE; + TransitionToState(STATE_INIT_ENTRY); + cache_->DoomEntryValidationNoMatch(entry_); entry_ = nullptr; - mode_ = NONE; return OK; } + TransitionToState(STATE_CACHE_WRITE_RESPONSE_COMPLETE); return WriteResponseInfoToEntry(truncated_); }
diff --git a/net/http/http_cache_transaction.h b/net/http/http_cache_transaction.h index dec02f1..545e05c 100644 --- a/net/http/http_cache_transaction.h +++ b/net/http/http_cache_transaction.h
@@ -176,6 +176,10 @@ // and this transaction needs to be restarted. void SetValidatingCannotProceed(); + // Invoked to remove the association between a transaction waiting to be + // added to an entry and the entry. + void ResetCachePendingState() { cache_pending_ = false; } + // Returns the estimate of dynamically allocated memory in bytes. size_t EstimateMemoryUsage() const; @@ -211,6 +215,7 @@ STATE_CREATE_ENTRY_COMPLETE, STATE_ADD_TO_ENTRY, STATE_ADD_TO_ENTRY_COMPLETE, + STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE, STATE_CACHE_READ_RESPONSE, STATE_CACHE_READ_RESPONSE_COMPLETE, STATE_TOGGLE_UNUSED_SINCE_PREFETCH, @@ -282,6 +287,7 @@ int DoCreateEntryComplete(int result); int DoAddToEntry(); int DoAddToEntryComplete(int result); + int DoDoneHeadersAddToEntryComplete(int result); int DoCacheReadResponse(); int DoCacheReadResponseComplete(int result); int DoCacheToggleUnusedSincePrefetch(); @@ -502,6 +508,11 @@ bool handling_206_; // We must deal with this 206 response. bool cache_pending_; // We are waiting for the HttpCache. bool done_reading_; // All available data was read. + + // Headers have been received from the network and it's not a match with the + // existing entry. + bool done_headers_create_new_entry_; + bool vary_mismatch_; // The request doesn't match the stored vary data. bool couldnt_conditionalize_request_; bool bypass_lock_for_test_; // A test is exercising the cache lock.
diff --git a/net/http/http_cache_unittest.cc b/net/http/http_cache_unittest.cc index b01427a7..1c05602a 100644 --- a/net/http/http_cache_unittest.cc +++ b/net/http/http_cache_unittest.cc
@@ -1887,11 +1887,9 @@ // entries since none of them matched the headers of the earlier one. EXPECT_TRUE(cache.IsWriterPresent(kSimpleGET_Transaction.url)); - // Note that there are only 3 entries created and not 5 since every other - // transaction would have gone to the network. EXPECT_EQ(5, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(3, cache.disk_cache()->create_count()); + EXPECT_EQ(5, cache.disk_cache()->create_count()); // All requests depend on the writer, and the writer is between Start and // Read, i.e. idle. @@ -1907,7 +1905,72 @@ EXPECT_EQ(5, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(3, cache.disk_cache()->create_count()); + EXPECT_EQ(5, cache.disk_cache()->create_count()); +} + +// Parallel validation results in 200 for 1 transaction and validation matches +// for subsequent transactions. +TEST(HttpCache, SimpleGET_ParallelValidationNoMatch1) { + MockHttpCache cache; + MockHttpRequest request(kSimpleGET_Transaction); + + MockTransaction transaction(kSimpleGET_Transaction); + transaction.load_flags |= LOAD_VALIDATE_CACHE; + MockHttpRequest validate_request(transaction); + std::vector<std::unique_ptr<Context>> context_list; + const int kNumTransactions = 5; + for (int i = 0; i < kNumTransactions; ++i) { + context_list.push_back(base::MakeUnique<Context>()); + auto& c = context_list[i]; + c->result = cache.CreateTransaction(&c->trans); + ASSERT_THAT(c->result, IsOk()); + EXPECT_EQ(LOAD_STATE_IDLE, c->trans->GetLoadState()); + + MockHttpRequest* this_request = &request; + if (i == 1) + this_request = &validate_request; + + c->result = c->trans->Start(this_request, c->callback.callback(), + NetLogWithSource()); + } + + // All requests are waiting for the active entry. + for (auto& context : context_list) { + EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, context->trans->GetLoadState()); + } + + // Allow all requests to move from the Create queue to the active entry. + base::RunLoop().RunUntilIdle(); + + // The first request should be a writer at this point, and the second + // request should have passed the validation phase and created a new + // entry. Rest of them should be added to the new entry. + EXPECT_TRUE(cache.IsWriterPresent(kSimpleGET_Transaction.url)); + EXPECT_EQ(3, cache.GetCountDoneHeadersQueue(kSimpleGET_Transaction.url)); + + EXPECT_EQ(2, cache.network_layer()->transaction_count()); + EXPECT_EQ(0, cache.disk_cache()->open_count()); + EXPECT_EQ(2, cache.disk_cache()->create_count()); + + // All requests depend on the writer, and the writer is between Start and + // Read, i.e. idle. + for (auto& context : context_list) { + EXPECT_EQ(LOAD_STATE_IDLE, context->trans->GetLoadState()); + } + + EXPECT_EQ(1, cache.disk_cache()->doomed_count()); + + for (size_t i = 0; i < context_list.size(); i++) { + if (context_list[i]->result == ERR_IO_PENDING) + context_list[i]->result = context_list[i]->callback.WaitForResult(); + + ReadAndVerifyTransaction(context_list[i]->trans.get(), + kSimpleGET_Transaction); + } + + EXPECT_EQ(2, cache.network_layer()->transaction_count()); + EXPECT_EQ(0, cache.disk_cache()->open_count()); + EXPECT_EQ(2, cache.disk_cache()->create_count()); } // Tests that a GET followed by a DELETE results in DELETE immediately starting @@ -2156,7 +2219,7 @@ // The pending transactions will be added to a new entry. base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, cache.GetCountDoneHeadersQueue(kSimpleGET_Transaction.url)); + EXPECT_EQ(2, cache.GetCountDoneHeadersQueue(kSimpleGET_Transaction.url)); EXPECT_TRUE(cache.IsWriterPresent(kSimpleGET_Transaction.url)); // Complete the rest of the transactions. @@ -2165,7 +2228,7 @@ ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction); } - EXPECT_EQ(3, cache.network_layer()->transaction_count()); + EXPECT_EQ(2, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); EXPECT_EQ(2, cache.disk_cache()->create_count()); } @@ -2230,10 +2293,6 @@ c->trans->ResumeNetworkStart(); base::RunLoop().RunUntilIdle(); - // Headers transaction would have doomed the new entry created. - EXPECT_TRUE( - cache.disk_cache()->IsDiskEntryDoomed(kSimpleGET_Transaction.url)); - // Complete the rest of the transactions. for (auto& context : context_list) { if (!context) @@ -2243,7 +2302,7 @@ EXPECT_EQ(4, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(2, cache.disk_cache()->create_count()); + EXPECT_EQ(3, cache.disk_cache()->create_count()); } // Tests when a writer is destroyed mid-read and entry is marked as truncated, @@ -2372,10 +2431,6 @@ c->trans->ResumeNetworkStart(); base::RunLoop().RunUntilIdle(); - // Headers transaction would have doomed the new entry created. - EXPECT_TRUE( - cache.disk_cache()->IsDiskEntryDoomed(kSimpleGET_Transaction.url)); - // Complete the rest of the transactions. for (auto& context : context_list) { if (!context) @@ -2385,7 +2440,7 @@ EXPECT_EQ(4, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(2, cache.disk_cache()->create_count()); + EXPECT_EQ(3, cache.disk_cache()->create_count()); } // Tests that a transaction is currently in headers phase and is destroyed @@ -2679,7 +2734,7 @@ EXPECT_EQ(3, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(2, cache.disk_cache()->create_count()); + EXPECT_EQ(3, cache.disk_cache()->create_count()); // Now, make sure that the second request asks for the entry not to be stored. request_handler.set_no_store(true); @@ -2694,7 +2749,7 @@ EXPECT_EQ(3, cache.network_layer()->transaction_count()); EXPECT_EQ(0, cache.disk_cache()->open_count()); - EXPECT_EQ(2, cache.disk_cache()->create_count()); + EXPECT_EQ(3, cache.disk_cache()->create_count()); RemoveMockTransaction(&kFastNoStoreGET_Transaction); }
diff --git a/net/http/http_stream_factory_impl_job_controller.cc b/net/http/http_stream_factory_impl_job_controller.cc index c2c818b..207a9c3 100644 --- a/net/http/http_stream_factory_impl_job_controller.cc +++ b/net/http/http_stream_factory_impl_job_controller.cc
@@ -1168,6 +1168,12 @@ if (!original_url.SchemeIs(url::kHttpsScheme)) continue; + // If there is no QUIC version in the advertised versions supported by + // the net stack, ignore this entry. + if (SelectQuicVersion(alternative_service_info.advertised_versions()) == + QUIC_VERSION_UNSUPPORTED) + continue; + // Check whether there is an existing QUIC session to use for this origin. HostPortPair mapped_origin(origin.host(), origin.port()); ignore_result(ApplyHostMappingRules(original_url, &mapped_origin)); @@ -1195,6 +1201,25 @@ return first_alternative_service_info; } +QuicVersion HttpStreamFactoryImpl::JobController::SelectQuicVersion( + const QuicVersionVector& advertised_versions) { + const QuicVersionVector& supported_versions = + session_->params().quic_supported_versions; + if (advertised_versions.empty()) + return supported_versions[0]; + + for (const QuicVersion& supported : supported_versions) { + for (const QuicVersion& advertised : advertised_versions) { + if (supported == advertised) { + DCHECK_NE(QUIC_VERSION_UNSUPPORTED, supported); + return supported; + } + } + } + + return QUIC_VERSION_UNSUPPORTED; +} + bool HttpStreamFactoryImpl::JobController:: ShouldCreateAlternativeProxyServerJob( const ProxyInfo& proxy_info,
diff --git a/net/http/http_stream_factory_impl_job_controller.h b/net/http/http_stream_factory_impl_job_controller.h index f477953..71bd77a 100644 --- a/net/http/http_stream_factory_impl_job_controller.h +++ b/net/http/http_stream_factory_impl_job_controller.h
@@ -277,6 +277,13 @@ HttpStreamRequest::Delegate* delegate, HttpStreamRequest::StreamType stream_type); + // Returns a QuicVersion that has been advertised in |advertised_versions| + // and is supported. If more than one QuicVersions are supported, the first + // matched in the supported versions will be returned. If no mutually + // supported version is found, QUIC_VERSION_UNSUPPORTED_VERSION will be + // returned. + QuicVersion SelectQuicVersion(const QuicVersionVector& advertised_versions); + // Remove session from the SpdySessionRequestMap. void RemoveRequestFromSpdySessionRequestMap();
diff --git a/net/http/http_stream_factory_impl_job_controller_unittest.cc b/net/http/http_stream_factory_impl_job_controller_unittest.cc index 688fbd2..4917a63 100644 --- a/net/http/http_stream_factory_impl_job_controller_unittest.cc +++ b/net/http/http_stream_factory_impl_job_controller_unittest.cc
@@ -706,6 +706,35 @@ EXPECT_TRUE(HttpStreamFactoryImplPeer::IsJobControllerDeleted(factory_)); } +// Test that the controller does not create alternative job when the advertised +// versions in AlternativeServiceInfo do not contain any version that is +// supported. +TEST_F(HttpStreamFactoryImplJobControllerTest, + DoNotCreateAltJobIfQuicVersionsUnsupported) { + tcp_data_ = base::MakeUnique<SequencedSocketData>(nullptr, 0, nullptr, 0); + tcp_data_->set_connect_data(MockConnect(ASYNC, OK)); + HttpRequestInfo request_info; + request_info.method = "GET"; + request_info.url = GURL("https://www.google.com"); + + Initialize(request_info); + url::SchemeHostPort server(request_info.url); + AlternativeService alternative_service(kProtoQUIC, server.host(), 443); + base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1); + session_->http_server_properties()->SetQuicAlternativeService( + server, alternative_service, expiration, {QUIC_VERSION_UNSUPPORTED}); + + request_ = + job_controller_->Start(&request_delegate_, nullptr, net_log_.bound(), + HttpStreamRequest::HTTP_STREAM, DEFAULT_PRIORITY); + EXPECT_TRUE(job_controller_->main_job()); + EXPECT_FALSE(job_controller_->alternative_job()); + + request_.reset(); + VerifyBrokenAlternateProtocolMapping(request_info, false); + EXPECT_TRUE(HttpStreamFactoryImplPeer::IsJobControllerDeleted(factory_)); +} + TEST_F(HttpStreamFactoryImplJobControllerTest, OnStreamFailedForBothJobs) { quic_data_ = base::MakeUnique<MockQuicData>(); quic_data_->AddConnect(ASYNC, ERR_FAILED); @@ -2081,8 +2110,8 @@ } // Test that GetAlternativeServiceInfoFor will include a list of advertised -// versions. Returns an empty list if advertised versions are missing in -// HttpServerProperties. +// versions, which contains a version that is supported. Returns an empty list +// if advertised versions are missing in HttpServerProperties. TEST_F(HttpStreamFactoryImplJobControllerTest, GetAlternativeServiceInfoFor) { HttpRequestInfo request_info; request_info.method = "GET"; @@ -2105,30 +2134,61 @@ // Verify that JobController get an empty list of supported QUIC versions. EXPECT_TRUE(alt_svc_info.advertised_versions().empty()); - // Set alternative service for the same server with QUIC_VERSION_39 specified. + // Set alternative service for the same server with the same list of versions + // that is supported. + QuicVersionVector supported_versions = + session_->params().quic_supported_versions; ASSERT_TRUE(session_->http_server_properties()->SetQuicAlternativeService( - server, alternative_service, expiration, {QUIC_VERSION_39})); + server, alternative_service, expiration, supported_versions)); alt_svc_info = JobControllerPeer::GetAlternativeServiceInfoFor( job_controller_, request_info, &request_delegate_, HttpStreamRequest::HTTP_STREAM); - EXPECT_EQ(1u, alt_svc_info.advertised_versions().size()); - // Verify that JobController returns the single version specified in set. - EXPECT_EQ(QUIC_VERSION_39, alt_svc_info.advertised_versions()[0]); + std::sort(supported_versions.begin(), supported_versions.end()); + EXPECT_EQ(supported_versions, alt_svc_info.advertised_versions()); + + QuicVersion unsupported_version_1(QUIC_VERSION_UNSUPPORTED); + QuicVersion unsupported_version_2(QUIC_VERSION_UNSUPPORTED); + for (const QuicVersion& version : AllSupportedVersions()) { + if (std::find(supported_versions.begin(), supported_versions.end(), + version) != supported_versions.end()) + continue; + if (unsupported_version_1 == QUIC_VERSION_UNSUPPORTED) { + unsupported_version_1 = version; + continue; + } + unsupported_version_2 = version; + break; + } // Set alternative service for the same server with two QUIC versions: - // QUIC_VERSION_35, QUIC_VERSION_39. + // - one unsupported version: |unsupported_version_1|, + // - one supported version: session_->params().quic_supported_versions[0]. + QuicVersionVector mixed_quic_versions = { + unsupported_version_1, session_->params().quic_supported_versions[0]}; ASSERT_TRUE(session_->http_server_properties()->SetQuicAlternativeService( - server, alternative_service, expiration, - {QUIC_VERSION_35, QUIC_VERSION_39})); + server, alternative_service, expiration, mixed_quic_versions)); alt_svc_info = JobControllerPeer::GetAlternativeServiceInfoFor( job_controller_, request_info, &request_delegate_, HttpStreamRequest::HTTP_STREAM); EXPECT_EQ(2u, alt_svc_info.advertised_versions().size()); // Verify that JobController returns the list of versions specified in set. - EXPECT_EQ(QUIC_VERSION_35, alt_svc_info.advertised_versions()[0]); - EXPECT_EQ(QUIC_VERSION_39, alt_svc_info.advertised_versions()[1]); + std::sort(mixed_quic_versions.begin(), mixed_quic_versions.end()); + EXPECT_EQ(mixed_quic_versions, alt_svc_info.advertised_versions()); + + // Set alternative service for the same server with two unsupported QUIC + // versions: |unsupported_version_1|, |unsupported_version_2|. + ASSERT_TRUE(session_->http_server_properties()->SetQuicAlternativeService( + server, alternative_service, expiration, + {unsupported_version_1, unsupported_version_2})); + + alt_svc_info = JobControllerPeer::GetAlternativeServiceInfoFor( + job_controller_, request_info, &request_delegate_, + HttpStreamRequest::HTTP_STREAM); + // Verify that JobController returns no valid alternative service. + EXPECT_EQ(kProtoUnknown, alt_svc_info.alternative_service().protocol); + EXPECT_EQ(0u, alt_svc_info.advertised_versions().size()); } } // namespace test
diff --git a/net/http/mock_http_cache.cc b/net/http/mock_http_cache.cc index 5363d3af..514cc42 100644 --- a/net/http/mock_http_cache.cc +++ b/net/http/mock_http_cache.cc
@@ -370,10 +370,13 @@ //----------------------------------------------------------------------------- MockDiskCache::MockDiskCache() - : open_count_(0), create_count_(0), fail_requests_(false), - soft_failures_(false), double_create_check_(true), - fail_sparse_requests_(false) { -} + : open_count_(0), + create_count_(0), + doomed_count_(0), + fail_requests_(false), + soft_failures_(false), + double_create_check_(true), + fail_sparse_requests_(false) {} MockDiskCache::~MockDiskCache() { ReleaseAll(); @@ -468,6 +471,7 @@ if (it != entries_.end()) { it->second->Release(); entries_.erase(it); + doomed_count_++; } if (GetTestModeForEntry(key) & TEST_MODE_SYNC_CACHE_START)
diff --git a/net/http/mock_http_cache.h b/net/http/mock_http_cache.h index ca07304..d568c64 100644 --- a/net/http/mock_http_cache.h +++ b/net/http/mock_http_cache.h
@@ -144,6 +144,9 @@ // Returns number of times a cache entry was successfully created. int create_count() const { return create_count_; } + // Returns number of doomed entries. + int doomed_count() const { return doomed_count_; } + // Fail any subsequent CreateEntry and OpenEntry. void set_fail_requests() { fail_requests_ = true; } @@ -169,6 +172,7 @@ EntryMap entries_; int open_count_; int create_count_; + int doomed_count_; bool fail_requests_; bool soft_failures_; bool double_create_check_;
diff --git a/net/nqe/network_quality_estimator.cc b/net/nqe/network_quality_estimator.cc index c0316253..5c13b47 100644 --- a/net/nqe/network_quality_estimator.cc +++ b/net/nqe/network_quality_estimator.cc
@@ -766,8 +766,7 @@ bool private_network_request = nqe::internal::IsPrivateHost( request.context()->host_resolver(), - HostPortPair(request.url().host(), request.url().EffectiveIntPort()), - net_log_); + HostPortPair(request.url().host(), request.url().EffectiveIntPort())); return (use_localhost_requests_ || !private_network_request) && // Verify that response headers are received, so it can be ensured that
diff --git a/net/nqe/network_quality_estimator_util.cc b/net/nqe/network_quality_estimator_util.cc index bffaac2..34e6b77e 100644 --- a/net/nqe/network_quality_estimator_util.cc +++ b/net/nqe/network_quality_estimator_util.cc
@@ -10,6 +10,7 @@ #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/dns/host_resolver.h" +#include "net/log/net_log_with_source.h" namespace net { @@ -18,14 +19,14 @@ namespace internal { bool IsPrivateHost(HostResolver* host_resolver, - const HostPortPair& host_port_pair, - const NetLogWithSource& net_log) { + const HostPortPair& host_port_pair) { // Try resolving |host_port_pair.host()| synchronously. HostResolver::RequestInfo resolve_info(host_port_pair); resolve_info.set_allow_cached_response(true); AddressList addresses; // Resolve synchronously using the resolver's cache. - int rv = host_resolver->ResolveFromCache(resolve_info, &addresses, net_log); + int rv = host_resolver->ResolveFromCache(resolve_info, &addresses, + NetLogWithSource()); DCHECK_NE(rv, ERR_IO_PENDING); if (rv == OK && !addresses.empty()) {
diff --git a/net/nqe/network_quality_estimator_util.h b/net/nqe/network_quality_estimator_util.h index 94289c1e..02448241 100644 --- a/net/nqe/network_quality_estimator_util.h +++ b/net/nqe/network_quality_estimator_util.h
@@ -11,7 +11,6 @@ class HostPortPair; class HostResolver; -class NetLogWithSource; namespace nqe { @@ -28,8 +27,7 @@ // |host_port_pair|. The method is synchronous. // |host_resolver| must not be null. NET_EXPORT_PRIVATE bool IsPrivateHost(HostResolver* host_resolver, - const HostPortPair& host_port_pair, - const NetLogWithSource& net_log); + const HostPortPair& host_port_pair); } // namespace internal
diff --git a/net/nqe/network_quality_estimator_util_unittest.cc b/net/nqe/network_quality_estimator_util_unittest.cc index 0f80d78..896ac7b7 100644 --- a/net/nqe/network_quality_estimator_util_unittest.cc +++ b/net/nqe/network_quality_estimator_util_unittest.cc
@@ -29,8 +29,6 @@ TEST(NetworkQualityEstimatorUtilTest, ReservedHost) { std::unique_ptr<BoundTestNetLog> net_log = base::MakeUnique<BoundTestNetLog>(); - BoundTestNetLog* net_log_ptr = net_log.get(); - MockCachingHostResolver mock_host_resolver; scoped_refptr<net::RuleBasedHostResolverProc> rules( @@ -75,28 +73,23 @@ EXPECT_EQ(2u, mock_host_resolver.num_resolve()); EXPECT_FALSE(IsPrivateHost(&mock_host_resolver, - HostPortPair("2607:f8b0:4006:819::200e", 80), - net_log_ptr->bound())); + HostPortPair("2607:f8b0:4006:819::200e", 80))); EXPECT_EQ(1u, mock_host_resolver.num_resolve_from_cache()); - EXPECT_TRUE(IsPrivateHost(&mock_host_resolver, - HostPortPair("192.168.0.1", 443), - net_log_ptr->bound())); + EXPECT_TRUE( + IsPrivateHost(&mock_host_resolver, HostPortPair("192.168.0.1", 443))); EXPECT_EQ(2u, mock_host_resolver.num_resolve_from_cache()); - EXPECT_FALSE(IsPrivateHost(&mock_host_resolver, - HostPortPair("92.168.0.1", 443), - net_log_ptr->bound())); + EXPECT_FALSE( + IsPrivateHost(&mock_host_resolver, HostPortPair("92.168.0.1", 443))); EXPECT_EQ(3u, mock_host_resolver.num_resolve_from_cache()); - EXPECT_TRUE(IsPrivateHost(&mock_host_resolver, - HostPortPair("example1.com", 443), - net_log_ptr->bound())); + EXPECT_TRUE( + IsPrivateHost(&mock_host_resolver, HostPortPair("example1.com", 443))); EXPECT_EQ(4u, mock_host_resolver.num_resolve_from_cache()); - EXPECT_FALSE(IsPrivateHost(&mock_host_resolver, - HostPortPair("example2.com", 443), - net_log_ptr->bound())); + EXPECT_FALSE( + IsPrivateHost(&mock_host_resolver, HostPortPair("example2.com", 443))); EXPECT_EQ(5u, mock_host_resolver.num_resolve_from_cache()); // IsPrivateHost() should have queried only the resolver's cache. @@ -109,8 +102,6 @@ TEST(NetworkQualityEstimatorUtilTest, ReservedHostUncached) { std::unique_ptr<BoundTestNetLog> net_log = base::MakeUnique<BoundTestNetLog>(); - BoundTestNetLog* net_log_ptr = net_log.get(); - MockCachingHostResolver mock_host_resolver; scoped_refptr<net::RuleBasedHostResolverProc> rules( @@ -121,9 +112,8 @@ mock_host_resolver.set_rules(rules.get()); // Not in DNS host cache, so should not be marked as private. - EXPECT_FALSE(IsPrivateHost(&mock_host_resolver, - HostPortPair("example3.com", 443), - net_log_ptr->bound())); + EXPECT_FALSE( + IsPrivateHost(&mock_host_resolver, HostPortPair("example3.com", 443))); EXPECT_EQ(0u, mock_host_resolver.num_resolve()); EXPECT_EQ(1u, mock_host_resolver.num_resolve_from_cache()); @@ -140,9 +130,8 @@ EXPECT_EQ(OK, callback.WaitForResult()); EXPECT_EQ(1u, mock_host_resolver.num_resolve()); } - EXPECT_TRUE(IsPrivateHost(&mock_host_resolver, - HostPortPair("example3.com", 443), - net_log_ptr->bound())); + EXPECT_TRUE( + IsPrivateHost(&mock_host_resolver, HostPortPair("example3.com", 443))); // IsPrivateHost() should have queried only the resolver's cache. EXPECT_EQ(1u, mock_host_resolver.num_resolve()); @@ -163,18 +152,12 @@ scoped_refptr<net::RuleBasedHostResolverProc> rules( new net::RuleBasedHostResolverProc(nullptr)); - EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("localhost", 443), - net_log_ptr->bound())); - EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("localhost6", 443), - net_log_ptr->bound())); - EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("127.0.0.1", 80), - net_log_ptr->bound())); - EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("0.0.0.0", 80), - net_log_ptr->bound())); - EXPECT_TRUE( - IsPrivateHost(&resolver, HostPortPair("::1", 80), net_log_ptr->bound())); - EXPECT_FALSE(IsPrivateHost(&resolver, HostPortPair("google.com", 80), - net_log_ptr->bound())); + EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("localhost", 443))); + EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("localhost6", 443))); + EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("127.0.0.1", 80))); + EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("0.0.0.0", 80))); + EXPECT_TRUE(IsPrivateHost(&resolver, HostPortPair("::1", 80))); + EXPECT_FALSE(IsPrivateHost(&resolver, HostPortPair("google.com", 80))); } } // namespace
diff --git a/net/nqe/throughput_analyzer.cc b/net/nqe/throughput_analyzer.cc index 2c4d1b8..96880ed 100644 --- a/net/nqe/throughput_analyzer.cc +++ b/net/nqe/throughput_analyzer.cc
@@ -263,8 +263,7 @@ bool private_network_request = nqe::internal::IsPrivateHost( request.context()->host_resolver(), - HostPortPair(request.url().host(), request.url().EffectiveIntPort()), - net_log_); + HostPortPair(request.url().host(), request.url().EffectiveIntPort())); return !(use_localhost_requests_for_tests_ || !private_network_request) || request.creation_time() < last_connection_change_;
diff --git a/net/nqe/throughput_analyzer_unittest.cc b/net/nqe/throughput_analyzer_unittest.cc index ca7091f..d3011cd 100644 --- a/net/nqe/throughput_analyzer_unittest.cc +++ b/net/nqe/throughput_analyzer_unittest.cc
@@ -119,11 +119,11 @@ ? "http://127.0.0.1/test.html" : "http://example.com/test.html"; - EXPECT_EQ(test.use_local_requests, - nqe::internal::IsPrivateHost( - context.host_resolver(), - HostPortPair(GURL(url).host(), GURL(url).EffectiveIntPort()), - base::MakeUnique<BoundTestNetLog>()->bound())); + EXPECT_EQ( + test.use_local_requests, + nqe::internal::IsPrivateHost( + context.host_resolver(), + HostPortPair(GURL(url).host(), GURL(url).EffectiveIntPort()))); for (size_t i = 0; i < 1000; ++i) { std::unique_ptr<URLRequest> request( context.CreateRequest(GURL(url), DEFAULT_PRIORITY, &test_delegate,
diff --git a/net/quic/chromium/quic_network_transaction_unittest.cc b/net/quic/chromium/quic_network_transaction_unittest.cc index f371dc1b..2d62f45e 100644 --- a/net/quic/chromium/quic_network_transaction_unittest.cc +++ b/net/quic/chromium/quic_network_transaction_unittest.cc
@@ -1190,6 +1190,100 @@ SendRequestAndExpectQuicResponse("hello!"); } +TEST_P(QuicNetworkTransactionTest, DoNotUseQuicForUnsupportedVersion) { + QuicVersion unsupported_version = QUIC_VERSION_UNSUPPORTED; + // Add support for another QUIC version besides |version_|. Also find a + // unsupported version. + for (const QuicVersion& version : AllSupportedVersions()) { + if (version == version_) + continue; + if (supported_versions_.size() != 2) { + supported_versions_.push_back(version); + continue; + } + unsupported_version = version; + break; + } + DCHECK_NE(unsupported_version, QUIC_VERSION_UNSUPPORTED); + + // Set up alternative service to use QUIC with a version that is not + // supported. + url::SchemeHostPort server(request_.url); + AlternativeService alternative_service(kProtoQUIC, kDefaultServerHostName, + 443); + base::Time expiration = base::Time::Now() + base::TimeDelta::FromDays(1); + http_server_properties_.SetQuicAlternativeService( + server, alternative_service, expiration, {unsupported_version}); + + AlternativeServiceInfoVector alt_svc_info_vector = + http_server_properties_.GetAlternativeServiceInfos(server); + EXPECT_EQ(1u, alt_svc_info_vector.size()); + EXPECT_EQ(kProtoQUIC, alt_svc_info_vector[0].alternative_service().protocol); + EXPECT_EQ(1u, alt_svc_info_vector[0].advertised_versions().size()); + EXPECT_EQ(unsupported_version, + alt_svc_info_vector[0].advertised_versions()[0]); + + // First request should still be sent via TCP as the QUIC version advertised + // in the stored AlternativeService is not supported by the client. However, + // the response from the server will advertise new Alt-Svc with supported + // versions. + std::string advertised_versions_list_str = + GenerateQuicVersionsListForAltSvcHeader(AllSupportedVersions()); + std::string altsvc_header = + base::StringPrintf("Alt-Svc: quic=\":443\"; v=\"%s\"\r\n\r\n", + advertised_versions_list_str.c_str()); + MockRead http_reads[] = { + MockRead("HTTP/1.1 200 OK\r\n"), MockRead(altsvc_header.c_str()), + MockRead("hello world"), + MockRead(SYNCHRONOUS, ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ), + MockRead(ASYNC, OK)}; + + StaticSocketDataProvider http_data(http_reads, arraysize(http_reads), nullptr, + 0); + socket_factory_.AddSocketDataProvider(&http_data); + socket_factory_.AddSSLSocketDataProvider(&ssl_data_); + + // Second request should be sent via QUIC as a new list of verions supported + // by the client has been advertised by the server. + MockQuicData mock_quic_data; + QuicStreamOffset header_stream_offset = 0; + mock_quic_data.AddWrite( + ConstructInitialSettingsPacket(1, &header_stream_offset)); + mock_quic_data.AddWrite(ConstructClientRequestHeadersPacket( + 2, GetNthClientInitiatedStreamId(0), true, true, + GetRequestHeaders("GET", "https", "/"), &header_stream_offset)); + mock_quic_data.AddRead(ConstructServerResponseHeadersPacket( + 1, GetNthClientInitiatedStreamId(0), false, false, + GetResponseHeaders("200 OK"))); + mock_quic_data.AddRead(ConstructServerDataPacket( + 2, GetNthClientInitiatedStreamId(0), false, true, 0, "hello!")); + mock_quic_data.AddWrite(ConstructClientAckPacket(3, 2, 1, 1)); + mock_quic_data.AddRead(ASYNC, ERR_IO_PENDING); // No more data to read + mock_quic_data.AddRead(ASYNC, 0); // EOF + + mock_quic_data.AddSocketDataToFactory(&socket_factory_); + + AddHangingNonAlternateProtocolSocketData(); + + CreateSession(supported_versions_); + + SendRequestAndExpectHttpResponse("hello world"); + SendRequestAndExpectQuicResponse("hello!"); + + // Check alternative service list is updated with new versions. + alt_svc_info_vector = + session_->http_server_properties()->GetAlternativeServiceInfos(server); + EXPECT_EQ(1u, alt_svc_info_vector.size()); + EXPECT_EQ(kProtoQUIC, alt_svc_info_vector[0].alternative_service().protocol); + EXPECT_EQ(2u, alt_svc_info_vector[0].advertised_versions().size()); + // Advertised versions will be lised in a sorted order. + std::sort(supported_versions_.begin(), supported_versions_.end()); + EXPECT_EQ(supported_versions_[0], + alt_svc_info_vector[0].advertised_versions()[0]); + EXPECT_EQ(supported_versions_[1], + alt_svc_info_vector[0].advertised_versions()[1]); +} + // Regression test for https://crbug.com/546991. // The server might not be able to serve a request on an alternative connection, // and might send a 421 Misdirected Request response status to indicate this.
diff --git a/net/quic/core/congestion_control/bbr_sender_test.cc b/net/quic/core/congestion_control/bbr_sender_test.cc index 68b37d9..dc91c20 100644 --- a/net/quic/core/congestion_control/bbr_sender_test.cc +++ b/net/quic/core/congestion_control/bbr_sender_test.cc
@@ -314,7 +314,6 @@ sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. - EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); @@ -378,11 +377,10 @@ sender_->ExportDebugState().max_bandwidth); // TODO(ianswett): Expect 0 packets are lost once BBR no longer measures // bandwidth higher than the link rate. - EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); // The margin here is high, because the aggregation greatly increases // smoothed rtt. EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); - ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.12f); + ExpectApproxEq(kTestRtt, rtt_stats_->min_rtt(), 0.33f); } // Test a simple long data transfer with 2 rtts of aggregation.
diff --git a/net/quic/core/spdy_utils_test.cc b/net/quic/core/spdy_utils_test.cc index 6acfc83..fa08193 100644 --- a/net/quic/core/spdy_utils_test.cc +++ b/net/quic/core/spdy_utils_test.cc
@@ -9,6 +9,7 @@ #include "net/quic/platform/api/quic_flag_utils.h" #include "net/quic/platform/api/quic_flags.h" #include "net/quic/platform/api/quic_string_piece.h" +#include "net/quic/platform/api/quic_test.h" #include "net/quic/platform/api/quic_text_utils.h" #include "net/test/gtest_util.h" @@ -30,7 +31,9 @@ return headers; } -TEST(CopyAndValidateHeaders, NormalUsage) { +using CopyAndValidateHeaders = QuicTest; + +TEST_F(CopyAndValidateHeaders, NormalUsage) { auto headers = FromList({// All cookie crumbs are joined. {"cookie", " part 1"}, {"cookie", "part 2 "}, @@ -69,7 +72,7 @@ EXPECT_EQ(-1, content_length); } -TEST(CopyAndValidateHeaders, EmptyName) { +TEST_F(CopyAndValidateHeaders, EmptyName) { auto headers = FromList({{"foo", "foovalue"}, {"", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; SpdyHeaderBlock block; @@ -77,7 +80,7 @@ SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } -TEST(CopyAndValidateHeaders, UpperCaseName) { +TEST_F(CopyAndValidateHeaders, UpperCaseName) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"bAz", ""}}); int64_t content_length = -1; @@ -86,7 +89,7 @@ SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } -TEST(CopyAndValidateHeaders, MultipleContentLengths) { +TEST_F(CopyAndValidateHeaders, MultipleContentLengths) { auto headers = FromList({{"content-length", "9"}, {"foo", "foovalue"}, {"content-length", "9"}, @@ -106,7 +109,7 @@ EXPECT_EQ(9, content_length); } -TEST(CopyAndValidateHeaders, InconsistentContentLengths) { +TEST_F(CopyAndValidateHeaders, InconsistentContentLengths) { auto headers = FromList({{"content-length", "9"}, {"foo", "foovalue"}, {"content-length", "8"}, @@ -118,7 +121,7 @@ SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } -TEST(CopyAndValidateHeaders, LargeContentLength) { +TEST_F(CopyAndValidateHeaders, LargeContentLength) { auto headers = FromList({{"content-length", "9000000000"}, {"foo", "foovalue"}, {"bar", "barvalue"}, @@ -134,7 +137,7 @@ EXPECT_EQ(9000000000, content_length); } -TEST(CopyAndValidateHeaders, MultipleValues) { +TEST_F(CopyAndValidateHeaders, MultipleValues) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"baz", ""}, @@ -151,7 +154,7 @@ EXPECT_EQ(-1, content_length); } -TEST(CopyAndValidateHeaders, MoreThanTwoValues) { +TEST_F(CopyAndValidateHeaders, MoreThanTwoValues) { auto headers = FromList({{"set-cookie", "value1"}, {"set-cookie", "value2"}, {"set-cookie", "value3"}}); @@ -165,7 +168,7 @@ EXPECT_EQ(-1, content_length); } -TEST(CopyAndValidateHeaders, Cookie) { +TEST_F(CopyAndValidateHeaders, Cookie) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"cookie", "value1"}, @@ -180,7 +183,7 @@ EXPECT_EQ(-1, content_length); } -TEST(CopyAndValidateHeaders, MultipleCookies) { +TEST_F(CopyAndValidateHeaders, MultipleCookies) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"cookie", "value1"}, @@ -196,7 +199,9 @@ EXPECT_EQ(-1, content_length); } -TEST(CopyAndValidateTrailers, SimplestValidList) { +using CopyAndValidateTrailers = QuicTest; + +TEST_F(CopyAndValidateTrailers, SimplestValidList) { // Verify that the simplest trailers are valid: just a final byte offset that // gets parsed successfully. auto trailers = FromList({{kFinalOffsetHeaderKey, "1234"}}); @@ -207,7 +212,7 @@ EXPECT_EQ(1234u, final_byte_offset); } -TEST(CopyAndValidateTrailers, EmptyTrailerList) { +TEST_F(CopyAndValidateTrailers, EmptyTrailerList) { // An empty trailer list will fail as required key kFinalOffsetHeaderKey is // not present. QuicHeaderList trailers; @@ -217,7 +222,7 @@ SpdyUtils::CopyAndValidateTrailers(trailers, &final_byte_offset, &block)); } -TEST(CopyAndValidateTrailers, FinalByteOffsetNotPresent) { +TEST_F(CopyAndValidateTrailers, FinalByteOffsetNotPresent) { // Validation fails if required kFinalOffsetHeaderKey is not present, even if // the rest of the header block is valid. auto trailers = FromList({{"key", "value"}}); @@ -227,7 +232,7 @@ &block)); } -TEST(CopyAndValidateTrailers, EmptyName) { +TEST_F(CopyAndValidateTrailers, EmptyName) { // Trailer validation will fail with an empty header key, in an otherwise // valid block of trailers. auto trailers = FromList({{"", "value"}, {kFinalOffsetHeaderKey, "1234"}}); @@ -237,7 +242,7 @@ &block)); } -TEST(CopyAndValidateTrailers, PseudoHeaderInTrailers) { +TEST_F(CopyAndValidateTrailers, PseudoHeaderInTrailers) { // Pseudo headers are illegal in trailers. auto trailers = FromList({{":pseudo_key", "value"}, {kFinalOffsetHeaderKey, "1234"}}); @@ -247,7 +252,7 @@ &block)); } -TEST(CopyAndValidateTrailers, DuplicateTrailers) { +TEST_F(CopyAndValidateTrailers, DuplicateTrailers) { // Duplicate trailers are allowed, and their values are concatenated into a // single string delimted with '\0'. Some of the duplicate headers // deliberately have an empty value. @@ -275,7 +280,7 @@ Pair("other_key", "value"))); } -TEST(CopyAndValidateTrailers, DuplicateCookies) { +TEST_F(CopyAndValidateTrailers, DuplicateCookies) { // Duplicate cookie headers in trailers should be concatenated into a single // "; " delimted string. FLAGS_quic_reloadable_flag_quic_handle_duplicate_trailers = true; @@ -297,7 +302,9 @@ Pair("key", "value"))); } -TEST(GetUrlFromHeaderBlock, Basic) { +using GetUrlFromHeaderBlock = QuicTest; + +TEST_F(GetUrlFromHeaderBlock, Basic) { SpdyHeaderBlock headers; EXPECT_EQ(SpdyUtils::GetUrlFromHeaderBlock(headers), ""); headers[":scheme"] = "https"; @@ -313,7 +320,9 @@ "https://www.google.com/index.html"); } -TEST(GetHostNameFromHeaderBlock, NormalUsage) { +using GetHostNameFromHeaderBlock = QuicTest; + +TEST_F(GetHostNameFromHeaderBlock, NormalUsage) { SpdyHeaderBlock headers; EXPECT_EQ(SpdyUtils::GetHostNameFromHeaderBlock(headers), ""); headers[":scheme"] = "https"; @@ -333,7 +342,9 @@ EXPECT_EQ(SpdyUtils::GetHostNameFromHeaderBlock(headers), "192.168.1.1"); } -TEST(PopulateHeaderBlockFromUrl, NormalUsage) { +using PopulateHeaderBlockFromUrl = QuicTest; + +TEST_F(PopulateHeaderBlockFromUrl, NormalUsage) { string url = "https://www.google.com/index.html"; SpdyHeaderBlock headers; EXPECT_TRUE(SpdyUtils::PopulateHeaderBlockFromUrl(url, &headers)); @@ -342,7 +353,7 @@ EXPECT_EQ("/index.html", headers[":path"].as_string()); } -TEST(PopulateHeaderBlockFromUrl, UrlWithNoPath) { +TEST_F(PopulateHeaderBlockFromUrl, UrlWithNoPath) { string url = "https://www.google.com"; SpdyHeaderBlock headers; EXPECT_TRUE(SpdyUtils::PopulateHeaderBlockFromUrl(url, &headers)); @@ -351,7 +362,7 @@ EXPECT_EQ("/", headers[":path"].as_string()); } -TEST(PopulateHeaderBlockFromUrl, Failure) { +TEST_F(PopulateHeaderBlockFromUrl, Failure) { SpdyHeaderBlock headers; EXPECT_FALSE(SpdyUtils::PopulateHeaderBlockFromUrl("/", &headers)); EXPECT_FALSE(SpdyUtils::PopulateHeaderBlockFromUrl("/index.html", &headers));
diff --git a/net/reporting/reporting_browsing_data_remover.cc b/net/reporting/reporting_browsing_data_remover.cc index d92a78e..5983fe6 100644 --- a/net/reporting/reporting_browsing_data_remover.cc +++ b/net/reporting/reporting_browsing_data_remover.cc
@@ -23,8 +23,10 @@ bool remove_clients = (data_type_mask & DATA_TYPE_CLIENTS) != 0; if (origin_filter.is_null()) { - if (remove_reports) - cache->RemoveAllReports(); + if (remove_reports) { + cache->RemoveAllReports( + ReportingReport::Outcome::ERASED_BROWSING_DATA_REMOVED); + } if (remove_clients) cache->RemoveAllClients(); return; @@ -40,7 +42,9 @@ reports_to_remove.push_back(report); } - cache->RemoveReports(reports_to_remove); + cache->RemoveReports( + reports_to_remove, + ReportingReport::Outcome::ERASED_BROWSING_DATA_REMOVED); } if (remove_clients) {
diff --git a/net/reporting/reporting_cache.cc b/net/reporting/reporting_cache.cc index fe682f2..87c270d6 100644 --- a/net/reporting/reporting_cache.cc +++ b/net/reporting/reporting_cache.cc
@@ -50,7 +50,20 @@ DCHECK(context_); } - ~ReportingCacheImpl() override {} + ~ReportingCacheImpl() override { + base::TimeTicks now = tick_clock()->NowTicks(); + + // Mark all undoomed reports as erased at shutdown, and record outcomes of + // all remaining reports (doomed or not). + for (auto it = reports_.begin(); it != reports_.end(); ++it) { + ReportingReport* report = it->second.get(); + if (!base::ContainsKey(doomed_reports_, report)) + report->outcome = ReportingReport::Outcome::ERASED_REPORTING_SHUT_DOWN; + report->RecordOutcome(now); + } + + reports_.clear(); + } void AddReport(const GURL& url, const std::string& group, @@ -73,8 +86,8 @@ // The newly-added report isn't pending, so even if all other reports are // pending, the cache should have a report to evict. DCHECK(!base::ContainsKey(pending_reports_, to_evict)); - size_t erased = reports_.erase(to_evict); - DCHECK_EQ(1u, erased); + reports_[to_evict]->outcome = ReportingReport::Outcome::ERASED_EVICTED; + RemoveReportInternal(to_evict); } context_->NotifyCacheUpdated(); @@ -110,7 +123,8 @@ } } - RemoveReports(reports_to_remove); + for (const ReportingReport* report : reports_to_remove) + RemoveReportInternal(report); } void IncrementReportsAttempts( @@ -123,35 +137,34 @@ context_->NotifyCacheUpdated(); } - void RemoveReports( - const std::vector<const ReportingReport*>& reports) override { + void RemoveReports(const std::vector<const ReportingReport*>& reports, + ReportingReport::Outcome outcome) override { for (const ReportingReport* report : reports) { + reports_[report]->outcome = outcome; if (base::ContainsKey(pending_reports_, report)) { doomed_reports_.insert(report); } else { DCHECK(!base::ContainsKey(doomed_reports_, report)); - size_t erased = reports_.erase(report); - DCHECK_EQ(1u, erased); + RemoveReportInternal(report); } } context_->NotifyCacheUpdated(); } - void RemoveAllReports() override { - std::vector<std::unordered_map<const ReportingReport*, - std::unique_ptr<ReportingReport>>::iterator> - reports_to_remove; + void RemoveAllReports(ReportingReport::Outcome outcome) override { + std::vector<const ReportingReport*> reports_to_remove; for (auto it = reports_.begin(); it != reports_.end(); ++it) { ReportingReport* report = it->second.get(); + report->outcome = outcome; if (!base::ContainsKey(pending_reports_, report)) - reports_to_remove.push_back(it); + reports_to_remove.push_back(report); else doomed_reports_.insert(report); } - for (auto& it : reports_to_remove) - reports_.erase(it); + for (const ReportingReport* report : reports_to_remove) + RemoveReportInternal(report); context_->NotifyCacheUpdated(); } @@ -314,6 +327,12 @@ base::TickClock* tick_clock() { return context_->tick_clock(); } + void RemoveReportInternal(const ReportingReport* report) { + reports_[report]->RecordOutcome(tick_clock()->NowTicks()); + size_t erased = reports_.erase(report); + DCHECK_EQ(1u, erased); + } + const ReportingReport* FindReportToEvict() const { const ReportingReport* earliest_queued = nullptr;
diff --git a/net/reporting/reporting_cache.h b/net/reporting/reporting_cache.h index 5664495..2cd4bb7 100644 --- a/net/reporting/reporting_cache.h +++ b/net/reporting/reporting_cache.h
@@ -14,13 +14,13 @@ #include "base/values.h" #include "net/base/net_export.h" #include "net/reporting/reporting_client.h" +#include "net/reporting/reporting_report.h" #include "url/gurl.h" #include "url/origin.h" namespace net { class ReportingContext; -struct ReportingReport; // The cache holds undelivered reports and clients (per-origin endpoint // configurations) in memory. (It is not responsible for persisting them.) @@ -76,12 +76,12 @@ // Removes a set of reports. Any reports that are pending will not be removed // immediately, but rather marked doomed and removed once they are no longer // pending. - virtual void RemoveReports( - const std::vector<const ReportingReport*>& reports) = 0; + virtual void RemoveReports(const std::vector<const ReportingReport*>& reports, + ReportingReport::Outcome outcome) = 0; // Removes all reports. Like |RemoveReports()|, pending reports are doomed // until no longer pending. - virtual void RemoveAllReports() = 0; + virtual void RemoveAllReports(ReportingReport::Outcome outcome) = 0; // Creates or updates a client for a particular origin and a particular // endpoint.
diff --git a/net/reporting/reporting_cache_unittest.cc b/net/reporting/reporting_cache_unittest.cc index eb2e158..d1924ff 100644 --- a/net/reporting/reporting_cache_unittest.cc +++ b/net/reporting/reporting_cache_unittest.cc
@@ -108,7 +108,7 @@ ASSERT_TRUE(report); EXPECT_EQ(1, report->attempts); - cache()->RemoveReports(reports); + cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN); EXPECT_EQ(3, observer()->cache_update_count()); cache()->GetReports(&reports); @@ -126,7 +126,7 @@ cache()->GetReports(&reports); EXPECT_EQ(2u, reports.size()); - cache()->RemoveAllReports(); + cache()->RemoveAllReports(ReportingReport::Outcome::UNKNOWN); EXPECT_EQ(3, observer()->cache_update_count()); cache()->GetReports(&reports); @@ -148,7 +148,7 @@ EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0])); EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0])); - cache()->RemoveReports(reports); + cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN); EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0])); EXPECT_TRUE(cache()->IsReportDoomedForTesting(reports[0])); EXPECT_EQ(2, observer()->cache_update_count()); @@ -179,7 +179,7 @@ EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0])); EXPECT_FALSE(cache()->IsReportDoomedForTesting(reports[0])); - cache()->RemoveAllReports(); + cache()->RemoveAllReports(ReportingReport::Outcome::UNKNOWN); EXPECT_TRUE(cache()->IsReportPendingForTesting(reports[0])); EXPECT_TRUE(cache()->IsReportDoomedForTesting(reports[0])); EXPECT_EQ(2, observer()->cache_update_count());
diff --git a/net/reporting/reporting_delivery_agent.cc b/net/reporting/reporting_delivery_agent.cc index fb12d03..38d601c 100644 --- a/net/reporting/reporting_delivery_agent.cc +++ b/net/reporting/reporting_delivery_agent.cc
@@ -170,7 +170,8 @@ void OnUploadComplete(const std::unique_ptr<Delivery>& delivery, ReportingUploader::Outcome outcome) { if (outcome == ReportingUploader::Outcome::SUCCESS) { - cache()->RemoveReports(delivery->reports); + cache()->RemoveReports(delivery->reports, + ReportingReport::Outcome::DELIVERED); endpoint_manager()->InformOfEndpointRequest(delivery->endpoint, true); } else { cache()->IncrementReportsAttempts(delivery->reports);
diff --git a/net/reporting/reporting_delivery_agent_unittest.cc b/net/reporting/reporting_delivery_agent_unittest.cc index c108c78..f1a575a 100644 --- a/net/reporting/reporting_delivery_agent_unittest.cc +++ b/net/reporting/reporting_delivery_agent_unittest.cc
@@ -178,7 +178,7 @@ EXPECT_FALSE(cache()->IsReportDoomedForTesting(report)); // Report should appear removed, even though the cache has doomed it. - cache()->RemoveReports(reports); + cache()->RemoveReports(reports, ReportingReport::Outcome::UNKNOWN); cache()->GetReports(&reports); EXPECT_TRUE(reports.empty()); EXPECT_TRUE(cache()->IsReportDoomedForTesting(report));
diff --git a/net/reporting/reporting_garbage_collector.cc b/net/reporting/reporting_garbage_collector.cc index 50e6d562..188cda1 100644 --- a/net/reporting/reporting_garbage_collector.cc +++ b/net/reporting/reporting_garbage_collector.cc
@@ -57,17 +57,21 @@ std::vector<const ReportingReport*> all_reports; context_->cache()->GetReports(&all_reports); - std::vector<const ReportingReport*> reports_to_remove; + std::vector<const ReportingReport*> failed_reports; + std::vector<const ReportingReport*> expired_reports; for (const ReportingReport* report : all_reports) { - if (now - report->queued >= policy.max_report_age || - report->attempts >= policy.max_report_attempts) { - reports_to_remove.push_back(report); - } + if (report->attempts >= policy.max_report_attempts) + failed_reports.push_back(report); + else if (now - report->queued >= policy.max_report_age) + expired_reports.push_back(report); } // Don't restart the timer on the garbage collector's own updates. context_->RemoveObserver(this); - context_->cache()->RemoveReports(reports_to_remove); + context_->cache()->RemoveReports(failed_reports, + ReportingReport::Outcome::ERASED_FAILED); + context_->cache()->RemoveReports(expired_reports, + ReportingReport::Outcome::ERASED_EXPIRED); context_->AddObserver(this); }
diff --git a/net/reporting/reporting_header_parser.cc b/net/reporting/reporting_header_parser.cc index 8a0c7b2..058b335 100644 --- a/net/reporting/reporting_header_parser.cc +++ b/net/reporting/reporting_header_parser.cc
@@ -8,6 +8,7 @@ #include "base/json/json_reader.h" #include "base/logging.h" +#include "base/metrics/histogram_macros.h" #include "base/time/tick_clock.h" #include "base/time/time.h" #include "base/values.h" @@ -19,39 +20,82 @@ namespace { +enum class HeaderOutcome { + DISCARDED_NO_REPORTING_SERVICE = 0, + DISCARDED_INVALID_SSL_INFO = 1, + DISCARDED_CERT_STATUS_ERROR = 2, + DISCARDED_INVALID_JSON = 3, + PARSED = 4, + + MAX +}; + +void RecordHeaderOutcome(HeaderOutcome outcome) { + UMA_HISTOGRAM_ENUMERATION("Reporting.HeaderOutcome", outcome, + HeaderOutcome::MAX); +} + +enum class HeaderEndpointOutcome { + DISCARDED_NOT_DICTIONARY = 0, + DISCARDED_ENDPOINT_MISSING = 1, + DISCARDED_ENDPOINT_NOT_STRING = 2, + DISCARDED_ENDPOINT_INVALID = 3, + DISCARDED_ENDPOINT_INSECURE = 4, + DISCARDED_TTL_MISSING = 5, + DISCARDED_TTL_NOT_INTEGER = 6, + DISCARDED_TTL_NEGATIVE = 7, + DISCARDED_GROUP_NOT_STRING = 8, + REMOVED = 9, + SET_REJECTED_BY_DELEGATE = 10, + SET = 11, + + MAX +}; + +void RecordHeaderEndpointOutcome(HeaderEndpointOutcome outcome) { + UMA_HISTOGRAM_ENUMERATION("Reporting.HeaderEndpointOutcome", outcome, + HeaderEndpointOutcome::MAX); +} + const char kUrlKey[] = "url"; const char kIncludeSubdomainsKey[] = "includeSubdomains"; const char kGroupKey[] = "group"; const char kGroupDefaultValue[] = "default"; const char kMaxAgeKey[] = "max-age"; -void ProcessEndpoint(ReportingDelegate* delegate, - ReportingCache* cache, - base::TimeTicks now, - const GURL& url, - const base::Value& value) { +HeaderEndpointOutcome ProcessEndpoint(ReportingDelegate* delegate, + ReportingCache* cache, + base::TimeTicks now, + const GURL& url, + const base::Value& value) { const base::DictionaryValue* dict = nullptr; if (!value.GetAsDictionary(&dict)) - return; + return HeaderEndpointOutcome::DISCARDED_NOT_DICTIONARY; DCHECK(dict); std::string endpoint_url_string; + if (!dict->HasKey(kUrlKey)) + return HeaderEndpointOutcome::DISCARDED_ENDPOINT_MISSING; if (!dict->GetString(kUrlKey, &endpoint_url_string)) - return; + return HeaderEndpointOutcome::DISCARDED_ENDPOINT_NOT_STRING; GURL endpoint_url(endpoint_url_string); if (!endpoint_url.is_valid()) - return; + return HeaderEndpointOutcome::DISCARDED_ENDPOINT_INVALID; if (!endpoint_url.SchemeIsCryptographic()) - return; + return HeaderEndpointOutcome::DISCARDED_ENDPOINT_INSECURE; int ttl_sec = -1; - if (!dict->GetInteger(kMaxAgeKey, &ttl_sec) || ttl_sec < 0) - return; + if (!dict->HasKey(kMaxAgeKey)) + return HeaderEndpointOutcome::DISCARDED_TTL_MISSING; + if (!dict->GetInteger(kMaxAgeKey, &ttl_sec)) + return HeaderEndpointOutcome::DISCARDED_TTL_NOT_INTEGER; + if (ttl_sec < 0) + return HeaderEndpointOutcome::DISCARDED_TTL_NEGATIVE; std::string group = kGroupDefaultValue; if (dict->HasKey(kGroupKey) && !dict->GetString(kGroupKey, &group)) - return; + return HeaderEndpointOutcome::DISCARDED_GROUP_NOT_STRING; ReportingClient::Subdomains subdomains = ReportingClient::Subdomains::EXCLUDE; bool subdomains_bool = false; @@ -61,22 +105,38 @@ subdomains = ReportingClient::Subdomains::INCLUDE; } - url::Origin origin(url); - - if (!delegate->CanSetClient(origin, endpoint_url)) - return; - - if (ttl_sec > 0) { - cache->SetClient(origin, endpoint_url, subdomains, group, - now + base::TimeDelta::FromSeconds(ttl_sec)); - } else { - cache->RemoveClientForOriginAndEndpoint(origin, endpoint_url); + if (ttl_sec == 0) { + cache->RemoveClientForOriginAndEndpoint(url::Origin(url), endpoint_url); + return HeaderEndpointOutcome::REMOVED; } + + url::Origin origin(url); + if (!delegate->CanSetClient(origin, endpoint_url)) + return HeaderEndpointOutcome::SET_REJECTED_BY_DELEGATE; + + cache->SetClient(origin, endpoint_url, subdomains, group, + now + base::TimeDelta::FromSeconds(ttl_sec)); + return HeaderEndpointOutcome::SET; } } // namespace // static +void ReportingHeaderParser::RecordHeaderDiscardedForNoReportingService() { + RecordHeaderOutcome(HeaderOutcome::DISCARDED_NO_REPORTING_SERVICE); +} + +// static +void ReportingHeaderParser::RecordHeaderDiscardedForInvalidSSLInfo() { + RecordHeaderOutcome(HeaderOutcome::DISCARDED_INVALID_SSL_INFO); +} + +// static +void ReportingHeaderParser::RecordHeaderDiscardedForCertStatusError() { + RecordHeaderOutcome(HeaderOutcome::DISCARDED_CERT_STATUS_ERROR); +} + +// static void ReportingHeaderParser::ParseHeader(ReportingContext* context, const GURL& url, const std::string& json_value) { @@ -84,8 +144,10 @@ std::unique_ptr<base::Value> value = base::JSONReader::Read("[" + json_value + "]"); - if (!value) + if (!value) { + RecordHeaderOutcome(HeaderOutcome::DISCARDED_INVALID_JSON); return; + } const base::ListValue* list = nullptr; bool is_list = value->GetAsList(&list); @@ -98,7 +160,8 @@ const base::Value* endpoint = nullptr; bool got_endpoint = list->Get(i, &endpoint); DCHECK(got_endpoint); - ProcessEndpoint(delegate, cache, now, url, *endpoint); + RecordHeaderEndpointOutcome( + ProcessEndpoint(delegate, cache, now, url, *endpoint)); } }
diff --git a/net/reporting/reporting_header_parser.h b/net/reporting/reporting_header_parser.h index fc165f3..c94f053 100644 --- a/net/reporting/reporting_header_parser.h +++ b/net/reporting/reporting_header_parser.h
@@ -18,6 +18,10 @@ class NET_EXPORT ReportingHeaderParser { public: + static void RecordHeaderDiscardedForNoReportingService(); + static void RecordHeaderDiscardedForInvalidSSLInfo(); + static void RecordHeaderDiscardedForCertStatusError(); + static void ParseHeader(ReportingContext* context, const GURL& url, const std::string& json_value);
diff --git a/net/reporting/reporting_network_change_observer.cc b/net/reporting/reporting_network_change_observer.cc index 6c62b7f..99bb5a6 100644 --- a/net/reporting/reporting_network_change_observer.cc +++ b/net/reporting/reporting_network_change_observer.cc
@@ -9,6 +9,7 @@ #include "net/reporting/reporting_cache.h" #include "net/reporting/reporting_context.h" #include "net/reporting/reporting_policy.h" +#include "net/reporting/reporting_report.h" namespace net { @@ -38,7 +39,8 @@ return; if (context_->policy().clear_reports_on_network_changes) - context_->cache()->RemoveAllReports(); + context_->cache()->RemoveAllReports( + ReportingReport::Outcome::ERASED_NETWORK_CHANGED); if (context_->policy().clear_clients_on_network_changes) context_->cache()->RemoveAllClients();
diff --git a/net/reporting/reporting_report.cc b/net/reporting/reporting_report.cc index b039bc1c..37c4a22 100644 --- a/net/reporting/reporting_report.cc +++ b/net/reporting/reporting_report.cc
@@ -8,12 +8,22 @@ #include <string> #include <utility> +#include "base/metrics/histogram_macros.h" #include "base/time/time.h" #include "base/values.h" #include "url/gurl.h" namespace net { +namespace { + +void RecordReportOutcome(ReportingReport::Outcome outcome) { + UMA_HISTOGRAM_ENUMERATION("Reporting.ReportOutcome", outcome, + ReportingReport::Outcome::MAX); +} + +} // namespace + ReportingReport::ReportingReport(const GURL& url, const std::string& group, const std::string& type, @@ -25,8 +35,36 @@ type(type), body(std::move(body)), queued(queued), - attempts(attempts) {} + attempts(attempts), + outcome(Outcome::UNKNOWN), + recorded_outcome(false) {} -ReportingReport::~ReportingReport() {} +ReportingReport::~ReportingReport() { + DCHECK(recorded_outcome); +} + +// static +void ReportingReport::RecordReportDiscardedForNoURLRequestContext() { + RecordReportOutcome(Outcome::DISCARDED_NO_URL_REQUEST_CONTEXT); +} + +// static +void ReportingReport::RecordReportDiscardedForNoReportingService() { + RecordReportOutcome(Outcome::DISCARDED_NO_REPORTING_SERVICE); +} + +void ReportingReport::RecordOutcome(base::TimeTicks now) { + DCHECK(!recorded_outcome); + + RecordReportOutcome(outcome); + + if (outcome == Outcome::DELIVERED) { + UMA_HISTOGRAM_LONG_TIMES_100("Reporting.ReportDeliveredLatency", + now - queued); + UMA_HISTOGRAM_COUNTS_100("Reporting.ReportDeliveredAttempts", attempts); + } + + recorded_outcome = true; +} } // namespace net
diff --git a/net/reporting/reporting_report.h b/net/reporting/reporting_report.h index b1b3101..e7fba5d 100644 --- a/net/reporting/reporting_report.h +++ b/net/reporting/reporting_report.h
@@ -21,6 +21,22 @@ // An undelivered report. struct NET_EXPORT ReportingReport { public: + // Used in histograms; please add new items at end and do not reorder. + enum class Outcome { + UNKNOWN = 0, + DISCARDED_NO_URL_REQUEST_CONTEXT = 1, + DISCARDED_NO_REPORTING_SERVICE = 2, + ERASED_FAILED = 3, + ERASED_EXPIRED = 4, + ERASED_EVICTED = 5, + ERASED_NETWORK_CHANGED = 6, + ERASED_BROWSING_DATA_REMOVED = 7, + ERASED_REPORTING_SHUT_DOWN = 8, + DELIVERED = 9, + + MAX + }; + ReportingReport(const GURL& url, const std::string& group, const std::string& type, @@ -29,6 +45,11 @@ int attempts); ~ReportingReport(); + static void RecordReportDiscardedForNoURLRequestContext(); + static void RecordReportDiscardedForNoReportingService(); + + void RecordOutcome(base::TimeTicks now); + // The URL of the document that triggered the report. (Included in the // delivered report.) GURL url; @@ -51,7 +72,11 @@ // attempt. (Not included in the delivered report.) int attempts = 0; + Outcome outcome; + private: + bool recorded_outcome; + DISALLOW_COPY_AND_ASSIGN(ReportingReport); };
diff --git a/net/url_request/url_request_http_job.cc b/net/url_request/url_request_http_job.cc index fa28333..32dd01f 100644 --- a/net/url_request/url_request_http_job.cc +++ b/net/url_request/url_request_http_job.cc
@@ -75,6 +75,7 @@ #endif #if BUILDFLAG(ENABLE_REPORTING) +#include "net/reporting/reporting_header_parser.h" #include "net/reporting/reporting_service.h" #endif // BUILDFLAG(ENABLE_REPORTING) @@ -858,21 +859,29 @@ DCHECK(response_info_); #if BUILDFLAG(ENABLE_REPORTING) - ReportingService* service = request_->context()->reporting_service(); - if (!service) + HttpResponseHeaders* headers = GetResponseHeaders(); + std::string value; + if (!headers->GetNormalizedHeader("Report-To", &value)) return; + ReportingService* service = request_->context()->reporting_service(); + if (!service) { + ReportingHeaderParser::RecordHeaderDiscardedForNoReportingService(); + return; + } + // Only accept Report-To headers on HTTPS connections that have no // certificate errors. // TODO(juliatuttle): Do we need to check cert status? const SSLInfo& ssl_info = response_info_->ssl_info; - if (!ssl_info.is_valid() || IsCertStatusError(ssl_info.cert_status)) + if (!ssl_info.is_valid()) { + ReportingHeaderParser::RecordHeaderDiscardedForInvalidSSLInfo(); return; - - HttpResponseHeaders* headers = GetResponseHeaders(); - std::string value; - if (!headers->GetNormalizedHeader("Report-To", &value)) + } + if (IsCertStatusError(ssl_info.cert_status)) { + ReportingHeaderParser::RecordHeaderDiscardedForCertStatusError(); return; + } service->ProcessHeader(request_info_.url.GetOrigin(), value); #endif // BUILDFLAG(ENABLE_REPORTING)
diff --git a/remoting/protocol/jingle_session.cc b/remoting/protocol/jingle_session.cc index dc77271..7fdbd42 100644 --- a/remoting/protocol/jingle_session.cc +++ b/remoting/protocol/jingle_session.cc
@@ -115,6 +115,9 @@ const std::string& id, PendingMessage&& pending_message); + // Sets the initial ID of the session initiate message. + void SetInitialId(const std::string& id); + private: // Implements an ordered list by using map with the |sequence_id| as the key, // so that |queue_| is always sorted by |sequence_id|. @@ -162,6 +165,12 @@ return result; }; +void JingleSession::OrderedMessageQueue::SetInitialId(const std::string& id) { + int current = GetSequentialId(id); + if (current != kInvalid) + next_incoming_ = current + 1; +} + JingleSession::PendingMessage::PendingMessage() = default; JingleSession::PendingMessage::PendingMessage(PendingMessage&& moved) = default; JingleSession::PendingMessage::PendingMessage( @@ -224,6 +233,7 @@ } void JingleSession::InitializeIncomingConnection( + const std::string& message_id, const JingleMessage& initiate_message, std::unique_ptr<Authenticator> authenticator) { DCHECK(thread_checker_.CalledOnValidThread()); @@ -234,6 +244,7 @@ peer_address_ = initiate_message.from; authenticator_ = std::move(authenticator); session_id_ = initiate_message.sid; + message_queue_->SetInitialId(message_id); SetState(ACCEPTING);
diff --git a/remoting/protocol/jingle_session.h b/remoting/protocol/jingle_session.h index 3b9c1fe0..9d82496f 100644 --- a/remoting/protocol/jingle_session.h +++ b/remoting/protocol/jingle_session.h
@@ -58,6 +58,7 @@ // Called by JingleSessionManager for incoming connections. void InitializeIncomingConnection( + const std::string& message_id, const JingleMessage& initiate_message, std::unique_ptr<Authenticator> authenticator); void AcceptIncomingConnection(const JingleMessage& initiate_message);
diff --git a/remoting/protocol/jingle_session_manager.cc b/remoting/protocol/jingle_session_manager.cc index 4aabd443..b039ae7d 100644 --- a/remoting/protocol/jingle_session_manager.cc +++ b/remoting/protocol/jingle_session_manager.cc
@@ -87,7 +87,7 @@ signal_strategy_->GetLocalAddress().id(), message->from.id()); JingleSession* session = new JingleSession(this); - session->InitializeIncomingConnection(*message, + session->InitializeIncomingConnection(stanza->Attr(buzz::QN_ID), *message, std::move(authenticator)); sessions_[session->session_id_] = session;
diff --git a/services/BUILD.gn b/services/BUILD.gn index 93cb992..37a9a0d 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn
@@ -122,11 +122,11 @@ "$google_play_services_package:google_play_services_vision_java", "//base:base_java", "//base:base_java_test_support", - "//device/generic_sensor:java", - "//device/generic_sensor/public/interfaces:interfaces_java", "//mojo/public/java:bindings_java", "//mojo/public/java:system_java", + "//services/device/generic_sensor:java", "//services/device/nfc/android:java", + "//services/device/public/interfaces:generic_sensor_java", "//services/device/public/interfaces:interfaces_java", "//services/device/public/java:nfc_java", "//services/shape_detection:shape_detection_java", @@ -139,6 +139,11 @@ testonly = true java_files = [ "shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java" ] deps = [ + "$google_play_services_package:google_play_services_base_java", + "$google_play_services_package:google_play_services_basement_java", + "$google_play_services_package:google_play_services_vision_common_java", + "$google_play_services_package:google_play_services_vision_java", + "//base:base_java", "//base:base_java_test_support", "//mojo/public/java:bindings_java", "//services/shape_detection:shape_detection_java",
diff --git a/services/device/BUILD.gn b/services/device/BUILD.gn index e656d097..c3c0cd7 100644 --- a/services/device/BUILD.gn +++ b/services/device/BUILD.gn
@@ -25,11 +25,11 @@ deps = [ "//base", - "//device/generic_sensor", "//device/sensors", "//device/sensors/public/interfaces", "//device/wake_lock", "//services/device/fingerprint", + "//services/device/generic_sensor", "//services/device/power_monitor", "//services/device/public/cpp:device_features", "//services/device/public/interfaces", @@ -53,6 +53,8 @@ } } +is_linux_without_udev = is_linux && !use_udev + source_set("tests") { testonly = true @@ -60,6 +62,7 @@ "battery/battery_status_manager_win_unittest.cc", "battery/battery_status_service_unittest.cc", "generic_sensor/generic_sensor_service_unittest.cc", + "generic_sensor/platform_sensor_and_provider_unittest_win.cc", "power_monitor/power_monitor_message_broadcaster_unittest.cc", "public/cpp/power_monitor/power_monitor_broadcast_source_unittest.cc", "vibration/vibration_manager_impl_unittest.cc", @@ -71,9 +74,9 @@ "//base", "//base/test:test_support", "//device/base/synchronization", - "//device/generic_sensor", "//device/wake_lock", "//mojo/public/cpp/bindings", + "//services/device/generic_sensor", "//services/device/power_monitor", "//services/device/public/cpp:device_features", "//services/device/public/cpp/power_monitor", @@ -81,6 +84,11 @@ "//testing/gtest", ] + if (!is_linux_without_udev) { + sources += + [ "generic_sensor/platform_sensor_and_provider_unittest_linux.cc" ] + } + if (is_linux && !is_chromeos && use_dbus) { sources += [ "battery/battery_status_manager_linux_unittest.cc" ] deps += [ "//dbus:test_support" ] @@ -109,6 +117,14 @@ "//services/device/vibration", ] } + + if (is_win) { + # Needed for "generic_sensor/platform_sensor_and_provider_unittest_win.cc" + libs = [ + "propsys.lib", + "sensorsapi.lib", + ] + } } service_manifest("manifest") { @@ -173,6 +189,7 @@ "//mojo/public/java:bindings_java", "//mojo/public/java:system_java", "//services/device/battery/android:battery_monitor_java", + "//services/device/generic_sensor:java", "//services/device/nfc/android:java", "//services/device/public/interfaces:interfaces_java", "//services/device/public/java:nfc_java",
diff --git a/services/device/android/register_jni.cc b/services/device/android/register_jni.cc index 345a8699..041dfdf 100644 --- a/services/device/android/register_jni.cc +++ b/services/device/android/register_jni.cc
@@ -5,6 +5,7 @@ #include "services/device/android/register_jni.h" #include "base/android/jni_android.h" +#include "services/device/generic_sensor/android/sensors_jni_registrar.h" #include "services/device/time_zone_monitor/android/time_zone_monitor_jni_registrar.h" namespace device { @@ -15,6 +16,9 @@ if (!g_jni_init_done) { JNIEnv* env = base::android::AttachCurrentThread(); + if (!android::RegisterSensorsJni(env)) + return false; + if (!android::RegisterTimeZoneMonitorJni(env)) return false;
diff --git a/services/device/device_service.cc b/services/device/device_service.cc index ca19aa5..2e3dd7d 100644 --- a/services/device/device_service.cc +++ b/services/device/device_service.cc
@@ -12,11 +12,11 @@ #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" -#include "device/generic_sensor/sensor_provider_impl.h" #include "device/sensors/device_sensor_host.h" #include "device/wake_lock/wake_lock_provider.h" #include "mojo/public/cpp/system/message_pipe.h" #include "services/device/fingerprint/fingerprint.h" +#include "services/device/generic_sensor/sensor_provider_impl.h" #include "services/device/power_monitor/power_monitor_message_broadcaster.h" #include "services/device/public/cpp/device_features.h" #include "services/device/public/interfaces/battery_monitor.mojom.h"
diff --git a/services/device/device_service.h b/services/device/device_service.h index 69ddb654..5bda46f 100644 --- a/services/device/device_service.h +++ b/services/device/device_service.h
@@ -6,7 +6,6 @@ #define SERVICES_DEVICE_DEVICE_SERVICE_H_ #include "base/memory/ref_counted.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom.h" #include "device/screen_orientation/public/interfaces/screen_orientation.mojom.h" #include "device/sensors/public/interfaces/motion.mojom.h" #include "device/sensors/public/interfaces/orientation.mojom.h" @@ -17,6 +16,7 @@ #include "services/device/public/interfaces/fingerprint.mojom.h" #include "services/device/public/interfaces/nfc_provider.mojom.h" #include "services/device/public/interfaces/power_monitor.mojom.h" +#include "services/device/public/interfaces/sensor_provider.mojom.h" #include "services/device/public/interfaces/time_zone_monitor.mojom.h" #include "services/device/public/interfaces/vibration_manager.mojom.h" #include "services/service_manager/public/cpp/binder_registry.h"
diff --git a/device/generic_sensor/BUILD.gn b/services/device/generic_sensor/BUILD.gn similarity index 89% rename from device/generic_sensor/BUILD.gn rename to services/device/generic_sensor/BUILD.gn index dfebf26..b256e93 100644 --- a/device/generic_sensor/BUILD.gn +++ b/services/device/generic_sensor/BUILD.gn
@@ -8,11 +8,12 @@ import("//build/config/android/rules.gni") # For generate_jni(). } -component("generic_sensor") { +source_set("generic_sensor") { + visibility = [ "//services/device:*" ] + output_name = "generic_sensor" sources = [ "generic_sensor_consts.h", - "generic_sensor_export.h", "linux/sensor_data_linux.cc", "linux/sensor_data_linux.h", "platform_sensor.cc", @@ -47,15 +48,13 @@ "sensor_provider_impl.h", ] - defines = [ "DEVICE_GENERIC_SENSOR_IMPLEMENTATION" ] - deps = [ "//base", "//device/base/synchronization", ] public_deps = [ - "//device/generic_sensor/public/cpp", + "//services/device/public/cpp/generic_sensor", ] if (is_android) { @@ -107,16 +106,22 @@ ] generate_jni("jni_headers") { + visibility = [ ":generic_sensor" ] + sources = device_sensors_jni_sources jni_package = "device" } android_library("java") { - java_files = device_sensors_jni_sources + visibility = [ + "//services:*", + "//services/device:*", + ] + java_files = device_sensors_jni_sources deps = [ "//base:base_java", - "//device/generic_sensor/public/interfaces:interfaces_java", + "//services/device/public/interfaces:generic_sensor_java", ] } }
diff --git a/device/generic_sensor/DEPS b/services/device/generic_sensor/DEPS similarity index 100% rename from device/generic_sensor/DEPS rename to services/device/generic_sensor/DEPS
diff --git a/device/generic_sensor/OWNERS b/services/device/generic_sensor/OWNERS similarity index 100% rename from device/generic_sensor/OWNERS rename to services/device/generic_sensor/OWNERS
diff --git a/device/generic_sensor/README.md b/services/device/generic_sensor/README.md similarity index 94% rename from device/generic_sensor/README.md rename to services/device/generic_sensor/README.md index e1842f9..8e10d13 100644 --- a/device/generic_sensor/README.md +++ b/services/device/generic_sensor/README.md
@@ -1,9 +1,9 @@ # Sensors -`device/generic_sensor` contains the platform-specific parts of the Sensor APIs +`services/device/generic_sensor` contains the platform-specific parts of the Sensor APIs implementation. -Sensors Mojo interfaces are defined in the `public/interfaces` subdirectory. +Sensors Mojo interfaces are defined in the `services/public/interfaces` subdirectory. The JS bindings are implemented in `third_party/WebKit/Source/modules/sensor`.
diff --git a/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java b/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java similarity index 100% rename from device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java rename to services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensor.java
diff --git a/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensorProvider.java b/services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensorProvider.java similarity index 100% rename from device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensorProvider.java rename to services/device/generic_sensor/android/java/src/org/chromium/device/sensors/PlatformSensorProvider.java
diff --git a/device/generic_sensor/android/sensors_jni_registrar.cc b/services/device/generic_sensor/android/sensors_jni_registrar.cc similarity index 82% rename from device/generic_sensor/android/sensors_jni_registrar.cc rename to services/device/generic_sensor/android/sensors_jni_registrar.cc index ca5c8aa..b34e7b8 100644 --- a/device/generic_sensor/android/sensors_jni_registrar.cc +++ b/services/device/generic_sensor/android/sensors_jni_registrar.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 "device/generic_sensor/android/sensors_jni_registrar.h" +#include "services/device/generic_sensor/android/sensors_jni_registrar.h" #include "base/android/jni_android.h" #include "base/android/jni_registrar.h" -#include "device/generic_sensor/platform_sensor_android.h" +#include "services/device/generic_sensor/platform_sensor_android.h" namespace device { namespace android {
diff --git a/device/generic_sensor/android/sensors_jni_registrar.h b/services/device/generic_sensor/android/sensors_jni_registrar.h similarity index 60% rename from device/generic_sensor/android/sensors_jni_registrar.h rename to services/device/generic_sensor/android/sensors_jni_registrar.h index e10738d..c16a9e9 100644 --- a/device/generic_sensor/android/sensors_jni_registrar.h +++ b/services/device/generic_sensor/android/sensors_jni_registrar.h
@@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_ -#define DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_ #include <jni.h> -#include "device/generic_sensor/generic_sensor_export.h" - namespace device { namespace android { @@ -16,9 +14,9 @@ // See https://www.chromium.org/developers/design-documents/android-jni // // Must be called before classes in the Sensors module are used. -bool DEVICE_GENERIC_SENSOR_EXPORT RegisterSensorsJni(JNIEnv* env); +bool RegisterSensorsJni(JNIEnv* env); } // namespace android } // namespace device -#endif // DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_ANDROID_SENSORS_JNI_REGISTRAR_H_
diff --git a/device/generic_sensor/generic_sensor_consts.h b/services/device/generic_sensor/generic_sensor_consts.h similarity index 84% rename from device/generic_sensor/generic_sensor_consts.h rename to services/device/generic_sensor/generic_sensor_consts.h index ca9b45a4..ba4b959 100644 --- a/device/generic_sensor/generic_sensor_consts.h +++ b/services/device/generic_sensor/generic_sensor_consts.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 DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_ -#define DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_ #define _USE_MATH_DEFINES #include <math.h> @@ -36,4 +36,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_GENERIC_SENSOR_CONSTS_H_
diff --git a/services/device/generic_sensor/generic_sensor_service_unittest.cc b/services/device/generic_sensor/generic_sensor_service_unittest.cc index 7d57988c..94b18136 100644 --- a/services/device/generic_sensor/generic_sensor_service_unittest.cc +++ b/services/device/generic_sensor/generic_sensor_service_unittest.cc
@@ -13,13 +13,13 @@ #include "base/threading/platform_thread.h" #include "build/build_config.h" #include "device/base/synchronization/one_writer_seqlock.h" -#include "device/generic_sensor/platform_sensor.h" -#include "device/generic_sensor/platform_sensor_provider.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" -#include "device/generic_sensor/sensor_provider_impl.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/device/device_service_test_base.h" +#include "services/device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/sensor_provider_impl.h" #include "services/device/public/cpp/device_features.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" #include "services/device/public/interfaces/constants.mojom.h" namespace device {
diff --git a/device/generic_sensor/linux/sensor_data_linux.cc b/services/device/generic_sensor/linux/sensor_data_linux.cc similarity index 97% rename from device/generic_sensor/linux/sensor_data_linux.cc rename to services/device/generic_sensor/linux/sensor_data_linux.cc index 8e506a9..84739eb 100644 --- a/device/generic_sensor/linux/sensor_data_linux.cc +++ b/services/device/generic_sensor/linux/sensor_data_linux.cc
@@ -2,11 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "services/device/generic_sensor/linux/sensor_data_linux.h" + #include "base/sys_info.h" #include "base/version.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" namespace device {
diff --git a/device/generic_sensor/linux/sensor_data_linux.h b/services/device/generic_sensor/linux/sensor_data_linux.h similarity index 85% rename from device/generic_sensor/linux/sensor_data_linux.h rename to services/device/generic_sensor/linux/sensor_data_linux.h index 5f82898..3e485b95 100644 --- a/device/generic_sensor/linux/sensor_data_linux.h +++ b/services/device/generic_sensor/linux/sensor_data_linux.h
@@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_ -#define DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_ -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -18,7 +17,7 @@ // SensorDeviceManager receives a udev device, it uses this structure to // identify what type of sensor that is and creates a SensorInfoLinux structure // that holds all the necessary information to create a PlatformSensorLinux. -struct DEVICE_GENERIC_SENSOR_EXPORT SensorPathsLinux { +struct SensorPathsLinux { using ReaderFunctor = base::Callback< void(double scaling, double offset, SensorReading& reading)>; @@ -44,8 +43,7 @@ }; // Initializes sensor data according to |type|. -bool DEVICE_GENERIC_SENSOR_EXPORT InitSensorData(mojom::SensorType type, - SensorPathsLinux* data); +bool InitSensorData(mojom::SensorType type, SensorPathsLinux* data); // This structure represents an iio device, which info is taken // from udev service. If a client requests a sensor from a provider, @@ -79,4 +77,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DATA_LINUX_H_
diff --git a/device/generic_sensor/linux/sensor_device_manager.cc b/services/device/generic_sensor/linux/sensor_device_manager.cc similarity index 97% rename from device/generic_sensor/linux/sensor_device_manager.cc rename to services/device/generic_sensor/linux/sensor_device_manager.cc index fb4ca88d..3771a9a 100644 --- a/device/generic_sensor/linux/sensor_device_manager.cc +++ b/services/device/generic_sensor/linux/sensor_device_manager.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 "device/generic_sensor/linux/sensor_device_manager.h" +#include "services/device/generic_sensor/linux/sensor_device_manager.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" +#include "services/device/generic_sensor/linux/sensor_data_linux.h" namespace device {
diff --git a/device/generic_sensor/linux/sensor_device_manager.h b/services/device/generic_sensor/linux/sensor_device_manager.h similarity index 85% rename from device/generic_sensor/linux/sensor_device_manager.h rename to services/device/generic_sensor/linux/sensor_device_manager.h index 937e8e54..9ac4d39 100644 --- a/device/generic_sensor/linux/sensor_device_manager.h +++ b/services/device/generic_sensor/linux/sensor_device_manager.h
@@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_ -#define DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_ #include "base/scoped_observer.h" - #include "base/single_thread_task_runner.h" #include "device/base/device_monitor_linux.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -20,8 +18,7 @@ // and listen to "add/removed" events to notify |provider_| about // added or removed iio devices. It has own cache to speed up an identification // process of removed devices. -class DEVICE_GENERIC_SENSOR_EXPORT SensorDeviceManager - : public DeviceMonitorLinux::Observer { +class SensorDeviceManager : public DeviceMonitorLinux::Observer { public: class Delegate { public: @@ -83,4 +80,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_LINUX_SENSOR_DEVICE_MANAGER_H_
diff --git a/device/generic_sensor/platform_sensor.cc b/services/device/generic_sensor/platform_sensor.cc similarity index 94% rename from device/generic_sensor/platform_sensor.cc rename to services/device/generic_sensor/platform_sensor.cc index 34afa2d6..cb78c97 100644 --- a/device/generic_sensor/platform_sensor.cc +++ b/services/device/generic_sensor/platform_sensor.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 "device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor.h" #include <utility> #include "base/threading/thread_task_runner_handle.h" -#include "device/generic_sensor/platform_sensor_provider.h" -#include "device/generic_sensor/public/cpp/platform_sensor_configuration.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" +#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor.h b/services/device/generic_sensor/platform_sensor.h similarity index 88% rename from device/generic_sensor/platform_sensor.h rename to services/device/generic_sensor/platform_sensor.h index 94629a5..1e3847e 100644 --- a/device/generic_sensor/platform_sensor.h +++ b/services/device/generic_sensor/platform_sensor.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 DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ #include <list> #include <map> @@ -13,10 +13,9 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/single_thread_task_runner.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" #include "mojo/public/cpp/system/buffer.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -25,8 +24,7 @@ // Base class for the sensors provided by the platform. Concrete instances of // this class are created by platform specific PlatformSensorProvider. -class DEVICE_GENERIC_SENSOR_EXPORT PlatformSensor - : public base::RefCountedThreadSafe<PlatformSensor> { +class PlatformSensor : public base::RefCountedThreadSafe<PlatformSensor> { public: // The interface that must be implemented by PlatformSensor clients. class Client { @@ -108,4 +106,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_H_
diff --git a/device/generic_sensor/platform_sensor_accelerometer_mac.cc b/services/device/generic_sensor/platform_sensor_accelerometer_mac.cc similarity index 93% rename from device/generic_sensor/platform_sensor_accelerometer_mac.cc rename to services/device/generic_sensor/platform_sensor_accelerometer_mac.cc index 19a7f296..4ca3b61 100644 --- a/device/generic_sensor/platform_sensor_accelerometer_mac.cc +++ b/services/device/generic_sensor/platform_sensor_accelerometer_mac.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 "device/generic_sensor/platform_sensor_accelerometer_mac.h" +#include "services/device/generic_sensor/platform_sensor_accelerometer_mac.h" #include <stdint.h> @@ -10,8 +10,8 @@ #include "base/bind.h" #include "device/base/synchronization/shared_memory_seqlock_buffer.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/platform_sensor_provider_mac.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/generic_sensor/platform_sensor_provider_mac.h" #include "third_party/sudden_motion_sensor/sudden_motion_sensor_mac.h" namespace {
diff --git a/device/generic_sensor/platform_sensor_accelerometer_mac.h b/services/device/generic_sensor/platform_sensor_accelerometer_mac.h similarity index 84% rename from device/generic_sensor/platform_sensor_accelerometer_mac.h rename to services/device/generic_sensor/platform_sensor_accelerometer_mac.h index 02e08b5..41a662c 100644 --- a/device/generic_sensor/platform_sensor_accelerometer_mac.h +++ b/services/device/generic_sensor/platform_sensor_accelerometer_mac.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_ #include <memory> #include "base/timer/timer.h" -#include "device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor.h" class SuddenMotionSensor; @@ -52,4 +52,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ACCELEROMETER_MAC_H_
diff --git a/device/generic_sensor/platform_sensor_ambient_light_mac.cc b/services/device/generic_sensor/platform_sensor_ambient_light_mac.cc similarity index 96% rename from device/generic_sensor/platform_sensor_ambient_light_mac.cc rename to services/device/generic_sensor/platform_sensor_ambient_light_mac.cc index 8a72acf..e60ced3 100644 --- a/device/generic_sensor/platform_sensor_ambient_light_mac.cc +++ b/services/device/generic_sensor/platform_sensor_ambient_light_mac.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 "device/generic_sensor/platform_sensor_ambient_light_mac.h" +#include "services/device/generic_sensor/platform_sensor_ambient_light_mac.h" #include <stdint.h> @@ -10,8 +10,8 @@ #include "base/bind.h" #include "device/base/synchronization/shared_memory_seqlock_buffer.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/platform_sensor_provider_mac.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/generic_sensor/platform_sensor_provider_mac.h" namespace {
diff --git a/device/generic_sensor/platform_sensor_ambient_light_mac.h b/services/device/generic_sensor/platform_sensor_ambient_light_mac.h similarity index 97% rename from device/generic_sensor/platform_sensor_ambient_light_mac.h rename to services/device/generic_sensor/platform_sensor_ambient_light_mac.h index 649b32ec..86c4871e 100644 --- a/device/generic_sensor/platform_sensor_ambient_light_mac.h +++ b/services/device/generic_sensor/platform_sensor_ambient_light_mac.h
@@ -9,7 +9,7 @@ #include "base/mac/scoped_ionotificationportref.h" #include "base/mac/scoped_ioobject.h" -#include "device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc b/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc similarity index 98% rename from device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc rename to services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc index 907d12c..9e1b94cb 100644 --- a/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc +++ b/services/device/generic_sensor/platform_sensor_and_provider_unittest_linux.cc
@@ -10,10 +10,10 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" -#include "device/generic_sensor/linux/sensor_device_manager.h" -#include "device/generic_sensor/platform_sensor_provider_linux.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/generic_sensor/linux/sensor_data_linux.h" +#include "services/device/generic_sensor/linux/sensor_device_manager.h" +#include "services/device/generic_sensor/platform_sensor_provider_linux.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc similarity index 98% rename from device/generic_sensor/platform_sensor_and_provider_unittest_win.cc rename to services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc index fbe917fe..8bf01e83 100644 --- a/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc +++ b/services/device/generic_sensor/platform_sensor_and_provider_unittest_win.cc
@@ -13,9 +13,9 @@ #include "base/run_loop.h" #include "base/win/iunknown_impl.h" #include "base/win/scoped_propvariant.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/platform_sensor_provider_win.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/generic_sensor/platform_sensor_provider_win.h" +#include "services/device/public/interfaces/sensor_provider.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/device/generic_sensor/platform_sensor_android.cc b/services/device/generic_sensor/platform_sensor_android.cc similarity index 97% rename from device/generic_sensor/platform_sensor_android.cc rename to services/device/generic_sensor/platform_sensor_android.cc index 10e3f6c1..7d73381 100644 --- a/device/generic_sensor/platform_sensor_android.cc +++ b/services/device/generic_sensor/platform_sensor_android.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 "device/generic_sensor/platform_sensor_android.h" +#include "services/device/generic_sensor/platform_sensor_android.h" #include "base/bind.h" #include "jni/PlatformSensor_jni.h"
diff --git a/device/generic_sensor/platform_sensor_android.h b/services/device/generic_sensor/platform_sensor_android.h similarity index 86% rename from device/generic_sensor/platform_sensor_android.h rename to services/device/generic_sensor/platform_sensor_android.h index 48937e0b..af0ed12 100644 --- a/device/generic_sensor/platform_sensor_android.h +++ b/services/device/generic_sensor/platform_sensor_android.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_ -#include "device/generic_sensor/platform_sensor.h" #include "base/android/scoped_java_ref.h" #include "base/memory/ref_counted.h" +#include "services/device/generic_sensor/platform_sensor.h" namespace device { @@ -52,4 +52,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_ANDROID_H_
diff --git a/device/generic_sensor/platform_sensor_linux.cc b/services/device/generic_sensor/platform_sensor_linux.cc similarity index 93% rename from device/generic_sensor/platform_sensor_linux.cc rename to services/device/generic_sensor/platform_sensor_linux.cc index 5d3e07b..9c6ca71 100644 --- a/device/generic_sensor/platform_sensor_linux.cc +++ b/services/device/generic_sensor/platform_sensor_linux.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 "device/generic_sensor/platform_sensor_linux.h" +#include "services/device/generic_sensor/platform_sensor_linux.h" #include "base/single_thread_task_runner.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" -#include "device/generic_sensor/platform_sensor_reader_linux.h" +#include "services/device/generic_sensor/linux/sensor_data_linux.h" +#include "services/device/generic_sensor/platform_sensor_reader_linux.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_linux.h b/services/device/generic_sensor/platform_sensor_linux.h similarity index 87% rename from device/generic_sensor/platform_sensor_linux.h rename to services/device/generic_sensor/platform_sensor_linux.h index 9442b0c..310c8a1 100644 --- a/device/generic_sensor/platform_sensor_linux.h +++ b/services/device/generic_sensor/platform_sensor_linux.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_ -#include "device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor.h" namespace base { class SingleThreadTaskRunner; @@ -63,4 +63,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_LINUX_H_
diff --git a/device/generic_sensor/platform_sensor_provider.cc b/services/device/generic_sensor/platform_sensor_provider.cc similarity index 74% rename from device/generic_sensor/platform_sensor_provider.cc rename to services/device/generic_sensor/platform_sensor_provider.cc index e7749e18..c7cc03f8 100644 --- a/device/generic_sensor/platform_sensor_provider.cc +++ b/services/device/generic_sensor/platform_sensor_provider.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 "device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" #if defined(OS_MACOSX) -#include "device/generic_sensor/platform_sensor_provider_mac.h" +#include "services/device/generic_sensor/platform_sensor_provider_mac.h" #elif defined(OS_ANDROID) -#include "device/generic_sensor/platform_sensor_provider_android.h" +#include "services/device/generic_sensor/platform_sensor_provider_android.h" #elif defined(OS_WIN) -#include "device/generic_sensor/platform_sensor_provider_win.h" +#include "services/device/generic_sensor/platform_sensor_provider_win.h" #elif defined(OS_LINUX) && defined(USE_UDEV) -#include "device/generic_sensor/platform_sensor_provider_linux.h" +#include "services/device/generic_sensor/platform_sensor_provider_linux.h" #endif namespace {
diff --git a/device/generic_sensor/platform_sensor_provider.h b/services/device/generic_sensor/platform_sensor_provider.h similarity index 69% rename from device/generic_sensor/platform_sensor_provider.h rename to services/device/generic_sensor/platform_sensor_provider.h index 6900734..e9777f9 100644 --- a/device/generic_sensor/platform_sensor_provider.h +++ b/services/device/generic_sensor/platform_sensor_provider.h
@@ -2,18 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_ -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/platform_sensor_provider_base.h" +#include "services/device/generic_sensor/platform_sensor_provider_base.h" namespace device { // This a singleton class returning the actual sensor provider // implementation for the current platform. -class DEVICE_GENERIC_SENSOR_EXPORT PlatformSensorProvider - : public PlatformSensorProviderBase { +class PlatformSensorProvider : public PlatformSensorProviderBase { public: // Returns the PlatformSensorProvider singleton. // Note: returns 'nullptr' if there is no available implementation for @@ -34,4 +32,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_H_
diff --git a/device/generic_sensor/platform_sensor_provider_android.cc b/services/device/generic_sensor/platform_sensor_provider_android.cc similarity index 90% rename from device/generic_sensor/platform_sensor_provider_android.cc rename to services/device/generic_sensor/platform_sensor_provider_android.cc index 05a008a..0c60a1b 100644 --- a/device/generic_sensor/platform_sensor_provider_android.cc +++ b/services/device/generic_sensor/platform_sensor_provider_android.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 "device/generic_sensor/platform_sensor_provider_android.h" +#include "services/device/generic_sensor/platform_sensor_provider_android.h" #include "base/android/scoped_java_ref.h" #include "base/memory/singleton.h" -#include "device/generic_sensor/platform_sensor_android.h" #include "jni/PlatformSensorProvider_jni.h" +#include "services/device/generic_sensor/platform_sensor_android.h" using base::android::AttachCurrentThread; using base::android::ScopedJavaLocalRef;
diff --git a/device/generic_sensor/platform_sensor_provider_android.h b/services/device/generic_sensor/platform_sensor_provider_android.h similarity index 74% rename from device/generic_sensor/platform_sensor_provider_android.h rename to services/device/generic_sensor/platform_sensor_provider_android.h index ea2212b..5a1610b 100644 --- a/device/generic_sensor/platform_sensor_provider_android.h +++ b/services/device/generic_sensor/platform_sensor_provider_android.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_ -#include "device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" #include "base/android/scoped_java_ref.h" @@ -32,4 +32,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_ANDROID_H_
diff --git a/device/generic_sensor/platform_sensor_provider_base.cc b/services/device/generic_sensor/platform_sensor_provider_base.cc similarity index 96% rename from device/generic_sensor/platform_sensor_provider_base.cc rename to services/device/generic_sensor/platform_sensor_provider_base.cc index 8af22ed..463eb64 100644 --- a/device/generic_sensor/platform_sensor_provider_base.cc +++ b/services/device/generic_sensor/platform_sensor_provider_base.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 "device/generic_sensor/platform_sensor_provider_base.h" +#include "services/device/generic_sensor/platform_sensor_provider_base.h" #include <utility> #include "base/stl_util.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom.h" +#include "services/device/public/interfaces/sensor_provider.mojom.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_provider_base.h b/services/device/generic_sensor/platform_sensor_provider_base.h similarity index 87% rename from device/generic_sensor/platform_sensor_provider_base.h rename to services/device/generic_sensor/platform_sensor_provider_base.h index c38443b..77926f78 100644 --- a/device/generic_sensor/platform_sensor_provider_base.h +++ b/services/device/generic_sensor/platform_sensor_provider_base.h
@@ -2,21 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_ #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_checker.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor.h" namespace device { // Base class that defines factory methods for PlatformSensor creation. // Its implementations must be accessed via GetInstance() method. -class DEVICE_GENERIC_SENSOR_EXPORT PlatformSensorProviderBase { +class PlatformSensorProviderBase { public: using CreateSensorCallback = base::Callback<void(scoped_refptr<PlatformSensor>)>; @@ -81,4 +80,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_BASE_H_
diff --git a/device/generic_sensor/platform_sensor_provider_linux.cc b/services/device/generic_sensor/platform_sensor_provider_linux.cc similarity index 95% rename from device/generic_sensor/platform_sensor_provider_linux.cc rename to services/device/generic_sensor/platform_sensor_provider_linux.cc index 4db2a4c..025cc59 100644 --- a/device/generic_sensor/platform_sensor_provider_linux.cc +++ b/services/device/generic_sensor/platform_sensor_provider_linux.cc
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "device/generic_sensor/platform_sensor_provider_linux.h" +#include "services/device/generic_sensor/platform_sensor_provider_linux.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" #include "base/task_runner_util.h" #include "base/threading/thread.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" -#include "device/generic_sensor/platform_sensor_linux.h" -#include "device/generic_sensor/platform_sensor_reader_linux.h" +#include "services/device/generic_sensor/linux/sensor_data_linux.h" +#include "services/device/generic_sensor/platform_sensor_linux.h" +#include "services/device/generic_sensor/platform_sensor_reader_linux.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_provider_linux.h b/services/device/generic_sensor/platform_sensor_provider_linux.h similarity index 87% rename from device/generic_sensor/platform_sensor_provider_linux.h rename to services/device/generic_sensor/platform_sensor_provider_linux.h index 5bde10f..31803cd 100644 --- a/device/generic_sensor/platform_sensor_provider_linux.h +++ b/services/device/generic_sensor/platform_sensor_provider_linux.h
@@ -2,28 +2,26 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_ -#define DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_ -#include "device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" #include "base/single_thread_task_runner.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/linux/sensor_device_manager.h" +#include "services/device/generic_sensor/linux/sensor_device_manager.h" namespace base { template <typename T> struct DefaultSingletonTraits; class Thread; -} +} // namespace base namespace device { struct SensorInfoLinux; -class DEVICE_GENERIC_SENSOR_EXPORT PlatformSensorProviderLinux - : public PlatformSensorProvider, - public SensorDeviceManager::Delegate { +class PlatformSensorProviderLinux : public PlatformSensorProvider, + public SensorDeviceManager::Delegate { public: static PlatformSensorProviderLinux* GetInstance(); @@ -119,4 +117,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PUBLIC_PLATFORM_SENSOR_PROVIDER_LINUX_H_
diff --git a/device/generic_sensor/platform_sensor_provider_mac.cc b/services/device/generic_sensor/platform_sensor_provider_mac.cc similarity index 84% rename from device/generic_sensor/platform_sensor_provider_mac.cc rename to services/device/generic_sensor/platform_sensor_provider_mac.cc index f88a34d..2fdfb1d 100644 --- a/device/generic_sensor/platform_sensor_provider_mac.cc +++ b/services/device/generic_sensor/platform_sensor_provider_mac.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 "device/generic_sensor/platform_sensor_provider_mac.h" +#include "services/device/generic_sensor/platform_sensor_provider_mac.h" #include "base/memory/singleton.h" -#include "device/generic_sensor/platform_sensor_accelerometer_mac.h" -#include "device/generic_sensor/platform_sensor_ambient_light_mac.h" +#include "services/device/generic_sensor/platform_sensor_accelerometer_mac.h" +#include "services/device/generic_sensor/platform_sensor_ambient_light_mac.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_provider_mac.h b/services/device/generic_sensor/platform_sensor_provider_mac.h similarity index 70% rename from device/generic_sensor/platform_sensor_provider_mac.h rename to services/device/generic_sensor/platform_sensor_provider_mac.h index f904eb20..809a4f2 100644 --- a/device/generic_sensor/platform_sensor_provider_mac.h +++ b/services/device/generic_sensor/platform_sensor_provider_mac.h
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_ -#include "device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" namespace device { @@ -27,4 +27,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_MAC_H_
diff --git a/device/generic_sensor/platform_sensor_provider_win.cc b/services/device/generic_sensor/platform_sensor_provider_win.cc similarity index 95% rename from device/generic_sensor/platform_sensor_provider_win.cc rename to services/device/generic_sensor/platform_sensor_provider_win.cc index e894837..07ffe2eb 100644 --- a/device/generic_sensor/platform_sensor_provider_win.cc +++ b/services/device/generic_sensor/platform_sensor_provider_win.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "device/generic_sensor/platform_sensor_provider_win.h" +#include "services/device/generic_sensor/platform_sensor_provider_win.h" #include <objbase.h> @@ -10,7 +10,7 @@ #include "base/memory/singleton.h" #include "base/task_runner_util.h" #include "base/threading/thread.h" -#include "device/generic_sensor/platform_sensor_win.h" +#include "services/device/generic_sensor/platform_sensor_win.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_provider_win.h b/services/device/generic_sensor/platform_sensor_provider_win.h similarity index 83% rename from device/generic_sensor/platform_sensor_provider_win.h rename to services/device/generic_sensor/platform_sensor_provider_win.h index 9cdacb4..e3ee6ed8 100644 --- a/device/generic_sensor/platform_sensor_provider_win.h +++ b/services/device/generic_sensor/platform_sensor_provider_win.h
@@ -2,20 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_ #include <SensorsApi.h> #include "base/win/scoped_comptr.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" namespace base { template <typename T> struct DefaultSingletonTraits; class Thread; -} +} // namespace base namespace device { @@ -26,8 +25,7 @@ // - Starts sensor thread and stops it when there are no active sensors. // - Initialises ISensorManager and creates sensor reader on sensor thread. // - Constructs PlatformSensorWin on IPC thread and returns it to requester. -class DEVICE_GENERIC_SENSOR_EXPORT PlatformSensorProviderWin final - : public PlatformSensorProvider { +class PlatformSensorProviderWin final : public PlatformSensorProvider { public: static PlatformSensorProviderWin* GetInstance(); @@ -70,4 +68,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_PROVIDER_WIN_H_
diff --git a/device/generic_sensor/platform_sensor_reader_linux.cc b/services/device/generic_sensor/platform_sensor_reader_linux.cc similarity index 90% rename from device/generic_sensor/platform_sensor_reader_linux.cc rename to services/device/generic_sensor/platform_sensor_reader_linux.cc index a814e878..521d780a 100644 --- a/device/generic_sensor/platform_sensor_reader_linux.cc +++ b/services/device/generic_sensor/platform_sensor_reader_linux.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 "device/generic_sensor/platform_sensor_reader_linux.h" +#include "services/device/generic_sensor/platform_sensor_reader_linux.h" #include "base/files/file_util.h" #include "base/memory/ptr_util.h" @@ -11,9 +11,9 @@ #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/timer/timer.h" -#include "device/generic_sensor/linux/sensor_data_linux.h" -#include "device/generic_sensor/platform_sensor_linux.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" +#include "services/device/generic_sensor/linux/sensor_data_linux.h" +#include "services/device/generic_sensor/platform_sensor_linux.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" namespace device { @@ -86,10 +86,11 @@ const PlatformSensorConfiguration& configuration) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!is_reading_active_); - timer_.Start(FROM_HERE, base::TimeDelta::FromMicroseconds( - base::Time::kMicrosecondsPerSecond / - configuration.frequency()), - this, &PollingSensorReader::PollForData); + timer_.Start( + FROM_HERE, + base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond / + configuration.frequency()), + this, &PollingSensorReader::PollForData); is_reading_active_ = true; }
diff --git a/device/generic_sensor/platform_sensor_reader_linux.h b/services/device/generic_sensor/platform_sensor_reader_linux.h similarity index 89% rename from device/generic_sensor/platform_sensor_reader_linux.h rename to services/device/generic_sensor/platform_sensor_reader_linux.h index c5c1630..c944efa 100644 --- a/device/generic_sensor/platform_sensor_reader_linux.h +++ b/services/device/generic_sensor/platform_sensor_reader_linux.h
@@ -2,14 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_ #include "base/callback.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" -#include "device/generic_sensor/generic_sensor_export.h" namespace base { class SingleThreadTaskRunner; @@ -70,4 +69,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_LINUX_H_
diff --git a/device/generic_sensor/platform_sensor_reader_win.cc b/services/device/generic_sensor/platform_sensor_reader_win.cc similarity index 91% rename from device/generic_sensor/platform_sensor_reader_win.cc rename to services/device/generic_sensor/platform_sensor_reader_win.cc index d158b99..b8a16d3 100644 --- a/device/generic_sensor/platform_sensor_reader_win.cc +++ b/services/device/generic_sensor/platform_sensor_reader_win.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "device/generic_sensor/platform_sensor_reader_win.h" +#include "services/device/generic_sensor/platform_sensor_reader_win.h" #include <Sensors.h> #include <objbase.h> @@ -13,9 +13,9 @@ #include "base/time/time.h" #include "base/win/iunknown_impl.h" #include "base/win/scoped_propvariant.h" -#include "device/generic_sensor/generic_sensor_consts.h" -#include "device/generic_sensor/public/cpp/platform_sensor_configuration.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" +#include "services/device/generic_sensor/generic_sensor_consts.h" +#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" namespace device { @@ -105,31 +105,31 @@ std::unique_ptr<ReaderInitParams> CreateGyroscopeReaderInitParams() { auto params = base::MakeUnique<ReaderInitParams>(); params->sensor_type_id = SENSOR_TYPE_GYROMETER_3D; - params->reader_func = base::Bind([](ISensorDataReport* report, - SensorReading* reading) { - double x = 0.0; - double y = 0.0; - double z = 0.0; - if (!GetReadingValueForProperty( - SENSOR_DATA_TYPE_ANGULAR_VELOCITY_X_DEGREES_PER_SECOND, report, - &x) || - !GetReadingValueForProperty( - SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Y_DEGREES_PER_SECOND, report, - &y) || - !GetReadingValueForProperty( - SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Z_DEGREES_PER_SECOND, report, - &z)) { - return E_FAIL; - } + params->reader_func = + base::Bind([](ISensorDataReport* report, SensorReading* reading) { + double x = 0.0; + double y = 0.0; + double z = 0.0; + if (!GetReadingValueForProperty( + SENSOR_DATA_TYPE_ANGULAR_VELOCITY_X_DEGREES_PER_SECOND, report, + &x) || + !GetReadingValueForProperty( + SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Y_DEGREES_PER_SECOND, report, + &y) || + !GetReadingValueForProperty( + SENSOR_DATA_TYPE_ANGULAR_VELOCITY_Z_DEGREES_PER_SECOND, report, + &z)) { + return E_FAIL; + } - // Windows uses coordinate system where Z axis points down from device - // screen, therefore, using right hand notation, we have to reverse - // sign for each axis. Values are converted from deg to rad. - reading->values[0] = -x * kRadiansInDegrees; - reading->values[1] = -y * kRadiansInDegrees; - reading->values[2] = -z * kRadiansInDegrees; - return S_OK; - }); + // Windows uses coordinate system where Z axis points down from device + // screen, therefore, using right hand notation, we have to reverse + // sign for each axis. Values are converted from deg to rad. + reading->values[0] = -x * kRadiansInDegrees; + reading->values[1] = -y * kRadiansInDegrees; + reading->values[2] = -z * kRadiansInDegrees; + return S_OK; + }); return params; }
diff --git a/device/generic_sensor/platform_sensor_reader_win.h b/services/device/generic_sensor/platform_sensor_reader_win.h similarity index 90% rename from device/generic_sensor/platform_sensor_reader_win.h rename to services/device/generic_sensor/platform_sensor_reader_win.h index 64fb3c8..632a0c37 100644 --- a/device/generic_sensor/platform_sensor_reader_win.h +++ b/services/device/generic_sensor/platform_sensor_reader_win.h
@@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_ #include <SensorsApi.h> #include "base/win/scoped_comptr.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -79,4 +79,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_READER_WIN_H_
diff --git a/device/generic_sensor/platform_sensor_win.cc b/services/device/generic_sensor/platform_sensor_win.cc similarity index 97% rename from device/generic_sensor/platform_sensor_win.cc rename to services/device/generic_sensor/platform_sensor_win.cc index 65cf562e..fd521ddd 100644 --- a/device/generic_sensor/platform_sensor_win.cc +++ b/services/device/generic_sensor/platform_sensor_win.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "device/generic_sensor/platform_sensor_win.h" +#include "services/device/generic_sensor/platform_sensor_win.h" + #include "base/single_thread_task_runner.h" namespace device {
diff --git a/device/generic_sensor/platform_sensor_win.h b/services/device/generic_sensor/platform_sensor_win.h similarity index 86% rename from device/generic_sensor/platform_sensor_win.h rename to services/device/generic_sensor/platform_sensor_win.h index 043fb1c..b2bd4c2 100644 --- a/device/generic_sensor/platform_sensor_win.h +++ b/services/device/generic_sensor/platform_sensor_win.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_ #include "base/memory/weak_ptr.h" -#include "device/generic_sensor/platform_sensor.h" -#include "device/generic_sensor/platform_sensor_reader_win.h" +#include "services/device/generic_sensor/platform_sensor.h" +#include "services/device/generic_sensor/platform_sensor_reader_win.h" namespace base { class SingleThreadTaskRunner; @@ -59,4 +59,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_WIN_H_
diff --git a/device/generic_sensor/sensor_impl.cc b/services/device/generic_sensor/sensor_impl.cc similarity index 97% rename from device/generic_sensor/sensor_impl.cc rename to services/device/generic_sensor/sensor_impl.cc index 3f82419..013e25a 100644 --- a/device/generic_sensor/sensor_impl.cc +++ b/services/device/generic_sensor/sensor_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 "device/generic_sensor/sensor_impl.h" +#include "services/device/generic_sensor/sensor_impl.h" #include <utility>
diff --git a/device/generic_sensor/sensor_impl.h b/services/device/generic_sensor/sensor_impl.h similarity index 84% rename from device/generic_sensor/sensor_impl.h rename to services/device/generic_sensor/sensor_impl.h index 48ad5322..d9606eed 100644 --- a/device/generic_sensor/sensor_impl.h +++ b/services/device/generic_sensor/sensor_impl.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_ -#define DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_ #include "base/macros.h" -#include "device/generic_sensor/platform_sensor.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/generic_sensor/platform_sensor.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -50,4 +50,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_IMPL_H_
diff --git a/device/generic_sensor/sensor_provider_impl.cc b/services/device/generic_sensor/sensor_provider_impl.cc similarity index 95% rename from device/generic_sensor/sensor_provider_impl.cc rename to services/device/generic_sensor/sensor_provider_impl.cc index 3e78e3a1..1f54909 100644 --- a/device/generic_sensor/sensor_provider_impl.cc +++ b/services/device/generic_sensor/sensor_provider_impl.cc
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "device/generic_sensor/sensor_provider_impl.h" +#include "services/device/generic_sensor/sensor_provider_impl.h" #include <utility> #include "base/memory/ptr_util.h" #include "base/threading/thread_task_runner_handle.h" -#include "device/generic_sensor/platform_sensor_provider.h" -#include "device/generic_sensor/sensor_impl.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "services/device/generic_sensor/platform_sensor_provider.h" +#include "services/device/generic_sensor/sensor_impl.h" namespace device {
diff --git a/device/generic_sensor/sensor_provider_impl.h b/services/device/generic_sensor/sensor_provider_impl.h similarity index 78% rename from device/generic_sensor/sensor_provider_impl.h rename to services/device/generic_sensor/sensor_provider_impl.h index 2dd3728b..1c2722d3 100644 --- a/device/generic_sensor/sensor_provider_impl.h +++ b/services/device/generic_sensor/sensor_provider_impl.h
@@ -2,13 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_ -#define DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_ +#ifndef SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_ +#define SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_ #include "base/macros.h" #include "base/single_thread_task_runner.h" -#include "device/generic_sensor/generic_sensor_export.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom.h" +#include "services/device/public/interfaces/sensor_provider.mojom.h" namespace device { @@ -18,8 +17,7 @@ // Implementation of SensorProvider mojo interface. // Uses PlatformSensorProvider singleton to create platform specific instances // of PlatformSensor which are used by SensorImpl. -class DEVICE_GENERIC_SENSOR_EXPORT SensorProviderImpl final - : public mojom::SensorProvider { +class SensorProviderImpl final : public mojom::SensorProvider { public: static void Create( scoped_refptr<base::SingleThreadTaskRunner> file_task_runner, @@ -50,4 +48,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_ +#endif // SERVICES_DEVICE_GENERIC_SENSOR_SENSOR_PROVIDER_IMPL_H_
diff --git a/device/generic_sensor/public/cpp/BUILD.gn b/services/device/public/cpp/generic_sensor/BUILD.gn similarity index 75% rename from device/generic_sensor/public/cpp/BUILD.gn rename to services/device/public/cpp/generic_sensor/BUILD.gn index 420fffb..351ea5c 100644 --- a/device/generic_sensor/public/cpp/BUILD.gn +++ b/services/device/public/cpp/generic_sensor/BUILD.gn
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -component("cpp") { +source_set("generic_sensor") { sources = [ "platform_sensor_configuration.cc", "platform_sensor_configuration.h", @@ -10,10 +10,8 @@ "sensor_reading.h", ] - defines = [ "DEVICE_GENERIC_SENSOR_PUBLIC_IMPLEMENTATION" ] - public_deps = [ - "//device/generic_sensor/public/interfaces", + "//services/device/public/interfaces:generic_sensor", ] deps = [
diff --git a/device/generic_sensor/public/cpp/OWNERS b/services/device/public/cpp/generic_sensor/OWNERS similarity index 100% rename from device/generic_sensor/public/cpp/OWNERS rename to services/device/public/cpp/generic_sensor/OWNERS
diff --git a/device/generic_sensor/public/cpp/platform_sensor_configuration.cc b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.cc similarity index 87% rename from device/generic_sensor/public/cpp/platform_sensor_configuration.cc rename to services/device/public/cpp/generic_sensor/platform_sensor_configuration.cc index 44b26b3..2079b30 100644 --- a/device/generic_sensor/public/cpp/platform_sensor_configuration.cc +++ b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.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 "device/generic_sensor/public/cpp/platform_sensor_configuration.h" +#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device {
diff --git a/device/generic_sensor/public/cpp/platform_sensor_configuration.h b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h similarity index 77% rename from device/generic_sensor/public/cpp/platform_sensor_configuration.h rename to services/device/public/cpp/generic_sensor/platform_sensor_configuration.h index c6a895e..be7ad030 100644 --- a/device/generic_sensor/public/cpp/platform_sensor_configuration.h +++ b/services/device/public/cpp/generic_sensor/platform_sensor_configuration.h
@@ -2,15 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_CONFIGURATION_H_ -#define DEVICE_GENERIC_SENSOR_PLATFORM_SENSOR_CONFIGURATION_H_ +#ifndef SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_PLATFORM_SENSOR_CONFIGURATION_H_ +#define SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_PLATFORM_SENSOR_CONFIGURATION_H_ #include "base/logging.h" -#include "device/generic_sensor/public/cpp/generic_sensor_public_export.h" namespace device { -class DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT PlatformSensorConfiguration { +class PlatformSensorConfiguration { public: PlatformSensorConfiguration(); explicit PlatformSensorConfiguration(double frequency); @@ -38,4 +37,4 @@ } // namespace device -#endif // DEVICE_SENSORS_PLATFORM_SENSOR_CONFIGURATION_H_ +#endif // SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_PLATFORM_SENSOR_CONFIGURATION_H_
diff --git a/device/generic_sensor/public/cpp/sensor_reading.cc b/services/device/public/cpp/generic_sensor/sensor_reading.cc similarity index 90% rename from device/generic_sensor/public/cpp/sensor_reading.cc rename to services/device/public/cpp/generic_sensor/sensor_reading.cc index ae61145..85b2c36 100644 --- a/device/generic_sensor/public/cpp/sensor_reading.cc +++ b/services/device/public/cpp/generic_sensor/sensor_reading.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 "device/generic_sensor/public/cpp/sensor_reading.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" namespace device {
diff --git a/device/generic_sensor/public/cpp/sensor_reading.h b/services/device/public/cpp/generic_sensor/sensor_reading.h similarity index 88% rename from device/generic_sensor/public/cpp/sensor_reading.h rename to services/device/public/cpp/generic_sensor/sensor_reading.h index a7048f7..699f92d 100644 --- a/device/generic_sensor/public/cpp/sensor_reading.h +++ b/services/device/public/cpp/generic_sensor/sensor_reading.h
@@ -2,12 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PUBLIC_CPP_SENSOR_READING_H_ -#define DEVICE_GENERIC_SENSOR_PUBLIC_CPP_SENSOR_READING_H_ +#ifndef SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_READING_H_ +#define SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_READING_H_ #include "device/base/synchronization/one_writer_seqlock.h" -#include "device/generic_sensor/public/cpp/generic_sensor_public_export.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace device { @@ -40,7 +39,7 @@ }; // This structure represents sensor reading data: timestamp and 4 values. -struct DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT SensorReading { +struct SensorReading { SensorReading(); ~SensorReading(); SensorReading(const SensorReading& other); @@ -101,7 +100,7 @@ // This structure represents sensor reading buffer: sensor reading and seqlock // for synchronization. -struct DEVICE_GENERIC_SENSOR_PUBLIC_EXPORT SensorReadingSharedBuffer { +struct SensorReadingSharedBuffer { SensorReadingSharedBuffer(); ~SensorReadingSharedBuffer(); SensorReadingField<OneWriterSeqLock> seqlock; @@ -113,4 +112,4 @@ } // namespace device -#endif // DEVICE_GENERIC_SENSOR_PUBLIC_CPP_SENSOR_READING_H_ +#endif // SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_READING_H_
diff --git a/device/generic_sensor/public/cpp/sensor_struct_traits.cc b/services/device/public/cpp/generic_sensor/sensor_struct_traits.cc similarity index 90% rename from device/generic_sensor/public/cpp/sensor_struct_traits.cc rename to services/device/public/cpp/generic_sensor/sensor_struct_traits.cc index a007b679..37e84687 100644 --- a/device/generic_sensor/public/cpp/sensor_struct_traits.cc +++ b/services/device/public/cpp/generic_sensor/sensor_struct_traits.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 "device/generic_sensor/public/cpp/sensor_struct_traits.h" +#include "services/device/public/cpp/generic_sensor/sensor_struct_traits.h" namespace mojo {
diff --git a/device/generic_sensor/public/cpp/sensor_struct_traits.h b/services/device/public/cpp/generic_sensor/sensor_struct_traits.h similarity index 66% rename from device/generic_sensor/public/cpp/sensor_struct_traits.h rename to services/device/public/cpp/generic_sensor/sensor_struct_traits.h index 96916382..5f5c57e 100644 --- a/device/generic_sensor/public/cpp/sensor_struct_traits.h +++ b/services/device/public/cpp/generic_sensor/sensor_struct_traits.h
@@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef DEVICE_GENERIC_SENSOR_PUBLIC_INTERFACES_SENSOR_STRUCT_TRAITS_H_ -#define DEVICE_GENERIC_SENSOR_PUBLIC_INTERFACES_SENSOR_STRUCT_TRAITS_H_ +#ifndef SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_STRUCT_TRAITS_H_ +#define SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_STRUCT_TRAITS_H_ -#include "device/generic_sensor/public/cpp/platform_sensor_configuration.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom.h" +#include "services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" +#include "services/device/public/interfaces/sensor.mojom.h" namespace mojo { @@ -28,4 +28,4 @@ } // namespace mojo -#endif // DEVICE_GENERIC_SENSOR_PUBLIC_INTERFACES_SENSOR_STRUCT_TRAITS_H_ +#endif // SERVICES_DEVICE_PUBLIC_CPP_GENERIC_SENSOR_SENSOR_STRUCT_TRAITS_H_
diff --git a/services/device/public/interfaces/BUILD.gn b/services/device/public/interfaces/BUILD.gn index b368d19..a4adfe0 100644 --- a/services/device/public/interfaces/BUILD.gn +++ b/services/device/public/interfaces/BUILD.gn
@@ -24,6 +24,20 @@ use_new_js_bindings = false } +mojom("generic_sensor") { + sources = [ + "sensor.mojom", + "sensor_provider.mojom", + ] + + public_deps = [ + ":constants", + ] + + # TODO(crbug.com/699569): Convert to use the new JS bindings. + use_new_js_bindings = false +} + mojom("constants") { sources = [ "constants.mojom",
diff --git a/services/device/public/interfaces/OWNERS b/services/device/public/interfaces/OWNERS index 08850f4..2c44a46 100644 --- a/services/device/public/interfaces/OWNERS +++ b/services/device/public/interfaces/OWNERS
@@ -1,2 +1,6 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS +per-file *_struct_traits*.*=set noparent +per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *.typemap=set noparent +per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/device/generic_sensor/public/interfaces/sensor.mojom b/services/device/public/interfaces/sensor.mojom similarity index 100% rename from device/generic_sensor/public/interfaces/sensor.mojom rename to services/device/public/interfaces/sensor.mojom
diff --git a/services/device/public/interfaces/sensor.typemap b/services/device/public/interfaces/sensor.typemap new file mode 100644 index 0000000..d230c99 --- /dev/null +++ b/services/device/public/interfaces/sensor.typemap
@@ -0,0 +1,13 @@ +# 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. + +mojom = "//services/device/public/interfaces/sensor.mojom" +public_headers = [ "//services/device/public/cpp/generic_sensor/platform_sensor_configuration.h" ] +traits_headers = + [ "//services/device/public/cpp/generic_sensor/sensor_struct_traits.h" ] +sources = [ + "//services/device/public/cpp/generic_sensor/sensor_struct_traits.cc", +] +type_mappings = + [ "device.mojom.SensorConfiguration=device::PlatformSensorConfiguration" ]
diff --git a/device/generic_sensor/public/interfaces/sensor_provider.mojom b/services/device/public/interfaces/sensor_provider.mojom similarity index 100% rename from device/generic_sensor/public/interfaces/sensor_provider.mojom rename to services/device/public/interfaces/sensor_provider.mojom
diff --git a/device/generic_sensor/public/interfaces/typemaps.gni b/services/device/public/interfaces/typemaps.gni similarity index 68% rename from device/generic_sensor/public/interfaces/typemaps.gni rename to services/device/public/interfaces/typemaps.gni index d8877b1..3a292ce 100644 --- a/device/generic_sensor/public/interfaces/typemaps.gni +++ b/services/device/public/interfaces/typemaps.gni
@@ -2,4 +2,4 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -typemaps = [ "//device/generic_sensor/public/interfaces/sensor.typemap" ] +typemaps = [ "//services/device/public/interfaces/sensor.typemap" ]
diff --git a/services/identity/identity_manager.cc b/services/identity/identity_manager.cc index 7d03d82..627e21f 100644 --- a/services/identity/identity_manager.cc +++ b/services/identity/identity_manager.cc
@@ -77,22 +77,42 @@ &IdentityManager::OnSigninManagerShutdown, base::Unretained(this))); binding_.set_connection_error_handler( base::Bind(&IdentityManager::OnConnectionError, base::Unretained(this))); + + token_service_->AddObserver(this); } -IdentityManager::~IdentityManager() {} +IdentityManager::~IdentityManager() { + token_service_->RemoveObserver(this); +} void IdentityManager::GetPrimaryAccountInfo( GetPrimaryAccountInfoCallback callback) { // It's annoying that this can't be trivially implemented in terms of // GetAccountInfoFromGaiaId(), but there's no SigninManagerBase method that // directly returns the authenticated GAIA ID. We can of course get it from - // the AccountInfo but once we have the ACcountInfo we ... have the + // the AccountInfo but once we have the AccountInfo we ... have the // AccountInfo. AccountInfo account_info = signin_manager_->GetAuthenticatedAccountInfo(); AccountState account_state = GetStateOfAccount(account_info); std::move(callback).Run(account_info, account_state); } +void IdentityManager::GetPrimaryAccountWhenAvailable( + GetPrimaryAccountWhenAvailableCallback callback) { + AccountInfo account_info = signin_manager_->GetAuthenticatedAccountInfo(); + AccountState account_state = GetStateOfAccount(account_info); + + if (!account_state.has_refresh_token) { + primary_account_available_callbacks_.push_back(std::move(callback)); + return; + } + + DCHECK(!account_info.account_id.empty()); + DCHECK(!account_info.email.empty()); + DCHECK(!account_info.gaia.empty()); + std::move(callback).Run(account_info, account_state); +} + void IdentityManager::GetAccountInfoFromGaiaId( const std::string& gaia_id, GetAccountInfoFromGaiaIdCallback callback) { @@ -114,6 +134,21 @@ std::move(access_token_request); } +void IdentityManager::OnRefreshTokenAvailable(const std::string& account_id) { + AccountInfo account_info = account_tracker_->GetAccountInfo(account_id); + AccountState account_state = GetStateOfAccount(account_info); + + if (account_state.is_primary_account) { + DCHECK(!account_info.account_id.empty()); + DCHECK(!account_info.email.empty()); + DCHECK(!account_info.gaia.empty()); + for (auto&& callback : primary_account_available_callbacks_) { + std::move(callback).Run(account_info, account_state); + } + primary_account_available_callbacks_.clear(); + } +} + void IdentityManager::AccessTokenRequestCompleted(AccessTokenRequest* request) { access_token_requests_.erase(request); } @@ -123,6 +158,8 @@ AccountState account_state; account_state.has_refresh_token = token_service_->RefreshTokenIsAvailable(account_info.account_id); + account_state.is_primary_account = + (account_info.account_id == signin_manager_->GetAuthenticatedAccountId()); return account_state; }
diff --git a/services/identity/identity_manager.h b/services/identity/identity_manager.h index dd3d381e..fe49463 100644 --- a/services/identity/identity_manager.h +++ b/services/identity/identity_manager.h
@@ -18,7 +18,8 @@ namespace identity { -class IdentityManager : public mojom::IdentityManager { +class IdentityManager : public mojom::IdentityManager, + public OAuth2TokenService::Observer { public: static void Create(mojom::IdentityManagerRequest request, AccountTrackerService* account_tracker, @@ -68,6 +69,8 @@ // mojom::IdentityManager: void GetPrimaryAccountInfo(GetPrimaryAccountInfoCallback callback) override; + void GetPrimaryAccountWhenAvailable( + GetPrimaryAccountWhenAvailableCallback callback) override; void GetAccountInfoFromGaiaId( const std::string& gaia_id, GetAccountInfoFromGaiaIdCallback callback) override; @@ -76,6 +79,9 @@ const std::string& consumer_id, GetAccessTokenCallback callback) override; + // OAuth2TokenService::Observer: + void OnRefreshTokenAvailable(const std::string& account_id) override; + // Deletes |request|. void AccessTokenRequestCompleted(AccessTokenRequest* request); @@ -102,6 +108,11 @@ // The set of pending requests for access tokens. AccessTokenRequests access_token_requests_; + + // List of callbacks that will be notified when the primary account is + // available. + std::vector<GetPrimaryAccountWhenAvailableCallback> + primary_account_available_callbacks_; }; } // namespace identity
diff --git a/services/identity/identity_manager_unittest.cc b/services/identity/identity_manager_unittest.cc index 215a828..1fdb055d 100644 --- a/services/identity/identity_manager_unittest.cc +++ b/services/identity/identity_manager_unittest.cc
@@ -105,6 +105,16 @@ quit_closure.Run(); } + void OnPrimaryAccountAvailable(base::Closure quit_closure, + AccountInfo* caller_account_info, + AccountState* caller_account_state, + const AccountInfo& account_info, + const AccountState& account_state) { + *caller_account_info = account_info; + *caller_account_state = account_state; + quit_closure.Run(); + } + void OnReceivedAccountInfoFromGaiaId( base::Closure quit_closure, const base::Optional<AccountInfo>& account_info, @@ -196,6 +206,7 @@ EXPECT_EQ(kTestGaiaId, primary_account_info_->gaia); EXPECT_EQ(kTestEmail, primary_account_info_->email); EXPECT_FALSE(primary_account_state_.has_refresh_token); + EXPECT_TRUE(primary_account_state_.is_primary_account); } // Check that the primary account info has expected values if signed in with a @@ -215,6 +226,166 @@ EXPECT_EQ(kTestGaiaId, primary_account_info_->gaia); EXPECT_EQ(kTestEmail, primary_account_info_->email); EXPECT_TRUE(primary_account_state_.has_refresh_token); + EXPECT_TRUE(primary_account_state_.is_primary_account); +} + +// Check that GetPrimaryAccountWhenAvailable() returns immediately in the +// case where the primary account is available when the call is received. +TEST_F(IdentityManagerTest, GetPrimaryAccountWhenAvailableSignedIn) { + signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + token_service()->UpdateCredentials( + signin_manager()->GetAuthenticatedAccountId(), kTestRefreshToken); + + AccountInfo account_info; + AccountState account_state; + base::RunLoop run_loop; + identity_manager_->GetPrimaryAccountWhenAvailable(base::Bind( + &IdentityManagerTest::OnPrimaryAccountAvailable, base::Unretained(this), + run_loop.QuitClosure(), base::Unretained(&account_info), + base::Unretained(&account_state))); + run_loop.Run(); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + account_info.account_id); + EXPECT_EQ(kTestGaiaId, account_info.gaia); + EXPECT_EQ(kTestEmail, account_info.email); + EXPECT_TRUE(account_state.has_refresh_token); + EXPECT_TRUE(account_state.is_primary_account); +} + +// Check that GetPrimaryAccountWhenAvailable() returns the expected account +// info in the case where the primary account is made available *after* the +// call is received. +TEST_F(IdentityManagerTest, GetPrimaryAccountWhenAvailableSignInLater) { + AccountInfo account_info; + AccountState account_state; + + base::RunLoop run_loop; + identity_manager_->GetPrimaryAccountWhenAvailable(base::Bind( + &IdentityManagerTest::OnPrimaryAccountAvailable, base::Unretained(this), + run_loop.QuitClosure(), base::Unretained(&account_info), + base::Unretained(&account_state))); + + // Verify that the primary account info is not currently available (this also + // serves to ensure that the preceding call has been received by the Identity + // Manager before proceeding). + base::RunLoop run_loop2; + identity_manager_->GetPrimaryAccountInfo( + base::Bind(&IdentityManagerTest::OnReceivedPrimaryAccountInfo, + base::Unretained(this), run_loop2.QuitClosure())); + run_loop2.Run(); + EXPECT_FALSE(primary_account_info_); + + // Make the primary account available and check that the callback is invoked + // as expected. + signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + token_service()->UpdateCredentials( + signin_manager()->GetAuthenticatedAccountId(), kTestRefreshToken); + run_loop.Run(); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + account_info.account_id); + EXPECT_EQ(kTestGaiaId, account_info.gaia); + EXPECT_EQ(kTestEmail, account_info.email); + EXPECT_TRUE(account_state.has_refresh_token); + EXPECT_TRUE(account_state.is_primary_account); +} + +// Check that GetPrimaryAccountWhenAvailable() returns the expected account +// info in the case where signin is done before the call is received but the +// refresh token is made available only *after* the call is received. +TEST_F(IdentityManagerTest, GetPrimaryAccountWhenAvailableTokenAvailableLater) { + AccountInfo account_info; + AccountState account_state; + + // Sign in, but don't set the refresh token yet. + signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + base::RunLoop run_loop; + identity_manager_->GetPrimaryAccountWhenAvailable(base::Bind( + &IdentityManagerTest::OnPrimaryAccountAvailable, base::Unretained(this), + run_loop.QuitClosure(), base::Unretained(&account_info), + base::Unretained(&account_state))); + + // Verify that the primary account info is present, but that the primary + // account is not yet considered available (this also + // serves to ensure that the preceding call has been received by the Identity + // Manager before proceeding). + base::RunLoop run_loop2; + identity_manager_->GetPrimaryAccountInfo( + base::Bind(&IdentityManagerTest::OnReceivedPrimaryAccountInfo, + base::Unretained(this), run_loop2.QuitClosure())); + run_loop2.Run(); + + EXPECT_TRUE(primary_account_info_); + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + primary_account_info_->account_id); + EXPECT_TRUE(account_info.account_id.empty()); + + // Set the refresh token and check that the callback is invoked as expected + // (i.e., the primary account is now considered available). + token_service()->UpdateCredentials( + signin_manager()->GetAuthenticatedAccountId(), kTestRefreshToken); + run_loop.Run(); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + account_info.account_id); + EXPECT_EQ(kTestGaiaId, account_info.gaia); + EXPECT_EQ(kTestEmail, account_info.email); + EXPECT_TRUE(account_state.has_refresh_token); + EXPECT_TRUE(account_state.is_primary_account); +} + +// Check that GetPrimaryAccountWhenAvailable() returns the expected account +// info to all callers in the case where the primary account is made available +// after multiple overlapping calls have been received. +TEST_F(IdentityManagerTest, GetPrimaryAccountWhenAvailableOverlappingCalls) { + AccountInfo account_info1; + AccountState account_state1; + base::RunLoop run_loop; + identity_manager_->GetPrimaryAccountWhenAvailable(base::Bind( + &IdentityManagerTest::OnPrimaryAccountAvailable, base::Unretained(this), + run_loop.QuitClosure(), base::Unretained(&account_info1), + base::Unretained(&account_state1))); + + AccountInfo account_info2; + AccountState account_state2; + base::RunLoop run_loop2; + identity_manager_->GetPrimaryAccountWhenAvailable(base::Bind( + &IdentityManagerTest::OnPrimaryAccountAvailable, base::Unretained(this), + run_loop2.QuitClosure(), base::Unretained(&account_info2), + base::Unretained(&account_state2))); + + // Verify that the primary account info is not currently available (this also + // serves to ensure that the preceding call has been received by the Identity + // Manager before proceeding). + base::RunLoop run_loop3; + identity_manager_->GetPrimaryAccountInfo( + base::Bind(&IdentityManagerTest::OnReceivedPrimaryAccountInfo, + base::Unretained(this), run_loop3.QuitClosure())); + run_loop3.Run(); + EXPECT_FALSE(primary_account_info_); + + // Make the primary account available and check that the callbacks are invoked + // as expected. + signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + token_service()->UpdateCredentials( + signin_manager()->GetAuthenticatedAccountId(), kTestRefreshToken); + run_loop.Run(); + run_loop2.Run(); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + account_info1.account_id); + EXPECT_EQ(kTestGaiaId, account_info1.gaia); + EXPECT_EQ(kTestEmail, account_info1.email); + EXPECT_TRUE(account_state1.has_refresh_token); + EXPECT_TRUE(account_state1.is_primary_account); + + EXPECT_EQ(signin_manager()->GetAuthenticatedAccountId(), + account_info2.account_id); + EXPECT_EQ(kTestGaiaId, account_info2.gaia); + EXPECT_EQ(kTestEmail, account_info2.email); + EXPECT_TRUE(account_state2.has_refresh_token); + EXPECT_TRUE(account_state2.is_primary_account); } // Check that the account info for a given GAIA ID is null if that GAIA ID is @@ -245,6 +416,7 @@ EXPECT_EQ(kTestGaiaId, account_info_from_gaia_id_->gaia); EXPECT_EQ(kTestEmail, account_info_from_gaia_id_->email); EXPECT_FALSE(account_state_from_gaia_id_.has_refresh_token); + EXPECT_FALSE(account_state_from_gaia_id_.is_primary_account); } // Check that the account info for a given GAIA ID has expected values if that @@ -264,6 +436,7 @@ EXPECT_EQ(kTestGaiaId, account_info_from_gaia_id_->gaia); EXPECT_EQ(kTestEmail, account_info_from_gaia_id_->email); EXPECT_TRUE(account_state_from_gaia_id_.has_refresh_token); + EXPECT_FALSE(account_state_from_gaia_id_.is_primary_account); } // Check that the expected error is received if requesting an access token when
diff --git a/services/identity/public/cpp/account_state.cc b/services/identity/public/cpp/account_state.cc index 81b3aec..45ab366 100644 --- a/services/identity/public/cpp/account_state.cc +++ b/services/identity/public/cpp/account_state.cc
@@ -6,7 +6,8 @@ namespace identity { -AccountState::AccountState() : has_refresh_token(false) {} +AccountState::AccountState() + : has_refresh_token(false), is_primary_account(false) {} AccountState::AccountState(const AccountState& other) = default; AccountState::~AccountState() {}
diff --git a/services/identity/public/cpp/account_state.h b/services/identity/public/cpp/account_state.h index 2485537..519313c5 100644 --- a/services/identity/public/cpp/account_state.h +++ b/services/identity/public/cpp/account_state.h
@@ -15,6 +15,7 @@ ~AccountState(); bool has_refresh_token; + bool is_primary_account; }; } // namespace identity
diff --git a/services/identity/public/cpp/account_state_struct_traits.cc b/services/identity/public/cpp/account_state_struct_traits.cc index 2e8cee9..5bb5c17b 100644 --- a/services/identity/public/cpp/account_state_struct_traits.cc +++ b/services/identity/public/cpp/account_state_struct_traits.cc
@@ -12,6 +12,7 @@ identity::AccountState>::Read(identity::mojom::AccountState::DataView data, identity::AccountState* out) { out->has_refresh_token = data.has_refresh_token(); + out->is_primary_account = data.is_primary_account(); return true; }
diff --git a/services/identity/public/cpp/account_state_struct_traits.h b/services/identity/public/cpp/account_state_struct_traits.h index b6f258ca..162756c 100644 --- a/services/identity/public/cpp/account_state_struct_traits.h +++ b/services/identity/public/cpp/account_state_struct_traits.h
@@ -17,6 +17,10 @@ return r.has_refresh_token; } + static bool is_primary_account(const identity::AccountState& r) { + return r.is_primary_account; + } + static bool Read(identity::mojom::AccountState::DataView data, identity::AccountState* out); };
diff --git a/services/identity/public/interfaces/account_state.mojom b/services/identity/public/interfaces/account_state.mojom index 3ef655a..e3364c4 100644 --- a/services/identity/public/interfaces/account_state.mojom +++ b/services/identity/public/interfaces/account_state.mojom
@@ -10,4 +10,8 @@ struct AccountState { // Whether the account has a refresh token available. bool has_refresh_token; + + // Whether this account is the primary account (i.e., the account being used + // to sync). + bool is_primary_account; };
diff --git a/services/identity/public/interfaces/identity_manager.mojom b/services/identity/public/interfaces/identity_manager.mojom index 8683460..219bff43 100644 --- a/services/identity/public/interfaces/identity_manager.mojom +++ b/services/identity/public/interfaces/identity_manager.mojom
@@ -19,6 +19,14 @@ GetPrimaryAccountInfo() => (AccountInfo? account_info, AccountState account_state); + // Returns the AccountInfo for the Google account that serves as the user's + // primary account once this account is available (i.e., the user is signed + // in and a refresh token is available). |account_state| gives the current + // state of the account. Overlapping requests are permitted; all pending + // requests will be called back when the primary account is available. + GetPrimaryAccountWhenAvailable() => (AccountInfo account_info, + AccountState account_state); + // Returns the AccountInfo for the user's Google account corresponding to // |gaia_id|, or null if the user has such corresponding account. // |account_state| gives the current state of the account (relevant only if
diff --git a/services/metrics/OWNERS b/services/metrics/OWNERS new file mode 100644 index 0000000..3b1e068 --- /dev/null +++ b/services/metrics/OWNERS
@@ -0,0 +1,7 @@ +asvitkine@chromium.org +holte@chromium.org +isherman@chromium.org +mpearson@chromium.org +rkaplow@chromium.org + +# COMPONENT: Internals>Metrics
diff --git a/services/metrics/README.md b/services/metrics/README.md new file mode 100644 index 0000000..547e4a4 --- /dev/null +++ b/services/metrics/README.md
@@ -0,0 +1,6 @@ +The Metrics Service maintains and provides access to the browser metrics. + +This service is currently in development. At the moment, this is a placeholder +that allows Blink to use some interfaces that were previously in //components. + +The tracking bug is https://crbug.com/642762.
diff --git a/components/ukm/public/BUILD.gn b/services/metrics/public/cpp/BUILD.gn similarity index 77% rename from components/ukm/public/BUILD.gn rename to services/metrics/public/cpp/BUILD.gn index a791444..7e38abb 100644 --- a/components/ukm/public/BUILD.gn +++ b/services/metrics/public/cpp/BUILD.gn
@@ -4,22 +4,22 @@ import("//mojo/public/tools/bindings/mojom.gni") -component("public") { +component("metrics_cpp") { sources = [ + "metrics_export.h", "mojo_ukm_recorder.cc", "mojo_ukm_recorder.h", "ukm_entry_builder.cc", "ukm_entry_builder.h", - "ukm_export.h", "ukm_recorder.cc", "ukm_recorder.h", ] - defines = [ "UKM_IMPLEMENTATION" ] + defines = [ "METRICS_IMPLEMENTATION" ] public_deps = [ "//base", - "//components/ukm/public/interfaces", + "//services/metrics/public/interfaces", "//url", ]
diff --git a/services/metrics/public/cpp/metrics_export.h b/services/metrics/public/cpp/metrics_export.h new file mode 100644 index 0000000..16d835d --- /dev/null +++ b/services/metrics/public/cpp/metrics_export.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 SERVICES_METRICS_PUBLIC_CPP_METRICS_EXPORT_H_ +#define SERVICES_METRICS_PUBLIC_CPP_METRICS_EXPORT_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) + +#if defined(METRICS_IMPLEMENTATION) +#define METRICS_EXPORT __declspec(dllexport) +#else +#define METRICS_EXPORT __declspec(dllimport) +#endif // defined(METRICS_IMPLEMENTATION) + +#else // defined(WIN32) +#if defined(METRICS_IMPLEMENTATION) +#define METRICS_EXPORT __attribute__((visibility("default"))) +#else +#define METRICS_EXPORT +#endif +#endif + +#else // defined(COMPONENT_BUILD) +#define METRICS_EXPORT +#endif + +#endif // SERVICES_METRICS_PUBLIC_CPP_METRICS_EXPORT_H_
diff --git a/components/ukm/public/mojo_ukm_recorder.cc b/services/metrics/public/cpp/mojo_ukm_recorder.cc similarity index 90% rename from components/ukm/public/mojo_ukm_recorder.cc rename to services/metrics/public/cpp/mojo_ukm_recorder.cc index 2e07e8c..b6b3ae8 100644 --- a/components/ukm/public/mojo_ukm_recorder.cc +++ b/services/metrics/public/cpp/mojo_ukm_recorder.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 "components/ukm/public/mojo_ukm_recorder.h" +#include "services/metrics/public/cpp/mojo_ukm_recorder.h" #include <utility>
diff --git a/components/ukm/public/mojo_ukm_recorder.h b/services/metrics/public/cpp/mojo_ukm_recorder.h similarity index 73% rename from components/ukm/public/mojo_ukm_recorder.h rename to services/metrics/public/cpp/mojo_ukm_recorder.h index 2df0780..1a490e9 100644 --- a/components/ukm/public/mojo_ukm_recorder.h +++ b/services/metrics/public/cpp/mojo_ukm_recorder.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_UKM_PUBLIC_MOJO_UKM_RECORDER_H_ -#define COMPONENTS_UKM_PUBLIC_MOJO_UKM_RECORDER_H_ +#ifndef SERVICES_METRICS_PUBLIC_CPP_MOJO_UKM_RECORDER_H_ +#define SERVICES_METRICS_PUBLIC_CPP_MOJO_UKM_RECORDER_H_ -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" -#include "components/ukm/public/ukm_export.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/metrics_export.h" +#include "services/metrics/public/cpp/ukm_recorder.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" namespace ukm { @@ -25,7 +25,7 @@ * recorder.GetEntryBuilder(coordination_unit_id, "MyEvent"); * builder->AddMetric("MyMetric", metric_value); */ -class UKM_EXPORT MojoUkmRecorder : public UkmRecorder { +class METRICS_EXPORT MojoUkmRecorder : public UkmRecorder { public: explicit MojoUkmRecorder(mojom::UkmRecorderInterfacePtr interface); ~MojoUkmRecorder() override; @@ -42,4 +42,4 @@ } // namespace ukm -#endif // COMPONENTS_UKM_PUBLIC_MOJO_UKM_RECORDER_H_ +#endif // SERVICES_METRICS_PUBLIC_CPP_MOJO_UKM_RECORDER_H_
diff --git a/components/ukm/public/ukm_entry_builder.cc b/services/metrics/public/cpp/ukm_entry_builder.cc similarity index 86% rename from components/ukm/public/ukm_entry_builder.cc rename to services/metrics/public/cpp/ukm_entry_builder.cc index 72a227a..46f6d29 100644 --- a/components/ukm/public/ukm_entry_builder.cc +++ b/services/metrics/public/cpp/ukm_entry_builder.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 "components/ukm/public/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" #include <memory> #include "base/metrics/metrics_hashes.h" -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" namespace ukm {
diff --git a/components/ukm/public/ukm_entry_builder.h b/services/metrics/public/cpp/ukm_entry_builder.h similarity index 80% rename from components/ukm/public/ukm_entry_builder.h rename to services/metrics/public/cpp/ukm_entry_builder.h index 1c9facfe..c2250b4 100644 --- a/components/ukm/public/ukm_entry_builder.h +++ b/services/metrics/public/cpp/ukm_entry_builder.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 COMPONENTS_UKM_UKM_ENTRY_BUILDER_H -#define COMPONENTS_UKM_UKM_ENTRY_BUILDER_H +#ifndef SERVICES_METRICS_PUBLIC_CPP_UKM_ENTRY_BUILDER_H +#define SERVICES_METRICS_PUBLIC_CPP_UKM_ENTRY_BUILDER_H #include <string> #include "base/macros.h" -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" -#include "components/ukm/public/ukm_export.h" +#include "services/metrics/public/cpp/metrics_export.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" namespace ukm { @@ -29,7 +29,7 @@ // // When there exists an added metric, the builder will automatically add the // UkmEntry to UkmService upon destruction when going out of scope. -class UKM_EXPORT UkmEntryBuilder { +class METRICS_EXPORT UkmEntryBuilder { public: using AddEntryCallback = base::Callback<void(mojom::UkmEntryPtr)>; UkmEntryBuilder(const AddEntryCallback& callback, @@ -49,4 +49,4 @@ } // namespace ukm -#endif // COMPONENTS_UKM_UKM_ENTRY_BUILDER_H +#endif // SERVICES_METRICS_PUBLIC_CPP_UKM_ENTRY_BUILDER_H
diff --git a/components/ukm/public/ukm_recorder.cc b/services/metrics/public/cpp/ukm_recorder.cc similarity index 90% rename from components/ukm/public/ukm_recorder.cc rename to services/metrics/public/cpp/ukm_recorder.cc index 07a74fb..551c0128 100644 --- a/components/ukm/public/ukm_recorder.cc +++ b/services/metrics/public/cpp/ukm_recorder.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 "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "base/atomic_sequence_num.h" #include "base/bind.h" #include "base/feature_list.h" #include "base/memory/ptr_util.h" -#include "components/ukm/public/ukm_entry_builder.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" namespace ukm {
diff --git a/components/ukm/public/ukm_recorder.h b/services/metrics/public/cpp/ukm_recorder.h similarity index 87% rename from components/ukm/public/ukm_recorder.h rename to services/metrics/public/cpp/ukm_recorder.h index c4c18b97..1aadef76 100644 --- a/components/ukm/public/ukm_recorder.h +++ b/services/metrics/public/cpp/ukm_recorder.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 COMPONENTS_UKM_PUBLIC_UKM_RECORDER_H_ -#define COMPONENTS_UKM_PUBLIC_UKM_RECORDER_H_ +#ifndef SERVICES_METRICS_PUBLIC_CPP_UKM_RECORDER_H_ +#define SERVICES_METRICS_PUBLIC_CPP_UKM_RECORDER_H_ #include <stddef.h> @@ -13,9 +13,9 @@ #include "base/feature_list.h" #include "base/macros.h" #include "base/threading/thread_checker.h" -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" -#include "components/ukm/public/ukm_entry_builder.h" -#include "components/ukm/public/ukm_export.h" +#include "services/metrics/public/cpp/metrics_export.h" +#include "services/metrics/public/cpp/ukm_entry_builder.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" #include "url/gurl.h" class ContextualSearchRankerLoggerImpl; @@ -30,7 +30,7 @@ class MediaInternals; class RenderFrameImpl; class RenderWidgetHostLatencyTracker; -} +} // namespace content namespace resource_coordinator { class CoordinationUnitManager; @@ -47,7 +47,7 @@ namespace password_manager { class PasswordManagerMetricsRecorder; class PasswordFormMetricsRecorder; -} +} // namespace password_manager namespace ukm { @@ -56,12 +56,12 @@ class TestRecordingHelper; // This feature controls whether UkmService should be created. -UKM_EXPORT extern const base::Feature kUkmFeature; +METRICS_EXPORT extern const base::Feature kUkmFeature; typedef int64_t SourceId; // Interface for recording UKM -class UKM_EXPORT UkmRecorder { +class METRICS_EXPORT UkmRecorder { public: UkmRecorder(); virtual ~UkmRecorder(); @@ -125,4 +125,4 @@ } // namespace ukm -#endif // COMPONENTS_UKM_PUBLIC_UKM_RECORDER_H_ +#endif // SERVICES_METRICS_PUBLIC_CPP_UKM_RECORDER_H_
diff --git a/components/ukm/public/interfaces/BUILD.gn b/services/metrics/public/interfaces/BUILD.gn similarity index 100% rename from components/ukm/public/interfaces/BUILD.gn rename to services/metrics/public/interfaces/BUILD.gn
diff --git a/components/ukm/public/interfaces/OWNERS b/services/metrics/public/interfaces/OWNERS similarity index 100% rename from components/ukm/public/interfaces/OWNERS rename to services/metrics/public/interfaces/OWNERS
diff --git a/components/ukm/public/interfaces/ukm_interface.mojom b/services/metrics/public/interfaces/ukm_interface.mojom similarity index 100% rename from components/ukm/public/interfaces/ukm_interface.mojom rename to services/metrics/public/interfaces/ukm_interface.mojom
diff --git a/services/resource_coordinator/DEPS b/services/resource_coordinator/DEPS index f8703ea4..b47bded 100644 --- a/services/resource_coordinator/DEPS +++ b/services/resource_coordinator/DEPS
@@ -1,5 +1,5 @@ include_rules = [ - "+components/ukm/public", "+third_party/smhasher", + "+services/metrics/public", "+services/service_manager/public" ]
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h b/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h index cfc08ff..9025577 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h +++ b/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h
@@ -5,17 +5,13 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_OBSERVER_H_ #define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_GRAPH_OBSERVER_H_ -#include <memory> -#include <unordered_map> - #include "base/macros.h" -#include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" -#include "services/resource_coordinator/public/cpp/coordination_unit_id.h" -#include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/resource_coordinator/public/interfaces/coordination_unit.mojom.h" namespace resource_coordinator { +class CoordinationUnitImpl; + // An observer API for the coordination unit graph maintained by GRC. // // Observers are instantiated when the resource_coordinator service @@ -58,7 +54,7 @@ // Called whenever a |property| within the |coordination_unit|'s // internal property store has changed. virtual void OnPropertyChanged(const CoordinationUnitImpl* coordination_unit, - mojom::PropertyType property) {} + const mojom::PropertyPtr& property) {} // Called whenever parent-child relationship ends where the // |coordination_unit| was the parent and the |child_coordination_unit|. @@ -73,7 +69,7 @@ const CoordinationUnitImpl* parent_coordination_unit) {} // Called when the |coordination_unit| is about to be destroyed. - virtual void OnCoordinationUnitWillBeDestroyed( + virtual void OnBeforeCoordinationUnitDestroyed( const CoordinationUnitImpl* coordination_unit) {} private:
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer_unittest.cc b/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer_unittest.cc index 2239721..8b217b4 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer_unittest.cc +++ b/services/resource_coordinator/coordination_unit/coordination_unit_graph_observer_unittest.cc
@@ -3,11 +3,9 @@ // found in the LICENSE file. #include <string> -#include <utility> #include "base/memory/ptr_util.h" #include "base/process/process_handle.h" -#include "base/run_loop.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_factory.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" @@ -28,24 +26,24 @@ class TestCoordinationUnitGraphObserver : public CoordinationUnitGraphObserver { public: TestCoordinationUnitGraphObserver() - : on_child_added_count_(0u), - on_parent_added_count_(0u), - on_coordination_unit_created_count_(0u), - on_property_changed_count_(0u), - on_child_removed_count_(0u), - on_parent_removed_count_(0u), - on_coordination_unit_will_be_destroyed_count_(0u) {} + : child_added_count_(0u), + parent_added_count_(0u), + coordination_unit_created_count_(0u), + property_changed_count_(0u), + child_removed_count_(0u), + parent_removed_count_(0u), + coordination_unit_destroyed_count_(0u) {} - size_t on_child_added_count() { return on_child_added_count_; } - size_t on_parent_added_count() { return on_parent_added_count_; } - size_t on_coordination_unit_created_count() { - return on_coordination_unit_created_count_; + size_t child_added_count() { return child_added_count_; } + size_t parent_added_count() { return parent_added_count_; } + size_t coordination_unit_created_count() { + return coordination_unit_created_count_; } - size_t on_property_changed_count() { return on_property_changed_count_; } - size_t on_child_removed_count() { return on_child_removed_count_; } - size_t on_parent_removed_count() { return on_parent_removed_count_; } - size_t on_coordination_unit_will_be_destroyed_count() { - return on_coordination_unit_will_be_destroyed_count_; + size_t property_changed_count() { return property_changed_count_; } + size_t child_removed_count() { return child_removed_count_; } + size_t parent_removed_count() { return parent_removed_count_; } + size_t coordination_unit_destroyed_count() { + return coordination_unit_destroyed_count_; } // Overridden from CoordinationUnitGraphObserver. @@ -54,45 +52,45 @@ } void OnCoordinationUnitCreated( const CoordinationUnitImpl* coordination_unit) override { - ++on_coordination_unit_created_count_; + ++coordination_unit_created_count_; } void OnChildAdded( const CoordinationUnitImpl* coordination_unit, const CoordinationUnitImpl* child_coordination_unit) override { - ++on_child_added_count_; + ++child_added_count_; } void OnParentAdded( const CoordinationUnitImpl* coordination_unit, const CoordinationUnitImpl* parent_coordination_unit) override { - ++on_parent_added_count_; + ++parent_added_count_; } void OnPropertyChanged(const CoordinationUnitImpl* coordination_unit, - mojom::PropertyType property) override { - ++on_property_changed_count_; + const mojom::PropertyPtr& property) override { + ++property_changed_count_; } void OnChildRemoved( const CoordinationUnitImpl* coordination_unit, const CoordinationUnitImpl* former_child_coordination_unit) override { - ++on_child_removed_count_; + ++child_removed_count_; } void OnParentRemoved( const CoordinationUnitImpl* coordination_unit, const CoordinationUnitImpl* former_parent_coordination_unit) override { - ++on_parent_removed_count_; + ++parent_removed_count_; } - void OnCoordinationUnitWillBeDestroyed( + void OnBeforeCoordinationUnitDestroyed( const CoordinationUnitImpl* coordination_unit) override { - ++on_coordination_unit_will_be_destroyed_count_; + ++coordination_unit_destroyed_count_; } private: - size_t on_child_added_count_; - size_t on_parent_added_count_; - size_t on_coordination_unit_created_count_; - size_t on_property_changed_count_; - size_t on_child_removed_count_; - size_t on_parent_removed_count_; - size_t on_coordination_unit_will_be_destroyed_count_; + size_t child_added_count_; + size_t parent_added_count_; + size_t coordination_unit_created_count_; + size_t property_changed_count_; + size_t child_removed_count_; + size_t parent_removed_count_; + size_t coordination_unit_destroyed_count_; }; } // namespace @@ -129,7 +127,7 @@ root_frame_coordination_unit.get()); coordination_unit_manager().OnCoordinationUnitCreated( frame_coordination_unit.get()); - EXPECT_EQ(2u, observer->on_coordination_unit_created_count()); + EXPECT_EQ(2u, observer->coordination_unit_created_count()); // The registered observer will only observe the events that happen to // |root_frame_coordination_unit| and |frame_coordination_unit| because @@ -141,8 +139,8 @@ // OnAddChild will called for |root_frame_coordination_unit| and // OnAddParent will called for |frame_coordination_unit|. root_frame_coordination_unit->AddChild(frame_coordination_unit->id()); - EXPECT_EQ(1u, observer->on_child_added_count()); - EXPECT_EQ(3u, observer->on_parent_added_count()); + EXPECT_EQ(1u, observer->child_added_count()); + EXPECT_EQ(3u, observer->parent_added_count()); // The registered observer will only observe the events that happen to // |root_frame_coordination_unit| and |frame_coordination_unit| because @@ -154,26 +152,26 @@ // OnRemoveChild will called for |root_frame_coordination_unit| and // OnRemoveParent will called for |frame_coordination_unit|. root_frame_coordination_unit->RemoveChild(frame_coordination_unit->id()); - EXPECT_EQ(1u, observer->on_child_removed_count()); - EXPECT_EQ(3u, observer->on_parent_removed_count()); + EXPECT_EQ(1u, observer->child_removed_count()); + EXPECT_EQ(3u, observer->parent_removed_count()); // The registered observer will only observe the events that happen to // |root_frame_coordination_unit| and |frame_coordination_unit| because // they are CoordinationUnitType::kFrame, so OnPropertyChanged // will only be called for |root_frame_coordination_unit|. - root_frame_coordination_unit->SetProperty(mojom::PropertyType::kTest, - base::Value(42)); - process_coordination_unit->SetProperty(mojom::PropertyType::kTest, - base::Value(42)); - EXPECT_EQ(1u, observer->on_property_changed_count()); + root_frame_coordination_unit->SetProperty(mojom::Property::New( + mojom::PropertyType::kTest, base::MakeUnique<base::Value>(42))); + process_coordination_unit->SetProperty(mojom::Property::New( + mojom::PropertyType::kTest, base::MakeUnique<base::Value>(42))); + EXPECT_EQ(1u, observer->property_changed_count()); - coordination_unit_manager().OnCoordinationUnitWillBeDestroyed( + coordination_unit_manager().OnBeforeCoordinationUnitDestroyed( process_coordination_unit.get()); - coordination_unit_manager().OnCoordinationUnitWillBeDestroyed( + coordination_unit_manager().OnBeforeCoordinationUnitDestroyed( root_frame_coordination_unit.get()); - coordination_unit_manager().OnCoordinationUnitWillBeDestroyed( + coordination_unit_manager().OnBeforeCoordinationUnitDestroyed( frame_coordination_unit.get()); - EXPECT_EQ(2u, observer->on_coordination_unit_will_be_destroyed_count()); + EXPECT_EQ(2u, observer->coordination_unit_destroyed_count()); } } // namespace resource_coordinator
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_impl.cc b/services/resource_coordinator/coordination_unit/coordination_unit_impl.cc index 50b6628e..da6840ae 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_impl.cc +++ b/services/resource_coordinator/coordination_unit/coordination_unit_impl.cc
@@ -4,9 +4,7 @@ #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" -#include <memory> #include <unordered_map> -#include <utility> #include "base/strings/string_number_conversions.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -15,6 +13,11 @@ namespace resource_coordinator { +#define NOTIFY_OBSERVERS(observers, Method, ...) \ + for (auto& observer : observers) { \ + observer.Method(__VA_ARGS__); \ + } + namespace { using CUIDMap = std::unordered_map<CoordinationUnitID, CoordinationUnitImpl*>; @@ -159,9 +162,7 @@ children_.count(child) ? false : children_.insert(child).second; if (success) { - for (auto& observer : observers_) { - observer.OnChildAdded(this, child); - } + NOTIFY_OBSERVERS(observers_, OnChildAdded, this, child); } return success; @@ -191,9 +192,7 @@ bool success = children_removed > 0; if (success) { - for (auto& observer : observers_) { - observer.OnChildRemoved(this, child); - } + NOTIFY_OBSERVERS(observers_, OnChildRemoved, this, child); } return success; @@ -203,9 +202,7 @@ DCHECK_EQ(0u, parents_.count(parent)); parents_.insert(parent); - for (auto& observer : observers_) { - observer.OnParentAdded(this, parent); - } + NOTIFY_OBSERVERS(observers_, OnParentAdded, this, parent); RecalcCoordinationPolicy(); } @@ -216,9 +213,7 @@ // TODO(matthalp, oysteine) should this go before or // after RecalcCoordinationPolicy? - for (auto& observer : observers_) { - observer.OnParentRemoved(this, parent); - } + NOTIFY_OBSERVERS(observers_, OnParentRemoved, this, parent); RecalcCoordinationPolicy(); } @@ -305,40 +300,37 @@ } base::Value CoordinationUnitImpl::GetProperty( - mojom::PropertyType property) const { - auto value_it = property_store_.find(property); + const mojom::PropertyType property_type) const { + auto value_it = properties_.find(property_type); - return value_it != property_store_.end() ? value_it->second : base::Value(); + return value_it != properties_.end() ? value_it->second : base::Value(); } -void CoordinationUnitImpl::ClearProperty(mojom::PropertyType property) { - property_store_.erase(property); +void CoordinationUnitImpl::ClearProperty( + const mojom::PropertyType property_type) { + properties_.erase(property_type); } void CoordinationUnitImpl::SetProperty(mojom::PropertyPtr property) { - SetProperty(property->property, *property->value); + SetProperty(property->property_type, *property->value); + PropagateProperty(property); + NOTIFY_OBSERVERS(observers_, OnPropertyChanged, this, property); } -void CoordinationUnitImpl::SetProperty(mojom::PropertyType property, +void CoordinationUnitImpl::SetProperty(mojom::PropertyType property_type, base::Value value) { // setting a property with an empty value is effectively clearing the // value from storage if (value.IsType(base::Value::Type::NONE)) { - ClearProperty(property); + ClearProperty(property_type); return; } - property_store_[property] = value; - - for (auto& observer : observers_) { - observer.OnPropertyChanged(this, property); - } + properties_[property_type] = value; } -void CoordinationUnitImpl::WillBeDestroyed() { - for (auto& observer : observers_) { - observer.OnCoordinationUnitWillBeDestroyed(this); - } +void CoordinationUnitImpl::BeforeDestroyed() { + NOTIFY_OBSERVERS(observers_, OnBeforeCoordinationUnitDestroyed, this); } void CoordinationUnitImpl::AddObserver( @@ -351,32 +343,4 @@ observers_.RemoveObserver(observer); } -// static -bool CoordinationUnitImpl::IsCoordinationUnitType( - const CoordinationUnitImpl* coordination_unit, - CoordinationUnitType type) { - return coordination_unit->id().type == type; -} - -// static -bool CoordinationUnitImpl::IsFrameCoordinationUnit( - const CoordinationUnitImpl* coordination_unit) { - return IsCoordinationUnitType(coordination_unit, - CoordinationUnitType::kFrame); -} - -// static -bool CoordinationUnitImpl::IsProcessCoordinationUnit( - const CoordinationUnitImpl* coordination_unit) { - return IsCoordinationUnitType(coordination_unit, - CoordinationUnitType::kProcess); -} - -// static -bool CoordinationUnitImpl::IsWebContentsCoordinationUnit( - const CoordinationUnitImpl* coordination_unit) { - return IsCoordinationUnitType(coordination_unit, - CoordinationUnitType::kWebContents); -} - } // namespace resource_coordinator
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/coordination_unit_impl.h index 2e69cc80..62cdb2e 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_impl.h +++ b/services/resource_coordinator/coordination_unit/coordination_unit_impl.h
@@ -5,13 +5,8 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_IMPL_H_ #define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_COORDINATION_UNIT_IMPL_H_ -#include <list> -#include <map> #include <memory> #include <set> -#include <unordered_map> -#include <utility> -#include <vector> #include "base/callback.h" #include "base/observer_list.h" @@ -20,7 +15,6 @@ #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/strong_binding.h" -#include "services/resource_coordinator/public/cpp/coordination_unit_id.h" #include "services/resource_coordinator/public/cpp/coordination_unit_types.h" #include "services/resource_coordinator/public/interfaces/coordination_unit.mojom.h" #include "services/resource_coordinator/public/interfaces/coordination_unit_provider.mojom.h" @@ -37,46 +31,30 @@ std::unique_ptr<service_manager::ServiceContextRef> service_ref); ~CoordinationUnitImpl() override; - // Utility functions for working with CoordinationUnitImpl instances. - static bool IsCoordinationUnitType( - const CoordinationUnitImpl* coordination_unit, - CoordinationUnitType type); - static bool IsFrameCoordinationUnit( - const CoordinationUnitImpl* coordination_unit); - static bool IsProcessCoordinationUnit( - const CoordinationUnitImpl* coordination_unit); - static bool IsWebContentsCoordinationUnit( - const CoordinationUnitImpl* coordination_unit); - - // Return all of the reachable |CoordinationUnitImpl| instances - // of type |CoordinationUnitType|. Note that a callee should - // never be associated with itself. - virtual std::set<CoordinationUnitImpl*> GetAssociatedCoordinationUnitsOfType( - CoordinationUnitType type); - - // Recalculate property internally. - virtual void RecalculateProperty(mojom::PropertyType property) {} - // Propagate property change to relevant |CoordinationUnitImpl| instances - // by invoking their their |RecalculateProperty|. - virtual void PropagateProperty(mojom::PropertyType property) {} - // Overridden from mojom::CoordinationUnit: void SendEvent(mojom::EventPtr event) override; void GetID(const GetIDCallback& callback) override; void AddBinding(mojom::CoordinationUnitRequest request) override; void AddChild(const CoordinationUnitID& child_id) override; void RemoveChild(const CoordinationUnitID& child_id) override; + void SetProperty(mojom::PropertyPtr property) override; + // TODO(crbug.com/691886) Consider removing this. void SetCoordinationPolicyCallback( mojom::CoordinationPolicyCallbackPtr callback) override; - void SetProperty(mojom::PropertyPtr property) override; + + // Return all of the reachable |CoordinationUnitImpl| instances + // of type |CoordinationUnitType|. Note that a callee should + // never be associated with itself. + virtual std::set<CoordinationUnitImpl*> GetAssociatedCoordinationUnitsOfType( + CoordinationUnitType type); + // Recalculate property internally. + virtual void RecalculateProperty(const mojom::PropertyType property_type) {} // Operations performed on the internal key-value store. - void ClearProperty(mojom::PropertyType property); - base::Value GetProperty(mojom::PropertyType property) const; - void SetProperty(mojom::PropertyType property, base::Value value); - + base::Value GetProperty(const mojom::PropertyType property_type) const; + void ClearProperty(const mojom::PropertyType property_type); // Methods utilized by the |CoordinationUnitGraphObserver| framework. - void WillBeDestroyed(); + void BeforeDestroyed(); void AddObserver(CoordinationUnitGraphObserver* observer); void RemoveObserver(CoordinationUnitGraphObserver* observer); @@ -84,15 +62,14 @@ const CoordinationUnitID& id() const { return id_; } const std::set<CoordinationUnitImpl*>& children() const { return children_; } const std::set<CoordinationUnitImpl*>& parents() const { return parents_; } - const std::unordered_map<mojom::PropertyType, base::Value>& - property_store_for_testing() const { - return property_store_; + const std::map<mojom::PropertyType, base::Value>& properties_for_testing() + const { + return properties_; } protected: - const CoordinationUnitID id_; - std::set<CoordinationUnitImpl*> children_; - std::set<CoordinationUnitImpl*> parents_; + // Propagate property change to relevant |CoordinationUnitImpl| instances. + virtual void PropagateProperty(const mojom::PropertyPtr& property) {} // Coordination unit graph traversal helper functions. std::set<CoordinationUnitImpl*> GetChildCoordinationUnitsOfType( @@ -100,18 +77,11 @@ std::set<CoordinationUnitImpl*> GetParentCoordinationUnitsOfType( CoordinationUnitType type); + const CoordinationUnitID id_; + std::set<CoordinationUnitImpl*> children_; + std::set<CoordinationUnitImpl*> parents_; + private: - bool AddChild(CoordinationUnitImpl* child); - bool RemoveChild(CoordinationUnitImpl* child); - void AddParent(CoordinationUnitImpl* parent); - void RemoveParent(CoordinationUnitImpl* parent); - bool HasParent(CoordinationUnitImpl* unit); - bool HasChild(CoordinationUnitImpl* unit); - void RecalcCoordinationPolicy(); - void UnregisterCoordinationPolicyCallback(); - - std::unordered_map<mojom::PropertyType, base::Value> property_store_; - enum StateFlags : uint8_t { kTestState, kTabVisible, @@ -119,7 +89,20 @@ kNetworkIdle, kNumStateFlags }; + + bool AddChild(CoordinationUnitImpl* child); + bool RemoveChild(CoordinationUnitImpl* child); + void AddParent(CoordinationUnitImpl* parent); + void RemoveParent(CoordinationUnitImpl* parent); + bool HasParent(CoordinationUnitImpl* unit); + bool HasChild(CoordinationUnitImpl* unit); + void SetProperty(mojom::PropertyType property_type, base::Value value); bool SelfOrParentHasFlagSet(StateFlags state); + // TODO(crbug.com/691886) Consider removing these. + void RecalcCoordinationPolicy(); + void UnregisterCoordinationPolicyCallback(); + + std::map<mojom::PropertyType, base::Value> properties_; std::unique_ptr<service_manager::ServiceContextRef> service_ref_; mojo::BindingSet<mojom::CoordinationUnit> bindings_; @@ -129,6 +112,7 @@ base::ObserverList<CoordinationUnitGraphObserver> observers_; + // TODO(crbug.com/691886) Consider switching properties_. base::Optional<bool> state_flags_[kNumStateFlags]; DISALLOW_COPY_AND_ASSIGN(CoordinationUnitImpl);
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_impl_unittest.cc b/services/resource_coordinator/coordination_unit/coordination_unit_impl_unittest.cc index fd21706..03369f18 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_impl_unittest.cc +++ b/services/resource_coordinator/coordination_unit/coordination_unit_impl_unittest.cc
@@ -2,10 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <memory> #include <string> -#include <utility> -#include <vector> #include "base/bind.h" #include "base/message_loop/message_loop.h" @@ -216,19 +213,21 @@ coordination_unit->GetProperty(mojom::PropertyType::kTest)); // An empty value should be able to set a property - coordination_unit->SetProperty(mojom::PropertyType::kTest, base::Value()); - EXPECT_EQ(0u, coordination_unit->property_store_for_testing().size()); + coordination_unit->SetProperty(mojom::Property::New( + mojom::PropertyType::kTest, base::MakeUnique<base::Value>())); + EXPECT_EQ(0u, coordination_unit->properties_for_testing().size()); base::Value int_val(41); // Perform a valid storage property set - coordination_unit->SetProperty(mojom::PropertyType::kTest, int_val); - EXPECT_EQ(1u, coordination_unit->property_store_for_testing().size()); + coordination_unit->SetProperty(mojom::Property::New( + mojom::PropertyType::kTest, base::MakeUnique<base::Value>(int_val))); + EXPECT_EQ(1u, coordination_unit->properties_for_testing().size()); EXPECT_EQ(int_val, coordination_unit->GetProperty(mojom::PropertyType::kTest)); coordination_unit->ClearProperty(mojom::PropertyType::kTest); - EXPECT_EQ(0u, coordination_unit->property_store_for_testing().size()); + EXPECT_EQ(0u, coordination_unit->properties_for_testing().size()); } TEST_F(CoordinationUnitImplTest,
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_manager.cc b/services/resource_coordinator/coordination_unit/coordination_unit_manager.cc index c0e3c01..c6b28f3d 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_manager.cc +++ b/services/resource_coordinator/coordination_unit/coordination_unit_manager.cc
@@ -9,8 +9,8 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" -#include "components/ukm/public/mojo_ukm_recorder.h" -#include "components/ukm/public/ukm_recorder.h" +#include "services/metrics/public/cpp/mojo_ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_recorder.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_graph_observer.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.h" @@ -50,9 +50,9 @@ } } -void CoordinationUnitManager::OnCoordinationUnitWillBeDestroyed( +void CoordinationUnitManager::OnBeforeCoordinationUnitDestroyed( CoordinationUnitImpl* coordination_unit) { - coordination_unit->WillBeDestroyed(); + coordination_unit->BeforeDestroyed(); } std::unique_ptr<ukm::UkmEntryBuilder>
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_manager.h b/services/resource_coordinator/coordination_unit/coordination_unit_manager.h index 2f3bcba..b1cca54 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_manager.h +++ b/services/resource_coordinator/coordination_unit/coordination_unit_manager.h
@@ -43,7 +43,7 @@ void RegisterObserver( std::unique_ptr<CoordinationUnitGraphObserver> observer); void OnCoordinationUnitCreated(CoordinationUnitImpl* coordination_unit); - void OnCoordinationUnitWillBeDestroyed( + void OnBeforeCoordinationUnitDestroyed( CoordinationUnitImpl* coordination_unit); std::unique_ptr<ukm::UkmEntryBuilder> CreateUkmEntryBuilder(
diff --git a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc b/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc index 845ec91a6..a73f88e 100644 --- a/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc +++ b/services/resource_coordinator/coordination_unit/coordination_unit_provider_impl.cc
@@ -42,7 +42,7 @@ coordination_unit_manager_->OnCoordinationUnitCreated(coordination_unit_impl); coordination_unit_binding->set_connection_error_handler( - base::Bind(&CoordinationUnitManager::OnCoordinationUnitWillBeDestroyed, + base::Bind(&CoordinationUnitManager::OnBeforeCoordinationUnitDestroyed, base::Unretained(coordination_unit_manager_), base::Unretained(coordination_unit_impl))); }
diff --git a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc b/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc index a64d1c1..a788ba8 100644 --- a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc +++ b/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.cc
@@ -4,16 +4,8 @@ #include "services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h" -#include <utility> - -namespace service_manager { -class ServiceContextRef; -} - namespace resource_coordinator { -struct CoordinationUnitID; - FrameCoordinationUnitImpl::FrameCoordinationUnitImpl( const CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceContextRef> service_ref)
diff --git a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h index 0bfc24d0..39d3fae 100644 --- a/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h +++ b/services/resource_coordinator/coordination_unit/frame_coordination_unit_impl.h
@@ -5,16 +5,10 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ #define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_FRAME_COORDINATION_UNIT_IMPL_H_ -#include <memory> #include <set> #include "base/macros.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" -#include "services/resource_coordinator/public/interfaces/coordination_unit.mojom.h" - -namespace service_manager { -class ServiceContextRef; -} namespace resource_coordinator {
diff --git a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc b/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc index b66777f..f2894a1 100644 --- a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc +++ b/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.cc
@@ -4,11 +4,8 @@ #include "services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h" -#include <utility> - #include "base/process/process.h" #include "base/process/process_handle.h" -#include "base/process/process_metrics.h" #include "base/time/time.h" #include "base/values.h" @@ -20,14 +17,8 @@ #include <windows.h> #endif -namespace service_manager { -class ServiceContextRef; -} - namespace resource_coordinator { -struct CoordinationUnitID; - namespace { const int kCPUProfilingIntervalInSeconds = 5; @@ -92,17 +83,24 @@ } } +void ProcessCoordinationUnitImpl::PropagateProperty( + const mojom::PropertyPtr& property) { + mojom::PropertyType property_type = property->property_type; + // Trigger tab coordination units to recalculate their CPU usage. + if (property_type == mojom::PropertyType::kCPUUsage) { + for (auto* tab_coordination_unit : GetAssociatedCoordinationUnitsOfType( + CoordinationUnitType::kWebContents)) { + tab_coordination_unit->RecalculateProperty( + mojom::PropertyType::kCPUUsage); + } + } +} + void ProcessCoordinationUnitImpl::MeasureProcessCPUUsage() { double cpu_usage = process_metrics_->GetPlatformIndependentCPUUsage(); - SetProperty(mojom::PropertyType::kCPUUsage, base::Value(cpu_usage)); - - // Trigger tab coordination units to recalculate their CPU usage. - // TODO(matthalp): Move propagation functionality into a separate, - // more generalized method to support other property changes. - for (auto* tab : GetAssociatedCoordinationUnitsOfType( - CoordinationUnitType::kWebContents)) { - tab->RecalculateProperty(mojom::PropertyType::kCPUUsage); - } + mojom::PropertyPtr property = mojom::Property::New( + mojom::PropertyType::kCPUUsage, base::MakeUnique<base::Value>(cpu_usage)); + SetProperty(std::move(property)); repeating_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kCPUProfilingIntervalInSeconds),
diff --git a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h index bbe57211..b519c5d63 100644 --- a/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h +++ b/services/resource_coordinator/coordination_unit/process_coordination_unit_impl.h
@@ -5,25 +5,15 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ #define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_PROCESS_COORDINATION_UNIT_IMPL_H_ -#include <stdint.h> - -#include <memory> #include <set> #include "base/macros.h" #include "base/process/process_metrics.h" #include "base/timer/timer.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" -#include "services/resource_coordinator/public/interfaces/coordination_unit.mojom.h" - -namespace service_manager { -class ServiceContextRef; -} namespace resource_coordinator { -struct CoordinationUnitID; - class ProcessCoordinationUnitImpl : public CoordinationUnitImpl { public: ProcessCoordinationUnitImpl( @@ -35,9 +25,12 @@ std::set<CoordinationUnitImpl*> GetAssociatedCoordinationUnitsOfType( CoordinationUnitType type) override; + private: + // CoordinationUnitImpl implementation. + void PropagateProperty(const mojom::PropertyPtr& property) override; + void MeasureProcessCPUUsage(); - private: std::unique_ptr<base::ProcessMetrics> process_metrics_; base::OneShotTimer repeating_timer_;
diff --git a/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.cc b/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.cc index e5b840ab..36ad583 100644 --- a/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.cc +++ b/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.cc
@@ -4,16 +4,8 @@ #include "services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.h" -#include <utility> - -namespace service_manager { -class ServiceContextRef; -} - namespace resource_coordinator { -struct CoordinationUnitID; - WebContentsCoordinationUnitImpl::WebContentsCoordinationUnitImpl( const CoordinationUnitID& id, std::unique_ptr<service_manager::ServiceContextRef> service_ref) @@ -74,10 +66,13 @@ } void WebContentsCoordinationUnitImpl::RecalculateProperty( - mojom::PropertyType property_type) { + const mojom::PropertyType property_type) { if (property_type == mojom::PropertyType::kCPUUsage) { double cpu_usage = CalculateCPUUsage(); - SetProperty(mojom::PropertyType::kCPUUsage, base::Value(cpu_usage)); + mojom::PropertyPtr property = + mojom::Property::New(mojom::PropertyType::kCPUUsage, + base::MakeUnique<base::Value>(cpu_usage)); + SetProperty(std::move(property)); } }
diff --git a/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.h b/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.h index 35523d8..d3aa8f4 100644 --- a/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.h +++ b/services/resource_coordinator/coordination_unit/web_contents_coordination_unit_impl.h
@@ -5,23 +5,13 @@ #ifndef SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_WEB_CONTENTS_COORDINATION_UNIT_IMPL_H_ #define SERVICES_RESOURCE_COORDINATOR_COORDINATION_UNIT_WEB_CONTENTS_COORDINATION_UNIT_IMPL_H_ -#include <stdint.h> - -#include <memory> #include <set> #include "base/macros.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_impl.h" -#include "services/resource_coordinator/public/interfaces/coordination_unit.mojom.h" - -namespace service_manager { -class ServiceContextRef; -} namespace resource_coordinator { -struct CoordinationUnitID; - class WebContentsCoordinationUnitImpl : public CoordinationUnitImpl { public: WebContentsCoordinationUnitImpl( @@ -32,7 +22,7 @@ // CoordinationUnitImpl implementation. std::set<CoordinationUnitImpl*> GetAssociatedCoordinationUnitsOfType( CoordinationUnitType type) override; - void RecalculateProperty(mojom::PropertyType property_type) override; + void RecalculateProperty(const mojom::PropertyType property_type) override; private: double CalculateCPUUsage();
diff --git a/services/resource_coordinator/public/interfaces/BUILD.gn b/services/resource_coordinator/public/interfaces/BUILD.gn index 1b4026de..a11ab082 100644 --- a/services/resource_coordinator/public/interfaces/BUILD.gn +++ b/services/resource_coordinator/public/interfaces/BUILD.gn
@@ -19,8 +19,8 @@ ] public_deps = [ - "//components/ukm/public/interfaces:interfaces", "//mojo/common:common_custom_types", + "//services/metrics/public/interfaces", ] component_output_prefix = "resource_coordinator_public_interfaces_internal"
diff --git a/services/resource_coordinator/public/interfaces/coordination_unit.mojom b/services/resource_coordinator/public/interfaces/coordination_unit.mojom index 16a1b54..57ead38 100644 --- a/services/resource_coordinator/public/interfaces/coordination_unit.mojom +++ b/services/resource_coordinator/public/interfaces/coordination_unit.mojom
@@ -40,7 +40,7 @@ // Key-value pair that corresponds to an entry in the CoordinationUnitImpl's // internal key-value store struct Property { - PropertyType property; + PropertyType property_type; mojo.common.mojom.Value value; };
diff --git a/services/resource_coordinator/public/interfaces/service_callbacks.mojom b/services/resource_coordinator/public/interfaces/service_callbacks.mojom index 62d066c..e7d3340 100644 --- a/services/resource_coordinator/public/interfaces/service_callbacks.mojom +++ b/services/resource_coordinator/public/interfaces/service_callbacks.mojom
@@ -4,7 +4,7 @@ module resource_coordinator.mojom; -import "components/ukm/public/interfaces/ukm_interface.mojom"; +import "services/metrics/public/interfaces/ukm_interface.mojom"; // This class is intended to provide an interface to register mojo interfaces // that are not currently accessible to the resource_coordinator service. For
diff --git a/services/resource_coordinator/resource_coordinator_service.h b/services/resource_coordinator/resource_coordinator_service.h index c88e81e3..27aae38 100644 --- a/services/resource_coordinator/resource_coordinator_service.h +++ b/services/resource_coordinator/resource_coordinator_service.h
@@ -11,7 +11,7 @@ #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "components/ukm/public/mojo_ukm_recorder.h" +#include "services/metrics/public/cpp/mojo_ukm_recorder.h" #include "services/resource_coordinator/coordination_unit/coordination_unit_manager.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h"
diff --git a/services/resource_coordinator/service_callbacks_impl.cc b/services/resource_coordinator/service_callbacks_impl.cc index acefed1..31cfb25 100644 --- a/services/resource_coordinator/service_callbacks_impl.cc +++ b/services/resource_coordinator/service_callbacks_impl.cc
@@ -7,7 +7,7 @@ #include <utility> #include "base/memory/ptr_util.h" -#include "components/ukm/public/mojo_ukm_recorder.h" +#include "services/metrics/public/cpp/mojo_ukm_recorder.h" #include "services/resource_coordinator/resource_coordinator_service.h" #include "services/service_manager/public/cpp/service_context_ref.h"
diff --git a/services/resource_coordinator/service_callbacks_impl.h b/services/resource_coordinator/service_callbacks_impl.h index 936be69..50c00513 100644 --- a/services/resource_coordinator/service_callbacks_impl.h +++ b/services/resource_coordinator/service_callbacks_impl.h
@@ -7,9 +7,9 @@ #include <memory> -#include "components/ukm/public/interfaces/ukm_interface.mojom.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "services/metrics/public/interfaces/ukm_interface.mojom.h" #include "services/resource_coordinator/public/interfaces/service_callbacks.mojom.h" #include "services/service_manager/public/cpp/bind_source_info.h"
diff --git a/services/resource_coordinator/tracing/recorder.cc b/services/resource_coordinator/tracing/recorder.cc index fa4f449..7997cb1 100644 --- a/services/resource_coordinator/tracing/recorder.cc +++ b/services/resource_coordinator/tracing/recorder.cc
@@ -31,7 +31,7 @@ void Recorder::AddChunk(const std::string& chunk) { if (chunk.empty()) return; - if (!background_task_runner_->RunsTasksOnCurrentThread()) { + if (!background_task_runner_->RunsTasksInCurrentSequence()) { background_task_runner_->PostTask( FROM_HERE, base::BindRepeating(&Recorder::AddChunk, weak_factory_.GetWeakPtr(), chunk));
diff --git a/services/resource_coordinator/tracing/recorder.h b/services/resource_coordinator/tracing/recorder.h index 7bc5bf8..1530c6c 100644 --- a/services/resource_coordinator/tracing/recorder.h +++ b/services/resource_coordinator/tracing/recorder.h
@@ -43,13 +43,13 @@ const std::string& data() const { // All access to |data_| should be done on the background thread. - DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); return data_; } void clear_data() { // All access to |data_| should be done on the background thread. - DCHECK(background_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); data_.clear(); }
diff --git a/services/service_manager/embedder/embedded_service_runner.cc b/services/service_manager/embedder/embedded_service_runner.cc index ab0fe87..66cb85e3 100644 --- a/services/service_manager/embedder/embedded_service_runner.cc +++ b/services/service_manager/embedder/embedded_service_runner.cc
@@ -64,7 +64,7 @@ if (!service_task_runner_) return; // Any extant ServiceContexts must be destroyed on the application thread. - if (service_task_runner_->RunsTasksOnCurrentThread()) { + if (service_task_runner_->RunsTasksInCurrentSequence()) { QuitOnServiceSequence(); } else { service_task_runner_->PostTask( @@ -83,7 +83,7 @@ void BindServiceRequestOnServiceSequence( service_manager::mojom::ServiceRequest request) { - DCHECK(service_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(service_task_runner_->RunsTasksInCurrentSequence()); int instance_id = next_instance_id_++; @@ -99,7 +99,7 @@ } void OnInstanceLost(int instance_id) { - DCHECK(service_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(service_task_runner_->RunsTasksInCurrentSequence()); auto id_iter = id_to_context_map_.find(instance_id); CHECK(id_iter != id_to_context_map_.end()); @@ -115,10 +115,10 @@ } void QuitOnServiceSequence() { - DCHECK(service_task_runner_->RunsTasksOnCurrentThread()); + DCHECK(service_task_runner_->RunsTasksInCurrentSequence()); contexts_.clear(); - if (quit_task_runner_->RunsTasksOnCurrentThread()) { + if (quit_task_runner_->RunsTasksInCurrentSequence()) { QuitOnRunnerThread(); } else { quit_task_runner_->PostTask(
diff --git a/services/service_manager/public/cpp/service_context_ref.cc b/services/service_manager/public/cpp/service_context_ref.cc index cf28aeb..7df2bbc 100644 --- a/services/service_manager/public/cpp/service_context_ref.cc +++ b/services/service_manager/public/cpp/service_context_ref.cc
@@ -27,7 +27,7 @@ ~ServiceContextRefImpl() override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (service_task_runner_->RunsTasksOnCurrentThread() && factory_) { + if (service_task_runner_->RunsTasksInCurrentSequence() && factory_) { factory_->Release(); } else { service_task_runner_->PostTask( @@ -40,7 +40,7 @@ std::unique_ptr<ServiceContextRef> Clone() override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (service_task_runner_->RunsTasksOnCurrentThread() && factory_) { + if (service_task_runner_->RunsTasksInCurrentSequence() && factory_) { factory_->AddRef(); } else { service_task_runner_->PostTask(
diff --git a/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImplGmsCore.java b/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImplGmsCore.java index d109df4..68249c2 100644 --- a/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImplGmsCore.java +++ b/services/shape_detection/android/java/src/org/chromium/shape_detection/FaceDetectionImplGmsCore.java
@@ -86,17 +86,13 @@ faceArray[i] = new FaceDetectionResult(); final Face face = faces.valueAt(i); - final PointF corner = face.getPosition(); - faceArray[i].boundingBox = new RectF(); - faceArray[i].boundingBox.x = corner.x; - faceArray[i].boundingBox.y = corner.y; - faceArray[i].boundingBox.width = face.getWidth(); - faceArray[i].boundingBox.height = face.getHeight(); - final List<Landmark> landmarks = face.getLandmarks(); ArrayList<org.chromium.shape_detection.mojom.Landmark> mojoLandmarks = new ArrayList<org.chromium.shape_detection.mojom.Landmark>(landmarks.size()); + int leftEyeIndex = -1; + int rightEyeIndex = -1; + int bottomMouthIndex = -1; for (int j = 0; j < landmarks.size(); j++) { final Landmark landmark = landmarks.get(j); final int landmarkType = landmark.getType(); @@ -110,10 +106,43 @@ mojoLandmark.type = landmarkType == Landmark.BOTTOM_MOUTH ? LandmarkType.MOUTH : LandmarkType.EYE; mojoLandmarks.add(mojoLandmark); + + if (landmarkType == Landmark.LEFT_EYE) { + leftEyeIndex = j; + } else if (landmarkType == Landmark.RIGHT_EYE) { + rightEyeIndex = j; + } else { + assert landmarkType == Landmark.BOTTOM_MOUTH; + bottomMouthIndex = j; + } } } faceArray[i].landmarks = mojoLandmarks.toArray( new org.chromium.shape_detection.mojom.Landmark[mojoLandmarks.size()]); + + final PointF corner = face.getPosition(); + faceArray[i].boundingBox = new RectF(); + if (leftEyeIndex != -1 && rightEyeIndex != -1) { + final PointF leftEyePoint = landmarks.get(leftEyeIndex).getPosition(); + final float eyesDistance = + leftEyePoint.x - landmarks.get(rightEyeIndex).getPosition().x; + final float eyeMouthDistance = bottomMouthIndex != -1 + ? landmarks.get(bottomMouthIndex).getPosition().y - leftEyePoint.y + : -1; + final PointF midEyePoint = + new PointF(corner.x + face.getWidth() / 2, leftEyePoint.y); + faceArray[i].boundingBox.x = midEyePoint.x - eyesDistance; + faceArray[i].boundingBox.y = midEyePoint.y - eyesDistance; + faceArray[i].boundingBox.width = 2 * eyesDistance; + faceArray[i].boundingBox.height = eyeMouthDistance > eyesDistance + ? eyeMouthDistance + eyesDistance + : 2 * eyesDistance; + } else { + faceArray[i].boundingBox.x = corner.x; + faceArray[i].boundingBox.y = corner.y; + faceArray[i].boundingBox.width = face.getWidth(); + faceArray[i].boundingBox.height = face.getHeight(); + } } callback.call(faceArray); }
diff --git a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java index 5fb16663..1d68929 100644 --- a/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java +++ b/services/shape_detection/android/javatests/src/org/chromium/shape_detection/FaceDetectionImplTest.java
@@ -10,6 +10,10 @@ import android.support.test.filters.SmallTest; import android.test.InstrumentationTestCase; +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GoogleApiAvailability; + +import org.chromium.base.ContextUtils; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.UrlUtils; import org.chromium.shape_detection.mojom.FaceDetection; @@ -31,9 +35,17 @@ // we have to use a large error threshold. public static final double BOUNDING_BOX_POSITION_ERROR = 10.0; public static final double BOUNDING_BOX_SIZE_ERROR = 5.0; + public static enum DetectionProviderType { ANDROID, GMS_CORE } + public static final boolean IS_GMS_CORE_SUPPORTED = isGmsCoreSupported(); public FaceDetectionImplTest() {} + private static boolean isGmsCoreSupported() { + return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( + ContextUtils.getApplicationContext()) + == ConnectionResult.SUCCESS; + } + private static org.chromium.skia.mojom.Bitmap mojoBitmapFromBitmap(Bitmap bitmap) { ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); bitmap.copyPixelsToBuffer(buffer); @@ -52,11 +64,20 @@ return mojoBitmapFromBitmap(bitmap); } - private static FaceDetectionResult[] detect(org.chromium.skia.mojom.Bitmap mojoBitmap) { + private static FaceDetectionResult[] detect( + org.chromium.skia.mojom.Bitmap mojoBitmap, DetectionProviderType api) { FaceDetectorOptions options = new FaceDetectorOptions(); - options.fastMode = false; + options.fastMode = true; options.maxDetectedFaces = 32; - FaceDetection detector = new FaceDetectionImpl(options); + FaceDetection detector = null; + if (api == DetectionProviderType.ANDROID) { + detector = new FaceDetectionImpl(options); + } else if (api == DetectionProviderType.GMS_CORE) { + detector = new FaceDetectionImplGmsCore(options); + } else { + assert false; + return null; + } final ArrayBlockingQueue<FaceDetectionResult[]> queue = new ArrayBlockingQueue<>(1); detector.detect(mojoBitmap, new FaceDetection.DetectResponse() { @@ -74,10 +95,8 @@ return toReturn; } - @SmallTest - @Feature({"ShapeDetection"}) - public void testDetectSucceedsOnValidImage() { - FaceDetectionResult[] results = detect(MONA_LISA_BITMAP); + private void detectSucceedsOnValidImage(DetectionProviderType api) { + FaceDetectionResult[] results = detect(MONA_LISA_BITMAP, api); assertEquals(1, results.length); assertEquals(40.0, results[0].boundingBox.width, BOUNDING_BOX_SIZE_ERROR); assertEquals(40.0, results[0].boundingBox.height, BOUNDING_BOX_SIZE_ERROR); @@ -87,7 +106,21 @@ @SmallTest @Feature({"ShapeDetection"}) - public void testDetectHandlesOddWidths() throws Exception { + public void testDetectValidImageWithAndroidAPI() { + detectSucceedsOnValidImage(DetectionProviderType.ANDROID); + } + + @SmallTest + @Feature({"ShapeDetection"}) + public void testDetectValidImageWithGmsCore() { + if (IS_GMS_CORE_SUPPORTED) { + detectSucceedsOnValidImage(DetectionProviderType.GMS_CORE); + } + } + + @SmallTest + @Feature({"ShapeDetection"}) + public void testDetectHandlesOddWidthWithAndroidAPI() throws Exception { // Pad the image so that the width is odd. Bitmap paddedBitmap = Bitmap.createBitmap(MONA_LISA_BITMAP.width + 1, MONA_LISA_BITMAP.height, Bitmap.Config.ARGB_8888); @@ -96,7 +129,7 @@ org.chromium.skia.mojom.Bitmap mojoBitmap = mojoBitmapFromBitmap(paddedBitmap); assertEquals(1, mojoBitmap.width % 2); - FaceDetectionResult[] results = detect(mojoBitmap); + FaceDetectionResult[] results = detect(mojoBitmap, DetectionProviderType.ANDROID); assertEquals(1, results.length); assertEquals(40.0, results[0].boundingBox.width, BOUNDING_BOX_SIZE_ERROR); assertEquals(40.0, results[0].boundingBox.height, BOUNDING_BOX_SIZE_ERROR);
diff --git a/services/ui/public/cpp/gpu/gpu.cc b/services/ui/public/cpp/gpu/gpu.cc index 6285c21..190bb01 100644 --- a/services/ui/public/cpp/gpu/gpu.cc +++ b/services/ui/public/cpp/gpu/gpu.cc
@@ -19,21 +19,27 @@ namespace ui { -Gpu::Gpu(service_manager::Connector* connector, - const std::string& service_name, +namespace { + +mojom::GpuPtr DefaultFactory(service_manager::Connector* connector, + const std::string& service_name) { + mojom::GpuPtr gpu_ptr; + connector->BindInterface(service_name, &gpu_ptr); + return gpu_ptr; +} + +} // namespace + +Gpu::Gpu(GpuPtrFactory factory, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : main_task_runner_(base::ThreadTaskRunnerHandle::Get()), io_task_runner_(std::move(task_runner)), - connector_(connector), - service_name_(service_name), + factory_(std::move(factory)), shutdown_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED) { DCHECK(main_task_runner_); - DCHECK(connector_); - mojom::GpuPtr gpu_ptr; - connector_->BindInterface(service_name_, &gpu_ptr); gpu_memory_buffer_manager_ = - base::MakeUnique<ClientGpuMemoryBufferManager>(std::move(gpu_ptr)); + base::MakeUnique<ClientGpuMemoryBufferManager>(factory_.Run()); if (!io_task_runner_) { io_thread_.reset(new base::Thread("GPUIOThread")); base::Thread::Options thread_options(base::MessageLoop::TYPE_IO, 0); @@ -55,8 +61,9 @@ service_manager::Connector* connector, const std::string& service_name, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { - return base::WrapUnique( - new Gpu(connector, service_name, std::move(task_runner))); + GpuPtrFactory factory = + base::BindRepeating(&DefaultFactory, connector, service_name); + return base::WrapUnique(new Gpu(std::move(factory), std::move(task_runner))); } scoped_refptr<cc::ContextProvider> Gpu::CreateContextProvider( @@ -96,7 +103,7 @@ if (gpu_) return; - connector_->BindInterface(service_name_, &gpu_); + gpu_ = factory_.Run(); gpu_->EstablishGpuChannel( base::Bind(&Gpu::OnEstablishedGpuChannel, base::Unretained(this))); } @@ -109,8 +116,7 @@ int client_id = 0; mojo::ScopedMessagePipeHandle channel_handle; gpu::GPUInfo gpu_info; - connector_->BindInterface(service_name_, &gpu_); - + gpu_ = factory_.Run(); mojo::SyncCallRestrictions::ScopedAllowSyncCall allow_sync_call; if (!gpu_->EstablishGpuChannel(&client_id, &channel_handle, &gpu_info)) { DLOG(WARNING)
diff --git a/services/ui/public/cpp/gpu/gpu.h b/services/ui/public/cpp/gpu/gpu.h index 2ca4852..4b506e2 100644 --- a/services/ui/public/cpp/gpu/gpu.h +++ b/services/ui/public/cpp/gpu/gpu.h
@@ -51,10 +51,10 @@ gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override; private: - friend struct base::DefaultSingletonTraits<Gpu>; + friend class GpuTest; - Gpu(service_manager::Connector* connector, - const std::string& service_name, + using GpuPtrFactory = base::RepeatingCallback<mojom::GpuPtr(void)>; + Gpu(GpuPtrFactory factory, scoped_refptr<base::SingleThreadTaskRunner> task_runner); scoped_refptr<gpu::GpuChannelHost> GetGpuChannel(); @@ -70,8 +70,7 @@ scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_; - service_manager::Connector* connector_; - const std::string service_name_; + GpuPtrFactory factory_; base::WaitableEvent shutdown_event_; std::unique_ptr<base::Thread> io_thread_; std::unique_ptr<ClientGpuMemoryBufferManager> gpu_memory_buffer_manager_;
diff --git a/services/ui/public/cpp/tests/BUILD.gn b/services/ui/public/cpp/tests/BUILD.gn index afdfd17..a64453f 100644 --- a/services/ui/public/cpp/tests/BUILD.gn +++ b/services/ui/public/cpp/tests/BUILD.gn
@@ -9,6 +9,7 @@ testonly = true sources = [ + "gpu_unittest.cc", "property_type_converters_unittest.cc", ]
diff --git a/services/ui/public/cpp/tests/gpu_unittest.cc b/services/ui/public/cpp/tests/gpu_unittest.cc new file mode 100644 index 0000000..132dbf7 --- /dev/null +++ b/services/ui/public/cpp/tests/gpu_unittest.cc
@@ -0,0 +1,124 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/ui/public/cpp/gpu/gpu.h" + +#include "base/callback_helpers.h" +#include "base/test/scoped_task_environment.h" +#include "gpu/config/gpu_info.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace ui { + +namespace { + +class TestGpuImpl : public mojom::Gpu { + public: + TestGpuImpl() {} + ~TestGpuImpl() override {} + + mojom::GpuPtr GetPtr() { + mojom::GpuPtr ptr; + bindings_.AddBinding(this, mojo::MakeRequest(&ptr)); + return ptr; + } + + void WaitUntilChannelRequest() { + DCHECK(quit_closure_.is_null()); + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + quit_closure_ = base::Closure(); + } + + bool RespondToGpuChannelRequests() { + if (establish_channel_callback_.is_null()) + return false; + constexpr int client_id = 1; + mojo::ScopedMessagePipeHandle handle; + base::ResetAndReturn(&establish_channel_callback_) + .Run(client_id, std::move(handle), gpu::GPUInfo()); + return true; + } + + // ui::mojom::Gpu overrides: + void EstablishGpuChannel( + const EstablishGpuChannelCallback& callback) override { + establish_channel_callback_ = callback; + if (!quit_closure_.is_null()) + quit_closure_.Run(); + } + + void CreateGpuMemoryBuffer( + gfx::GpuMemoryBufferId id, + const gfx::Size& size, + gfx::BufferFormat format, + gfx::BufferUsage usage, + const ui::mojom::Gpu::CreateGpuMemoryBufferCallback& callback) override {} + + void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id, + const gpu::SyncToken& sync_token) override {} + + private: + EstablishGpuChannelCallback establish_channel_callback_; + + mojo::BindingSet<mojom::Gpu> bindings_; + base::Closure quit_closure_; + + DISALLOW_COPY_AND_ASSIGN(TestGpuImpl); +}; + +} // namespace + +class GpuTest : public testing::Test { + public: + GpuTest() {} + ~GpuTest() override {} + + Gpu* gpu() { return gpu_.get(); } + + TestGpuImpl* gpu_impl() { return &gpu_impl_; } + + // testing::Test: + void SetUp() override { + auto factory = + base::BindRepeating(&TestGpuImpl::GetPtr, base::Unretained(&gpu_impl_)); + gpu_ = base::WrapUnique(new Gpu(std::move(factory), nullptr)); + } + + private: + base::test::ScopedTaskEnvironment env_; + TestGpuImpl gpu_impl_; + std::unique_ptr<Gpu> gpu_; + + DISALLOW_COPY_AND_ASSIGN(GpuTest); +}; + +// Tests that multiple calls for establishing a gpu channel are all notified +// correctly when the channel is established (or fails to establish). +TEST_F(GpuTest, EstablishRequestsQueued) { + int counter = 2; + base::RunLoop run_loop; + // A callback that decrements the counter, and runs the callback when the + // counter reaches 0. + auto callback = base::Bind( + [](int* counter, const base::Closure& callback, + scoped_refptr<gpu::GpuChannelHost> channel) { + --(*counter); + if (*counter == 0) + callback.Run(); + }, + &counter, run_loop.QuitClosure()); + gpu()->EstablishGpuChannel(callback); + gpu()->EstablishGpuChannel(callback); + EXPECT_EQ(2, counter); + gpu_impl()->WaitUntilChannelRequest(); + + EXPECT_TRUE(gpu_impl()->RespondToGpuChannelRequests()); + run_loop.Run(); + EXPECT_EQ(0, counter); +} + +} // namespace ui
diff --git a/services/video_capture/BUILD.gn b/services/video_capture/BUILD.gn index 789fef2c0..c4bde50 100644 --- a/services/video_capture/BUILD.gn +++ b/services/video_capture/BUILD.gn
@@ -52,6 +52,7 @@ "//services/video_capture/public/cpp", "//services/video_capture/public/interfaces", "//services/video_capture/public/interfaces:constants", + "//services/video_capture/public/uma", ] }
diff --git a/services/video_capture/device_factory_media_to_mojo_adapter.cc b/services/video_capture/device_factory_media_to_mojo_adapter.cc index 60b2b370..53c47520 100644 --- a/services/video_capture/device_factory_media_to_mojo_adapter.cc +++ b/services/video_capture/device_factory_media_to_mojo_adapter.cc
@@ -14,6 +14,7 @@ #include "media/capture/video/video_capture_device_info.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "services/video_capture/device_media_to_mojo_adapter.h" +#include "services/video_capture/public/uma/video_capture_service_event.h" namespace { @@ -158,6 +159,9 @@ void DeviceFactoryMediaToMojoAdapter::OnClientConnectionErrorOrClose( const std::string& device_id) { + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::SERVICE_LOST_CONNECTION_TO_BROWSER); + active_devices_by_id_[device_id].device->Stop(); active_devices_by_id_.erase(device_id); }
diff --git a/services/video_capture/public/uma/BUILD.gn b/services/video_capture/public/uma/BUILD.gn new file mode 100644 index 0000000..838e7c1 --- /dev/null +++ b/services/video_capture/public/uma/BUILD.gn
@@ -0,0 +1,14 @@ +# 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. + +source_set("uma") { + sources = [ + "video_capture_service_event.cc", + "video_capture_service_event.h", + ] + + public_deps = [ + "//base", + ] +}
diff --git a/services/video_capture/public/uma/video_capture_service_event.cc b/services/video_capture/public/uma/video_capture_service_event.cc new file mode 100644 index 0000000..20c365a --- /dev/null +++ b/services/video_capture/public/uma/video_capture_service_event.cc
@@ -0,0 +1,36 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "services/video_capture/public/uma/video_capture_service_event.h" + +#include "base/metrics/histogram_macros.h" + +namespace video_capture { +namespace uma { + +void LogVideoCaptureServiceEvent(VideoCaptureServiceEvent event) { + UMA_HISTOGRAM_ENUMERATION("Media.VideoCaptureService.Event", event, + NUM_VIDEO_CAPTURE_SERVICE_EVENT); +} + +void LogDurationFromLastConnectToClosingConnection(base::TimeDelta duration) { + UMA_HISTOGRAM_CUSTOM_TIMES( + "Media.VideoCaptureService.DurationFromLastConnectToClosingConnection", + duration, base::TimeDelta(), base::TimeDelta::FromDays(7), 50); +} + +void LogDurationFromLastConnectToConnectionLost(base::TimeDelta duration) { + UMA_HISTOGRAM_CUSTOM_TIMES( + "Media.VideoCaptureService.DurationFromLastConnectToConnectionLost", + duration, base::TimeDelta(), base::TimeDelta::FromDays(7), 50); +} + +void LogDurationUntilReconnect(base::TimeDelta duration) { + UMA_HISTOGRAM_CUSTOM_TIMES("Media.VideoCaptureService.DurationUntilReconnect", + duration, base::TimeDelta(), + base::TimeDelta::FromDays(7), 50); +} + +} // namespace uma +} // namespace video_capture
diff --git a/services/video_capture/public/uma/video_capture_service_event.h b/services/video_capture/public/uma/video_capture_service_event.h new file mode 100644 index 0000000..5ebb85a --- /dev/null +++ b/services/video_capture/public/uma/video_capture_service_event.h
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_SERVICE_EVENT_H_ +#define SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_SERVICE_EVENT_H_ + +#include "base/time/time.h" + +namespace video_capture { +namespace uma { + +// Used for logging capture events. +// Elements in this enum should not be deleted or rearranged; the only +// permitted operation is to add new elements before +// NUM_VIDEO_CAPTURE_SERVICE_EVENT. +enum VideoCaptureServiceEvent { + BROWSER_USING_LEGACY_CAPTURE = 0, + BROWSER_CONNECTING_TO_SERVICE = 1, + SERVICE_STARTED = 2, + SERVICE_CLOSING_BECAUSE_NO_CLIENT = 3, + SERVICE_LOST_CONNECTION_TO_BROWSER = 4, + BROWSER_LOST_CONNECTION_TO_SERVICE = 5, + BROWSER_CLOSING_CONNECTION_TO_SERVICE = 6, + NUM_VIDEO_CAPTURE_SERVICE_EVENT +}; + +void LogVideoCaptureServiceEvent(VideoCaptureServiceEvent event); + +void LogDurationFromLastConnectToClosingConnection(base::TimeDelta duration); +void LogDurationFromLastConnectToConnectionLost(base::TimeDelta duration); +void LogDurationUntilReconnect(base::TimeDelta duration); + +} // namespace uma +} // namespace video_capture + +#endif // SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_SERVICE_EVENT_H_
diff --git a/services/video_capture/service_impl.cc b/services/video_capture/service_impl.cc index 5c4aa54..edcc439 100644 --- a/services/video_capture/service_impl.cc +++ b/services/video_capture/service_impl.cc
@@ -8,6 +8,7 @@ #include "services/service_manager/public/cpp/service_context.h" #include "services/video_capture/device_factory_provider_impl.h" #include "services/video_capture/public/interfaces/constants.mojom.h" +#include "services/video_capture/public/uma/video_capture_service_event.h" #include "services/video_capture/testing_controls_impl.h" namespace video_capture { @@ -22,6 +23,10 @@ void ServiceImpl::OnStart() { DCHECK(thread_checker_.CalledOnValidThread()); + + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::SERVICE_STARTED); + ref_factory_ = base::MakeUnique<service_manager::ServiceContextRefFactory>(base::Bind( &ServiceImpl::MaybeRequestQuitDelayed, base::Unretained(this))); @@ -91,6 +96,8 @@ DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(ref_factory_); if (ref_factory_->HasNoRefs()) { + video_capture::uma::LogVideoCaptureServiceEvent( + video_capture::uma::SERVICE_CLOSING_BECAUSE_NO_CLIENT); context()->RequestQuit(); } }
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 967b5bd..78405b7 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1601,6 +1601,48 @@ } ] }, + "Android WebView L (dbg)": { + "cts_tests": [ + { + "arch": "arm64", + "platform": "L" + } + ], + "instrumentation_tests": [ + { + "test": "system_webview_shell_layout_test_apk" + } + ] + }, + "Android WebView M (dbg)": { + "cts_tests": [ + { + "arch": "arm64", + "platform": "M" + } + ], + "instrumentation_tests": [ + { + "test": "system_webview_shell_layout_test_apk" + }, + { + "test": "webview_ui_test_app_test_apk" + } + ] + }, + "Android WebView N (dbg)": { + "cts_tests": [ + { + "arch": "arm64", + "platform": "N" + } + ], + "instrumentation_tests": [ + { + "test": "system_webview_shell_layout_test_apk" + } + ] + }, "Android arm Builder (dbg)": { "additional_compile_targets": [ "dump_syms",
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index b8959cd..9bd8bab 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -10926,6 +10926,17 @@ { "args": [ "--enable-features=NetworkService", + "--test-launcher-filter-file=../../testing/buildbot/filters/mojo.fyi.network_browser_tests.filter" + ], + "name": "network_service_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "browser_tests" + }, + { + "args": [ + "--enable-features=NetworkService", "--test-launcher-filter-file=../../testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter" ], "name": "network_service_content_browsertests",
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index 87107b1..563e05f 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -15648,6 +15648,88 @@ } ] }, + "Win7 ANGLE Tryserver (AMD)": { + "gtest_tests": [ + { + "args": [ + "--test-launcher-batch-limit=400", + "--deqp-egl-display-type=angle-d3d11" + ], + "name": "angle_deqp_gles2_d3d11_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "1002:6613", + "os": "Windows-2008ServerR2-SP1" + } + ], + "shards": 4 + }, + "test": "angle_deqp_gles2_tests", + "use_xvfb": false + }, + { + "args": [ + "--use-gpu-in-tests", + "--test-launcher-retry-limit=0" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "1002:6613", + "os": "Windows-2008ServerR2-SP1" + } + ] + }, + "test": "angle_end2end_tests", + "use_xvfb": false + }, + { + "args": [ + "--test-launcher-retry-limit=0" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "1002:6613", + "os": "Windows-2008ServerR2-SP1" + } + ] + }, + "test": "angle_white_box_tests", + "use_xvfb": false + } + ], + "isolated_scripts": [ + { + "args": [ + "webgl_conformance", + "--show-stdout", + "--browser=release", + "--passthrough", + "-v", + "--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc --use-angle=d3d11 --use-passthrough-cmd-decoder" + ], + "isolate_name": "telemetry_gpu_integration_test", + "name": "webgl_conformance_d3d11_passthrough_tests", + "override_compile_targets": [ + "telemetry_gpu_integration_test" + ], + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "gpu": "1002:6613", + "os": "Windows-2008ServerR2-SP1" + } + ] + } + } + ] + }, "Win7 Debug (AMD)": { "gtest_tests": [ {
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index cba075b..d5ca687 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -24,6 +24,7 @@ "//testing/buildbot/filters/mash.browser_tests.filter", "//testing/buildbot/filters/mojo.fyi.browser_tests.filter", "//testing/buildbot/filters/mojo.fyi.mus.browser_tests.filter", + "//testing/buildbot/filters/mojo.fyi.network_browser_tests.filter", "//testing/buildbot/filters/mus.browser_tests.filter", "//testing/buildbot/filters/site-per-process.browser_tests.filter", ]
diff --git a/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter new file mode 100644 index 0000000..bd8a6e4 --- /dev/null +++ b/testing/buildbot/filters/mojo.fyi.network_browser_tests.filter
@@ -0,0 +1,70 @@ +# SafeBrowsing tests. +CertificateReportingServiceBrowserTest.* +DefaultSettingsFetcherTest.* +PermissionReporterBrowserTest.* +PhishingClassifierDelegateTest.* +PhishingClassifierTest.* +PhishingDOMFeatureExtractorTest.* +SafeBrowsingBlockingPageBrowserTest.* +SafeBrowsingBlockingPageIDNTest.* +SafeBrowsingDatabaseManagerCookieTest.* +SBNavigationObserverBrowserTest.* +SafeBrowsingServiceMetadataTest.* +SafeBrowsingServiceShutdownTest.* +SafeBrowsingServiceTest.* +ThreatDOMDetailsTest.* +V4SafeBrowsingServiceMetadataTest.* +V4SafeBrowsingServiceTest.* + +# Windows-only SafeBrowsing tests. +ChromeCleanerResetTaggedProfilesTest.* +ChromeCleanerTagForResettingTest.* +ExtensionSettingsOverrideTest.* +ReporterRunnerTest.* +SettingsResetPromptModelBrowserTest.* + +# crbug.com/736081: Failed SafeBrowsing tests. +-SBNavigationObserverBrowserTest.AddIPMapping +-SBNavigationObserverBrowserTest.DownloadViaHTML5FileApiWithUserGesture +-SBNavigationObserverBrowserTest.DownloadViaHTML5FileApiWithoutUserGesture +-SBNavigationObserverBrowserTest.IPListDedup +-SBNavigationObserverBrowserTest.PPAPIDownloadWithUserGestureOnHostingFrame +-SBNavigationObserverBrowserTest.PPAPIDownloadWithoutUserGestureOnHostingFrame +-SafeBrowsingServiceTest.MainFrameHitWithReferrer +-SafeBrowsingServiceTest.Prefetch +-V4SafeBrowsingServiceTest.MainFrameHitWithReferrer +-V4SafeBrowsingServiceTest.MalwareWithWhitelist +-V4SafeBrowsingServiceTest.Prefetch + +# crbug.com/736081: Timed-out SafeBrowsing tests. +-CertificateReportingServiceBrowserTest.Delayed_Reset +-CertificateReportingServiceBrowserTest.Delayed_Resumed +-CertificateReportingServiceBrowserTest.Delayed_Resumed_ServiceShutdown +-CertificateReportingServiceBrowserTest.DisableSafebrowsing +-CertificateReportingServiceBrowserTest.DontSendOldReports +-CertificateReportingServiceBrowserTest.DropOldReportsFromQueue +-CertificateReportingServiceBrowserTest.NotOptedIn_ShouldNotSendReports +-CertificateReportingServiceBrowserTest.OptedIn_ShouldQueueFailedReport +-CertificateReportingServiceBrowserTest.OptedIn_ShouldSendSuccessfulReport +-CertificateReportingServiceBrowserTest.OptedIn_ThenOptedOut +-CertificateReportingServiceBrowserTest.OptedOut_ThenOptedIn_ThenOptedOut +-SBNavigationObserverBrowserTest.CompleteReferrerChain +-SBNavigationObserverBrowserTest.DirectDownload +-SBNavigationObserverBrowserTest.DirectDownloadNoReferrer +-SBNavigationObserverBrowserTest.DirectDownloadNoReferrerTargetBlank +-SBNavigationObserverBrowserTest.MixRedirects +-SBNavigationObserverBrowserTest.MultiMetaRefreshRedirects +-SBNavigationObserverBrowserTest.NewTabDownload +-SBNavigationObserverBrowserTest.NewTabDownloadWithDataURL +-SBNavigationObserverBrowserTest.ReferrerAttributionWithinTwoUserGestures +-SBNavigationObserverBrowserTest.RetargetingAndServerRedirect +-SBNavigationObserverBrowserTest.ServerRedirect +-SBNavigationObserverBrowserTest.SingleMetaRefreshRedirect +-SBNavigationObserverBrowserTest.SingleMetaRefreshRedirectTargetBlank +-SBNavigationObserverBrowserTest.SubFrameDirectDownload +-SBNavigationObserverBrowserTest.SubFrameNewTabDownload +-SBNavigationObserverBrowserTest.TwoServerRedirects +-SBNavigationObserverBrowserTest.TypeInURLDownload +-SBNavigationObserverBrowserTest.VerifySanitizeReferrerChain +-SBNavigationObserverBrowserTest.WindowLocationRedirect +-SafeBrowsingServiceTest.MalwareWebSocketBlocked
diff --git a/testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter b/testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter index 37c9525..8285dec5 100644 --- a/testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter +++ b/testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter
@@ -150,6 +150,7 @@ -WebContentsImplBrowserTest.GetSizeForNewRenderView -WebContentsImplBrowserTest.UserAgentOverride -WebContentsViewAuraTest.ScreenshotForSwappedOutRenderViews +-WebRtcGetUserMediaOldConstraintsBrowserTest.GetUserMediaWithInvalidMandatorySourceID -WebRtcGetUserMediaOldConstraintsBrowserTest.TwoGetUserMediaWithFirstHdSecondVga -WebRtcGetUserMediaOldConstraintsBrowserTest.TwoGetUserMediaWithSecondVideoCropped -WebRtcVideoCaptureBrowserTest.RecoverFromCrashInVideoCaptureProcess
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 9c3385a..83c4156 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -403,6 +403,25 @@ ] } ], + "CaptivePortalCertificateList": [ + { + "platforms": [ + "android", + "chromeos", + "linux", + "mac", + "win" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "CaptivePortalCertificateList" + ] + } + ] + } + ], "CaptivePortalInterstitial": [ { "platforms": [
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG index 82f6d37..e9d3328 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-blink-features=LayoutNG
@@ -230,7 +230,7 @@ crbug.com/591099 animations/3d/state-at-end-event-transform.html [ Failure Pass ] crbug.com/591099 animations/animation-css-rule-types.html [ Failure ] crbug.com/591099 animations/animation-events-create.html [ Failure ] -crbug.com/591099 animations/animation-inherit-initial-unprefixed.html [ Failure ] +crbug.com/591099 animations/prefixed/animation-inherit-initial-unprefixed.html [ Failure ] crbug.com/591099 animations/animations-parsing.html [ Timeout ] crbug.com/591099 animations/animations-responsive-to-color-change.html [ Crash ] crbug.com/591099 animations/clear-svg-animation-effects.html [ Crash ] @@ -329,8 +329,8 @@ crbug.com/591099 animations/interpolation/webkit-text-stroke-color-interpolation.html [ Crash ] crbug.com/591099 animations/interpolation/webkit-transform-interpolation.html [ Crash ] crbug.com/591099 animations/interpolation/webkit-transform-origin-interpolation.html [ Crash ] -crbug.com/591099 animations/keyframes-cssom-prefixed-02.html [ Failure ] -crbug.com/591099 animations/keyframes-cssom-unprefixed-02.html [ Failure ] +crbug.com/591099 animations/prefixed/keyframes-cssom-prefixed-02.html [ Failure ] +crbug.com/591099 animations/prefixed/keyframes-cssom-unprefixed-02.html [ Failure ] crbug.com/591099 animations/keyframes-rule.html [ Failure ] crbug.com/591099 animations/lazy-detached-animation-stop.html [ Failure ] crbug.com/591099 animations/negative-delay-events.html [ Failure ] @@ -2892,7 +2892,6 @@ crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement05.html [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement06.html [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement07.html [ Crash Pass ] -crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement08.html [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement09.html [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement10.html [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/html/level2/html/HTMLIFrameElement11.html [ Crash ] @@ -3115,7 +3114,6 @@ crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLImageElement05.xhtml [ Crash ] crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLImageElement07.xhtml [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLImageElement09.xhtml [ Crash Pass ] -crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLImageElement11.xhtml [ Crash Pass ] crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLImageElement12.xhtml [ Crash ] crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLObjectElement01.xhtml [ Crash ] crbug.com/591099 dom/legacy_dom_conformance/xhtml/level2/html/HTMLObjectElement02.xhtml [ Crash ] @@ -3883,7 +3881,7 @@ crbug.com/591099 editing/selection/move-past-trailing-space.html [ Failure ] crbug.com/591099 editing/selection/move-vertically-with-paddings-borders.html [ Failure ] crbug.com/591099 editing/selection/no-range-canonicalization.html [ Failure ] -crbug.com/591099 editing/selection/node-removal-2.html [ Failure ] +crbug.com/591099 editing/selection/node-removal-2.html [ Failure Pass ] crbug.com/591099 editing/selection/offset-from-point.html [ Crash Failure ] crbug.com/591099 editing/selection/paint-hyphen.html [ Failure ] crbug.com/591099 editing/selection/paragraph-granularity.html [ Failure ] @@ -3960,6 +3958,7 @@ crbug.com/591099 editing/selection/triple-click-in-pre.html [ Failure ] crbug.com/591099 editing/selection/undo-crash.html [ Crash ] crbug.com/591099 editing/selection/user-select-all-parsing.html [ Failure ] +crbug.com/591099 editing/selection/user-select-all-with-shift.html [ Crash ] crbug.com/591099 editing/selection/user-select/user-select-all.html [ Crash ] crbug.com/591099 editing/selection/vertical-lr-ltr-extend-line-backward-br.html [ Failure Pass ] crbug.com/591099 editing/selection/vertical-lr-ltr-extend-line-forward-br.html [ Failure Pass ] @@ -4098,7 +4097,7 @@ crbug.com/591099 editing/unsupported-content/table-type-after.html [ Failure ] crbug.com/591099 editing/unsupported-content/table-type-before.html [ Failure ] crbug.com/591099 external/wpt/2dcontext/drawing-images-to-the-canvas/2d.drawImage.incomplete.emptysrc.html [ Crash ] -crbug.com/591099 external/wpt/2dcontext/drawing-images-to-the-canvas/2d.drawImage.incomplete.removedsrc.html [ Crash ] +crbug.com/591099 external/wpt/2dcontext/drawing-images-to-the-canvas/2d.drawImage.incomplete.removedsrc.html [ Crash Pass ] crbug.com/591099 external/wpt/2dcontext/drawing-images-to-the-canvas/2d.drawImage.zerosource.image.html [ Crash Pass ] crbug.com/591099 external/wpt/2dcontext/drawing-paths-to-the-canvas/canvas_focus_drawCustomFocusRing_001.html [ Crash ] crbug.com/591099 external/wpt/2dcontext/drawing-paths-to-the-canvas/drawFocusIfNeeded_001.html [ Crash ] @@ -4174,7 +4173,6 @@ crbug.com/591099 external/wpt/content-security-policy/navigation/to-javascript-url-script-src.html [ Crash ] crbug.com/591099 external/wpt/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.tentative.html [ Crash ] crbug.com/591099 external/wpt/content-security-policy/nonce-hiding/svgscript-nonces-hidden.tentative.html [ Crash ] -crbug.com/591099 external/wpt/content-security-policy/script-src/script-src-1_1.html [ Crash Pass ] crbug.com/591099 external/wpt/content-security-policy/script-src/script-src-1_2.html [ Crash Pass ] crbug.com/591099 external/wpt/content-security-policy/securitypolicyviolation/img-src-redirect-upgrade-reporting.https.html [ Crash ] crbug.com/591099 external/wpt/content-security-policy/securitypolicyviolation/script-sample-no-opt-in.html [ Crash ] @@ -4187,21 +4185,18 @@ crbug.com/591099 external/wpt/cors/remote-origin.htm [ Crash ] crbug.com/591099 external/wpt/css/CSS2/abspos/abspos-containing-block-initial-001.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/abspos/abspos-containing-block-initial-009a.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/floats-clear/float-replaced-height-001.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/float-replaced-width-002.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-001.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-026.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-027.xht [ Crash Failure ] +crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-026.xht [ Failure Pass ] +crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-027.xht [ Crash Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-029.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-031.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-101.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-114.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-125.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-132.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-141.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-143.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-144.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-145.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/floats-146.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/margin-collapse-018.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/floats-clear/margin-collapse-027.xht [ Failure ] @@ -4247,11 +4242,9 @@ crbug.com/591099 external/wpt/css/CSS2/linebox/inline-formatting-context-001.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/linebox/vertical-align-baseline-004a.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/linebox/vertical-align-baseline-005a.xht [ Failure ] -crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-formatting-context-height-001.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-formatting-context-height-002.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-in-inline-percents-001.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-non-replaced-height-005.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-non-replaced-width-007.xht [ Failure ] +crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-non-replaced-width-007.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-replaced-width-006.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/normal-flow/blocks-025.xht [ Failure ] crbug.com/591099 external/wpt/css/CSS2/normal-flow/inline-block-non-replaced-height-002.xht [ Failure Pass ] @@ -4766,7 +4759,7 @@ crbug.com/591099 external/wpt/css/css-ui-3/caret-color-019.html [ Crash ] crbug.com/591099 external/wpt/css/css-ui-3/caret-color-020.html [ Crash ] crbug.com/591099 external/wpt/css/css-ui-3/caret-color-021.html [ Crash ] -crbug.com/591099 external/wpt/css/css-ui-3/outline-004.html [ Failure ] +crbug.com/591099 external/wpt/css/css-ui-3/outline-004.html [ Failure Pass ] crbug.com/591099 external/wpt/css/css-ui-3/outline-011.html [ Failure ] crbug.com/591099 external/wpt/css/css-ui-3/outline-019.html [ Failure ] crbug.com/591099 external/wpt/css/css-ui-3/outline-offset.html [ Failure Pass ] @@ -4976,7 +4969,7 @@ crbug.com/591099 external/wpt/css/css-writing-modes-3/block-flow-direction-vrl-026.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/block-plaintext-004.html [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/border-vlr-007.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes-3/border-vrl-006.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes-3/border-vrl-006.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes-3/box-offsets-rel-pos-vlr-003.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/box-offsets-rel-pos-vrl-002.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/central-baseline-alignment-002.xht [ Failure ] @@ -5003,8 +4996,6 @@ crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vlr-009.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vlr-011.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vlr-013.xht [ Failure ] -crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vrl-002.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vrl-004.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vrl-006.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vrl-008.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/float-contiguous-vrl-010.xht [ Failure ] @@ -5084,7 +5075,7 @@ crbug.com/591099 external/wpt/css/css-writing-modes-3/overconstrained-rel-pos-rtl-top-bottom-vlr-007.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/overconstrained-rel-pos-rtl-top-bottom-vrl-006.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/padding-vlr-005.xht [ Failure Pass ] -crbug.com/591099 external/wpt/css/css-writing-modes-3/padding-vrl-004.xht [ Failure ] +crbug.com/591099 external/wpt/css/css-writing-modes-3/padding-vrl-004.xht [ Failure Pass ] crbug.com/591099 external/wpt/css/css-writing-modes-3/percent-margin-vlr-003.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/percent-margin-vlr-007.xht [ Failure ] crbug.com/591099 external/wpt/css/css-writing-modes-3/percent-margin-vrl-002.xht [ Failure ] @@ -5224,7 +5215,6 @@ crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-005.html [ Crash Failure Pass ] crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-005a.html [ Crash Failure ] crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-006.html [ Crash Failure ] -crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-006a.html [ Crash Failure Pass ] crbug.com/591099 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-007.html [ Crash Failure Pass ] crbug.com/591099 external/wpt/cssom-view/cssom-getClientRects-002.html [ Failure ] crbug.com/591099 external/wpt/cssom-view/elementFromPoint.html [ Crash ] @@ -6491,6 +6481,7 @@ crbug.com/591099 fast/animation/request-animation-frame-timestamps.html [ Failure ] crbug.com/591099 fast/animation/request-animation-frame-within-callback.html [ Failure ] crbug.com/591099 fast/animation/request-animation-frame.html [ Failure ] +crbug.com/591099 fast/animation/scroll-animations/scrolltimeline-currenttime.html [ Failure ] crbug.com/591099 fast/autoresize/basic.html [ Failure ] crbug.com/591099 fast/autoresize/turn-off-autoresize.html [ Failure ] crbug.com/591099 fast/backgrounds/001.html [ Failure ] @@ -6594,7 +6585,6 @@ crbug.com/591099 fast/block/dynamic-padding-border.html [ Failure ] crbug.com/591099 fast/block/float/002.html [ Crash Failure ] crbug.com/591099 fast/block/float/003.html [ Failure ] -crbug.com/591099 fast/block/float/008.html [ Failure Pass ] crbug.com/591099 fast/block/float/010.html [ Failure ] crbug.com/591099 fast/block/float/012.html [ Failure ] crbug.com/591099 fast/block/float/014.html [ Crash Failure ] @@ -6634,7 +6624,6 @@ crbug.com/591099 fast/block/float/containing-block-change-compositing.html [ Failure ] crbug.com/591099 fast/block/float/crash-on-absolute-positioning.html [ Failure ] crbug.com/591099 fast/block/float/crash-replaced-display-block.html [ Failure ] -crbug.com/591099 fast/block/float/dynamic-unfloat-pref-width.html [ Failure Pass ] crbug.com/591099 fast/block/float/editable-text-overlapping-float.html [ Failure ] crbug.com/591099 fast/block/float/element-clears-float-without-clearance.html [ Failure ] crbug.com/591099 fast/block/float/fit_line_below_floats.html [ Failure Pass ] @@ -6647,14 +6636,12 @@ crbug.com/591099 fast/block/float/float-inserted-into-clean-line.html [ Failure ] crbug.com/591099 fast/block/float/float-list-changed-before-layout-crash.html [ Crash ] crbug.com/591099 fast/block/float/float-not-removed-from-next-sibling-crash.html [ Failure ] -crbug.com/591099 fast/block/float/float-not-removed-from-next-sibling3.html [ Failure Pass ] crbug.com/591099 fast/block/float/float-not-removed-from-next-sibling5.html [ Crash Failure ] crbug.com/591099 fast/block/float/float-on-empty-line.html [ Failure ] crbug.com/591099 fast/block/float/float-on-line-large-and-small-float-below.html [ Crash ] crbug.com/591099 fast/block/float/float-on-line-obeys-container-padding.html [ Failure ] crbug.com/591099 fast/block/float/float-on-zero-height-line.html [ Failure ] crbug.com/591099 fast/block/float/float-overflow-hidden-containing-block-width.html [ Failure ] -crbug.com/591099 fast/block/float/float-overhangs-root.html [ Crash Failure Pass ] crbug.com/591099 fast/block/float/float-reparent-during-detach-crash.html [ Crash ] crbug.com/591099 fast/block/float/floats-and-text-indent-rl.html [ Failure ] crbug.com/591099 fast/block/float/floats-and-text-indent.html [ Failure ] @@ -6684,7 +6671,6 @@ crbug.com/591099 fast/block/float/negative-margin-on-element-avoiding-floats-with-margin-on-parent.html [ Failure ] crbug.com/591099 fast/block/float/negative-margin-on-element-avoiding-floats.html [ Failure ] crbug.com/591099 fast/block/float/nested-clearance.html [ Failure ] -crbug.com/591099 fast/block/float/nested-floats-expand-formatting-context.html [ Failure Pass ] crbug.com/591099 fast/block/float/nopaint-after-layer-destruction.html [ Failure ] crbug.com/591099 fast/block/float/nopaint-after-layer-destruction2.html [ Failure ] crbug.com/591099 fast/block/float/overhanging-float-add-in-static-position-block.html [ Crash Failure Pass ] @@ -6939,7 +6925,7 @@ crbug.com/591099 fast/borders/border-image-slices.html [ Failure Pass ] crbug.com/591099 fast/borders/border-image-source.html [ Failure Pass ] crbug.com/591099 fast/borders/border-image-width-negative.html [ Failure ] -crbug.com/591099 fast/borders/border-inner-bleed.html [ Failure ] +crbug.com/591099 fast/borders/border-inner-bleed.html [ Failure Pass ] crbug.com/591099 fast/borders/border-radius-child.html [ Failure ] crbug.com/591099 fast/borders/border-radius-complex-inner-double.html [ Failure Pass ] crbug.com/591099 fast/borders/border-radius-complex-inner.html [ Failure Pass ] @@ -7556,9 +7542,7 @@ crbug.com/591099 fast/css-intrinsic-dimensions/height-property-value.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/height.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/indefinite-percent-minmax-content-inlinesize-contribution-nonreplaced-blocks.html [ Failure ] -crbug.com/591099 fast/css-intrinsic-dimensions/intrinsic-sized-absolutes.html [ Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/intrinsic-sized-blocks.html [ Crash Failure Pass ] -crbug.com/591099 fast/css-intrinsic-dimensions/intrinsic-sized-replaced-absolutes.html [ Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/max-width-constrained.html [ Crash Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/max-width-unconstrained.html [ Crash Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/maxcontent-minmax-content-inlinesize-contribution-nonreplaced-blocks.html [ Crash Failure Pass ] @@ -7567,7 +7551,6 @@ crbug.com/591099 fast/css-intrinsic-dimensions/resize-inside-percent-width-overflow-hidden.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/width-avoid-floats.html [ Crash Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/width-property-value.html [ Failure ] -crbug.com/591099 fast/css-intrinsic-dimensions/width-shrinks-avoid-floats.html [ Crash Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/width.html [ Crash Failure ] crbug.com/591099 fast/css/001.html [ Crash Failure ] crbug.com/591099 fast/css/002.html [ Failure ] @@ -8439,10 +8422,6 @@ crbug.com/591099 fast/deprecated-flexbox/vertical-box-form-controls.html [ Failure ] crbug.com/591099 fast/dnd/dropEffect-for-file.html [ Crash ] crbug.com/591099 fast/dnd/dropEffect-for-image.html [ Timeout ] -crbug.com/591099 fast/dnd/link-dragging-draggable-div-with-dragged-link.html [ Pass Timeout ] -crbug.com/591099 fast/dnd/link-dragging-draggable-div-with-link.html [ Pass Timeout ] -crbug.com/591099 fast/dnd/link-dragging-draggable-link.html [ Pass Timeout ] -crbug.com/591099 fast/dnd/link-dragging-non-draggable-link.html [ Pass Timeout ] crbug.com/591099 fast/doctypes/001.html [ Crash Failure ] crbug.com/591099 fast/doctypes/002.html [ Crash Failure ] crbug.com/591099 fast/doctypes/003.html [ Crash Failure ] @@ -8645,7 +8624,6 @@ crbug.com/591099 fast/dom/HTMLImageElement/image-longdesc-absolute-url.html [ Failure ] crbug.com/591099 fast/dom/HTMLImageElement/image-lowsrc-getset.html [ Failure ] crbug.com/591099 fast/dom/HTMLImageElement/image-natural-width-height-svg.html [ Crash ] -crbug.com/591099 fast/dom/HTMLImageElement/image-natural-width-height.html [ Crash Pass ] crbug.com/591099 fast/dom/HTMLImageElement/image-sizes-1x.html [ Crash ] crbug.com/591099 fast/dom/HTMLImageElement/image-src-absolute-url.html [ Failure ] crbug.com/591099 fast/dom/HTMLImageElement/image-srcset-1x.html [ Crash ] @@ -8688,7 +8666,6 @@ crbug.com/591099 fast/dom/HTMLLinkElement/prefetch-detached.html [ Failure ] crbug.com/591099 fast/dom/HTMLLinkElement/prefetch-onerror.html [ Failure ] crbug.com/591099 fast/dom/HTMLLinkElement/prefetch-onload.html [ Crash Failure ] -crbug.com/591099 fast/dom/HTMLLinkElement/prefetch.html [ Crash Failure Pass ] crbug.com/591099 fast/dom/HTMLLinkElement/prerender-insert-after-stop.html [ Failure ] crbug.com/591099 fast/dom/HTMLLinkElement/prerender-remove-after-stop.html [ Failure ] crbug.com/591099 fast/dom/HTMLLinkElement/programmatically-add-link-with-onerror-handler.html [ Failure ] @@ -10033,7 +10010,7 @@ crbug.com/591099 fast/events/popup-allowed-from-gesture-initiated-event.html [ Crash Failure ] crbug.com/591099 fast/events/popup-allowed-from-gesture-only-once-iframes.html [ Timeout ] crbug.com/591099 fast/events/popup-allowed-from-gesture-only-once-two-events.html [ Failure ] -crbug.com/591099 fast/events/popup-allowed-from-gesture-only-once.html [ Failure ] +crbug.com/591099 fast/events/popup-allowed-from-gesture-only-once.html [ Failure Timeout ] crbug.com/591099 fast/events/popup-allowed-from-pointerup-exactly-once.html [ Crash ] crbug.com/591099 fast/events/popup-blocked-from-different-frames.html [ Failure ] crbug.com/591099 fast/events/popup-blocked-from-wrong-event.html [ Failure ] @@ -10385,7 +10362,6 @@ crbug.com/591099 fast/forms/button/button-inner-block-reuse.html [ Failure ] crbug.com/591099 fast/forms/button/button-submit.html [ Failure Pass ] crbug.com/591099 fast/forms/button/button-white-space.html [ Failure ] -crbug.com/591099 fast/forms/button/button-with-float.html [ Crash Failure Pass ] crbug.com/591099 fast/forms/calendar-picker/calendar-picker-appearance-zoom125.html [ Failure Timeout ] crbug.com/591099 fast/forms/calendar-picker/calendar-picker-appearance-zoom200.html [ Failure ] crbug.com/591099 fast/forms/calendar-picker/calendar-picker-date-types.html [ Failure Timeout ] @@ -10593,7 +10569,7 @@ crbug.com/591099 fast/forms/focus-with-display-block.html [ Failure ] crbug.com/591099 fast/forms/focus.html [ Crash Failure ] crbug.com/591099 fast/forms/focus2.html [ Crash ] -crbug.com/591099 fast/forms/form-added-to-table.html [ Failure ] +crbug.com/591099 fast/forms/form-added-to-table.html [ Failure Pass ] crbug.com/591099 fast/forms/form-and-frame-interaction-retains-values.html [ Crash Failure ] crbug.com/591099 fast/forms/form-associated-element-crash.html [ Crash Failure ] crbug.com/591099 fast/forms/form-associated-element-crash2.html [ Failure ] @@ -10946,7 +10922,6 @@ crbug.com/591099 fast/forms/select/disabled-select-change-index.html [ Failure ] crbug.com/591099 fast/forms/select/exceptions.html [ Failure ] crbug.com/591099 fast/forms/select/hidden-listbox.html [ Failure ] -crbug.com/591099 fast/forms/select/input-select-after-resize.html [ Crash Failure Pass Timeout ] crbug.com/591099 fast/forms/select/listbox-appearance-basic.html [ Failure ] crbug.com/591099 fast/forms/select/listbox-appearance-separator.html [ Failure ] crbug.com/591099 fast/forms/select/listbox-bidi-align.html [ Failure ] @@ -11146,7 +11121,7 @@ crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-appearance-zoom125.html [ Crash Failure Timeout ] crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-appearance-zoom200.html [ Crash Failure ] crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-key-operations.html [ Crash Failure Timeout ] -crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-min-max-attribute.html [ Crash Failure ] +crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-min-max-attribute.html [ Crash Failure Timeout ] crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-reset-value-after-reload.html [ Crash ] crbug.com/591099 fast/forms/suggestion-picker/date-suggestion-picker-step-attribute.html [ Crash Failure ] crbug.com/591099 fast/forms/suggestion-picker/datetimelocal-suggestion-picker-appearance-locale-hebrew.html [ Crash Failure Timeout ] @@ -12297,7 +12272,6 @@ crbug.com/591099 fast/multicol/client-rects.html [ Failure ] crbug.com/591099 fast/multicol/column-break-with-balancing.html [ Failure ] crbug.com/591099 fast/multicol/column-count-with-rules.html [ Failure ] -crbug.com/591099 fast/multicol/column-rules.html [ Failure Pass ] crbug.com/591099 fast/multicol/column-width-zero.html [ Failure ] crbug.com/591099 fast/multicol/columns-shorthand-parsing-2.html [ Failure ] crbug.com/591099 fast/multicol/composited-inner-multicol.html [ Failure ] @@ -12373,7 +12347,6 @@ crbug.com/591099 fast/multicol/flipped-blocks-border-after.html [ Failure ] crbug.com/591099 fast/multicol/flipped-blocks-hit-test.html [ Failure Pass ] crbug.com/591099 fast/multicol/float-after-break-after.html [ Failure ] -crbug.com/591099 fast/multicol/float-avoidance.html [ Failure Pass ] crbug.com/591099 fast/multicol/float-beside-bfc.html [ Failure ] crbug.com/591099 fast/multicol/float-big-line.html [ Failure ] crbug.com/591099 fast/multicol/float-break.html [ Failure ] @@ -12511,7 +12484,6 @@ crbug.com/591099 fast/multicol/span/clone-anonymous-block-non-inline-child-crash.html [ Crash Failure ] crbug.com/591099 fast/multicol/span/fill-after-spanner-exact-fit.html [ Failure ] crbug.com/591099 fast/multicol/span/fill-after-spanner-extra-height.html [ Failure ] -crbug.com/591099 fast/multicol/span/float.html [ Failure Pass ] crbug.com/591099 fast/multicol/span/foreignObject.html [ Failure ] crbug.com/591099 fast/multicol/span/in-nested-multicol-with-hard-breaks.html [ Failure ] crbug.com/591099 fast/multicol/span/in-nested-multicol-with-list-item.html [ Failure ] @@ -12529,7 +12501,6 @@ crbug.com/591099 fast/multicol/span/outer-column-break-after-inner-spanner-and-float.html [ Failure ] crbug.com/591099 fast/multicol/span/outer-column-break-after-inner-spanner.html [ Failure ] crbug.com/591099 fast/multicol/span/outline.html [ Failure ] -crbug.com/591099 fast/multicol/span/outside-multicol.html [ Failure Pass ] crbug.com/591099 fast/multicol/span/padding-before-unbreakable-content-crash.html [ Crash Failure ] crbug.com/591099 fast/multicol/span/percent-margins.html [ Failure ] crbug.com/591099 fast/multicol/span/preferred-widths-with-column-content.html [ Failure ] @@ -12548,7 +12519,7 @@ crbug.com/591099 fast/multicol/span/spanner-first.html [ Crash Failure ] crbug.com/591099 fast/multicol/span/spanner-img.html [ Crash Failure ] crbug.com/591099 fast/multicol/span/spanner-in-flexbox-in-multicol-in-flexbox-crash.html [ Failure ] -crbug.com/591099 fast/multicol/span/spanner-inline-block.html [ Failure ] +crbug.com/591099 fast/multicol/span/spanner-inline-block.html [ Failure Pass ] crbug.com/591099 fast/multicol/span/spanner-with-margin.html [ Crash Failure ] crbug.com/591099 fast/multicol/span/summary-split.html [ Failure ] crbug.com/591099 fast/multicol/span/two-rows-then-spanner-then-two-rows.html [ Failure ] @@ -12558,7 +12529,6 @@ crbug.com/591099 fast/multicol/table-caption-with-block.html [ Failure ] crbug.com/591099 fast/multicol/table-cell-content-change-with-decorations.html [ Failure ] crbug.com/591099 fast/multicol/table-cell-content-change.html [ Failure ] -crbug.com/591099 fast/multicol/tall-float1.html [ Failure Pass ] crbug.com/591099 fast/multicol/textarea-with-placeholder-as-multicol-crash.html [ Failure ] crbug.com/591099 fast/multicol/three-inner-rows.html [ Failure ] crbug.com/591099 fast/multicol/transform-inside-opacity.html [ Crash Failure ] @@ -12928,12 +12898,11 @@ crbug.com/591099 fast/replaced/vertical-rl/absolute-position-with-auto-height-and-top-and-bottom.html [ Failure ] crbug.com/591099 fast/replaced/vertical-rl/absolute-position-with-auto-width-and-left-and-right.html [ Failure ] crbug.com/591099 fast/replaced/vertical-writing-mode-max-logical-width-replaced.html [ Failure ] -crbug.com/591099 fast/replaced/width100percent-checkbox.html [ Failure ] -crbug.com/591099 fast/replaced/width100percent-radio.html [ Failure ] +crbug.com/591099 fast/replaced/width100percent-checkbox.html [ Failure Pass ] +crbug.com/591099 fast/replaced/width100percent-radio.html [ Failure Pass ] crbug.com/591099 fast/ruby/base-shorter-than-text.html [ Crash Failure ] crbug.com/591099 fast/ruby/float-overhang-from-ruby-text.html [ Crash Failure ] crbug.com/591099 fast/ruby/floating-ruby-text.html [ Crash Failure ] -crbug.com/591099 fast/ruby/generated-before-counter-doesnt-crash.html [ Crash Failure Pass ] crbug.com/591099 fast/ruby/line-break-ruby.html [ Crash ] crbug.com/591099 fast/ruby/list-item-marker-in-block-ruby.html [ Crash Failure ] crbug.com/591099 fast/ruby/merge-adjacent-anonymous-blocks-inside-ruby-run.html [ Crash Failure ] @@ -13115,6 +13084,7 @@ crbug.com/591099 fast/selectors/querySelector-leftmost-selector-matches-ancestor.html [ Failure ] crbug.com/591099 fast/selectors/querySelector-leftmost-selector-matches-rootNode.html [ Failure ] crbug.com/591099 fast/selectors/querySelector-scope.html [ Crash Failure ] +crbug.com/591099 fast/selectors/shadow-host-div-with-text.html [ Failure ] crbug.com/591099 fast/selectors/specificity-overflow.html [ Failure ] crbug.com/591099 fast/selectors/style-sharing-adjacent-selector.html [ Failure ] crbug.com/591099 fast/selectors/style-sharing-attribute-selector.html [ Failure ] @@ -13254,6 +13224,7 @@ crbug.com/591099 fast/sub-pixel/should-not-repaint-subpixel-composited-layer.html [ Failure Pass ] crbug.com/591099 fast/sub-pixel/size-of-box-with-zoom.html [ Failure ] crbug.com/591099 fast/sub-pixel/size-of-span-with-different-positions.html [ Failure ] +crbug.com/591099 fast/sub-pixel/sub-pixel-border-2.html [ Failure ] crbug.com/591099 fast/sub-pixel/sub-pixel-border.html [ Crash ] crbug.com/591099 fast/sub-pixel/sub-pixel-precision-on-height-of-replaced-element.html [ Failure ] crbug.com/591099 fast/sub-pixel/table-rows-have-stable-height.html [ Failure ] @@ -13729,6 +13700,8 @@ crbug.com/591099 fast/text/reset-drag-on-mouse-down.html [ Failure Timeout ] crbug.com/591099 fast/text/reset-emptyRun.html [ Failure ] crbug.com/591099 fast/text/selection-hard-linebreak.html [ Failure ] +crbug.com/591099 fast/text/selection-rect-line-height-too-big.html [ Failure ] +crbug.com/591099 fast/text/selection-rect-line-height-too-small.html [ Failure ] crbug.com/591099 fast/text/selection-with-inline-padding.html [ Failure ] crbug.com/591099 fast/text/shadow-no-blur.html [ Failure ] crbug.com/591099 fast/text/shadow-translucent-fill.html [ Failure ] @@ -13811,7 +13784,7 @@ crbug.com/591099 fast/text/word-space-between-inlines.html [ Failure ] crbug.com/591099 fast/text/word-space.html [ Failure ] crbug.com/591099 fast/text/word-wrap-whitespace-pre.html [ Failure Pass ] -crbug.com/591099 fast/text/writing-root-with-overflow-clip-baseline.html [ Crash Failure ] +crbug.com/591099 fast/text/writing-root-with-overflow-clip-baseline.html [ Crash Failure Pass ] crbug.com/591099 fast/text/zero-font-size.html [ Failure ] crbug.com/591099 fast/text/zero-width-characters-complex-script.html [ Failure ] crbug.com/591099 fast/text/zero-width-characters.html [ Failure ] @@ -13983,7 +13956,6 @@ crbug.com/591099 fast/writing-mode/text-combine-various-fonts.html [ Failure ] crbug.com/591099 fast/writing-mode/text-orientation-basic.html [ Failure ] crbug.com/591099 fast/writing-mode/vertical-baseline-alignment.html [ Failure ] -crbug.com/591099 fast/writing-mode/vertical-float-margin.html [ Failure Pass ] crbug.com/591099 fast/writing-mode/vertical-font-fallback.html [ Failure ] crbug.com/591099 fast/writing-mode/vertical-inline-block-hittest.html [ Crash ] crbug.com/591099 fast/writing-mode/vertical-lr-replaced-selection.html [ Failure ] @@ -14075,7 +14047,7 @@ crbug.com/591099 fast/xsl/xslt-xhtml-template.xml [ Failure ] crbug.com/591099 fast/xsl/xslt_unicode.xml [ Failure ] crbug.com/591099 fonts/cursive.html [ Failure Pass ] -crbug.com/591099 fonts/fantasy.html [ Failure ] +crbug.com/591099 fonts/fantasy.html [ Failure Pass ] crbug.com/591099 fonts/monospace.html [ Failure ] crbug.com/591099 fonts/sans-serif.html [ Failure ] crbug.com/591099 fonts/serif.html [ Failure ] @@ -14677,7 +14649,7 @@ crbug.com/591099 http/tests/inspector/bindings/shadowdom-navigator.html [ Failure Timeout ] crbug.com/591099 http/tests/inspector/bindings/sourcemap-bindings-multiple-frames.html [ Crash Timeout ] crbug.com/591099 http/tests/inspector/bindings/sourcemap-navigator-multiple-frames.html [ Crash Timeout ] -crbug.com/591099 http/tests/inspector/bindings/suspendtarget-bindings.html [ Crash ] +crbug.com/591099 http/tests/inspector/bindings/suspendtarget-bindings.html [ Crash Timeout ] crbug.com/591099 http/tests/inspector/bindings/suspendtarget-navigator.html [ Crash ] crbug.com/591099 http/tests/inspector/cache-storage/cache-data.html [ Failure Timeout ] crbug.com/591099 http/tests/inspector/cache-storage/cache-deletion.html [ Failure ] @@ -15177,7 +15149,6 @@ crbug.com/591099 http/tests/navigation/forward-to-fragment-fires-onload.html [ Crash Failure ] crbug.com/591099 http/tests/navigation/history-back-across-form-submission-to-fragment.html [ Failure ] crbug.com/591099 http/tests/navigation/image-load-in-subframe-unload-handler.html [ Crash ] -crbug.com/591099 http/tests/navigation/image-load-in-unload-handler.html [ Crash Pass ] crbug.com/591099 http/tests/navigation/javascriptlink-basic.html [ Crash Failure Timeout ] crbug.com/591099 http/tests/navigation/javascriptlink-goback.html [ Crash Failure Timeout ] crbug.com/591099 http/tests/navigation/lockedhistory-iframe.html [ Failure ] @@ -15235,7 +15206,6 @@ crbug.com/591099 http/tests/pointer-lock/pointerlockelement-same-origin.html [ Failure ] crbug.com/591099 http/tests/pointer-lock/requestPointerLock-can-not-transfer-between-documents.html [ Failure ] crbug.com/591099 http/tests/preload/dynamic_remove_preload_href.html [ Failure Pass ] -crbug.com/591099 http/tests/preload/dynamic_removing_preload.html [ Failure Pass ] crbug.com/591099 http/tests/preload/multiple-meta-csp.html [ Crash ] crbug.com/591099 http/tests/preload/preload-video-cors.html [ Crash ] crbug.com/591099 http/tests/previews/client-lofi-sprite.html [ Failure ] @@ -16369,8 +16339,6 @@ crbug.com/591099 inspector-protocol/css/cssom-matching-rules.html [ Failure ] crbug.com/591099 inspector-protocol/css/cssom-modify-rule-and-get-rule-list.html [ Failure ] crbug.com/591099 inspector-protocol/css/media-query-listener-exception.html [ Failure ] -crbug.com/591099 inspector-protocol/debugger/debugger-step-into-dedicated-worker.html [ Failure ] -crbug.com/591099 inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html [ Failure ] crbug.com/591099 inspector-protocol/dom-snapshot/dom-snapshot-getSnapshot.js [ Crash Failure Timeout ] crbug.com/591099 inspector-protocol/emulation/device-emulation-small-dw.js [ Failure ] crbug.com/591099 inspector-protocol/emulation/device-emulation-small.js [ Failure ] @@ -16554,9 +16522,9 @@ crbug.com/591099 inspector/database-table-name-excaping.html [ Failure ] crbug.com/591099 inspector/device-mode/device-mode-responsive.html [ Crash Failure ] crbug.com/591099 inspector/device-mode/device-mode-switching-devices.html [ Crash Failure ] -crbug.com/591099 inspector/device-mode/forced-viewport-unobserved.html [ Failure ] +crbug.com/591099 inspector/device-mode/forced-viewport-unobserved.html [ Crash Failure ] crbug.com/591099 inspector/diff-module.html [ Failure ] -crbug.com/591099 inspector/domdebugger/domdebugger-getEventListeners.html [ Crash Failure ] +crbug.com/591099 inspector/domdebugger/domdebugger-getEventListeners.html [ Crash Failure Timeout ] crbug.com/591099 inspector/editor/php-highlighter.html [ Crash Failure ] crbug.com/591099 inspector/editor/text-editor-auto-whitespace-removing.html [ Crash Failure Timeout ] crbug.com/591099 inspector/editor/text-editor-block-indent.html [ Crash Failure Timeout ] @@ -16576,8 +16544,8 @@ crbug.com/591099 inspector/editor/text-editor-smart-braces.html [ Crash Failure ] crbug.com/591099 inspector/editor/text-editor-token-at-position.html [ Crash Failure ] crbug.com/591099 inspector/editor/text-editor-word-jumps.html [ Crash Failure Timeout ] -crbug.com/591099 inspector/elements/accessibility/autocomplete-attribute.html [ Crash ] -crbug.com/591099 inspector/elements/accessibility/edit-aria-attributes.html [ Crash ] +crbug.com/591099 inspector/elements/accessibility/autocomplete-attribute.html [ Crash Timeout ] +crbug.com/591099 inspector/elements/accessibility/edit-aria-attributes.html [ Crash Timeout ] crbug.com/591099 inspector/elements/attribute-modified-ns.html [ Crash ] crbug.com/591099 inspector/elements/bidi-dom-tree.html [ Crash ] crbug.com/591099 inspector/elements/breadcrumb-updates.html [ Crash ] @@ -16615,7 +16583,7 @@ crbug.com/591099 inspector/elements/elements-inspect-iframe-from-different-domain.html [ Crash ] crbug.com/591099 inspector/elements/elements-panel-correct-case.html [ Crash ] crbug.com/591099 inspector/elements/elements-panel-limited-children.html [ Crash ] -crbug.com/591099 inspector/elements/elements-panel-reload-assert.html [ Crash ] +crbug.com/591099 inspector/elements/elements-panel-reload-assert.html [ Crash Timeout ] crbug.com/591099 inspector/elements/elements-panel-restore-selection-when-node-comes-later.html [ Crash ] crbug.com/591099 inspector/elements/elements-panel-rewrite-href.html [ Crash ] crbug.com/591099 inspector/elements/elements-panel-search.html [ Crash ] @@ -16718,7 +16686,7 @@ crbug.com/591099 inspector/elements/styles-2/paste-property.html [ Crash ] crbug.com/591099 inspector/elements/styles-2/perform-undo-perform-of-mergable-action.html [ Crash ] crbug.com/591099 inspector/elements/styles-2/property-ui-location.html [ Crash ] -crbug.com/591099 inspector/elements/styles-2/pseudo-elements.html [ Crash ] +crbug.com/591099 inspector/elements/styles-2/pseudo-elements.html [ Crash Timeout ] crbug.com/591099 inspector/elements/styles-2/region-style-crash.html [ Crash ] crbug.com/591099 inspector/elements/styles-3/computed-properties-retain-expanded.html [ Crash ] crbug.com/591099 inspector/elements/styles-3/remove-shadow-host.html [ Crash ] @@ -16771,7 +16739,7 @@ crbug.com/591099 inspector/elements/styles-4/styles-source-lines.html [ Crash ] crbug.com/591099 inspector/elements/styles-4/styles-source-offsets.html [ Crash ] crbug.com/591099 inspector/elements/styles-4/styles-update-from-js.html [ Crash ] -crbug.com/591099 inspector/elements/styles-4/styles-update-links-1.html [ Crash ] +crbug.com/591099 inspector/elements/styles-4/styles-update-links-1.html [ Crash Timeout ] crbug.com/591099 inspector/elements/styles-4/styles-update-links-2.html [ Crash ] crbug.com/591099 inspector/elements/styles-4/styles-update-links-3.html [ Crash ] crbug.com/591099 inspector/elements/styles-4/styles-update-links-4.html [ Crash ] @@ -16946,7 +16914,7 @@ crbug.com/591099 inspector/sources/debugger-breakpoints/event-listener-breakpoints-xhr.html [ Failure ] crbug.com/591099 inspector/sources/debugger-breakpoints/event-listener-breakpoints.html [ Failure ] crbug.com/591099 inspector/sources/debugger-breakpoints/nodejs-set-breakpoint.html [ Failure ] -crbug.com/591099 inspector/sources/debugger-breakpoints/possible-breakpoints.html [ Failure ] +crbug.com/591099 inspector/sources/debugger-breakpoints/possible-breakpoints.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger-breakpoints/set-breakpoint.html [ Failure Timeout ] crbug.com/591099 inspector/sources/debugger-breakpoints/set-conditional-breakpoint.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger-breakpoints/use-possible-breakpoints-to-resolve-breakpoint.html [ Failure ] @@ -17049,7 +17017,7 @@ crbug.com/591099 inspector/sources/debugger/debugger-compile-and-run.html [ Failure ] crbug.com/591099 inspector/sources/debugger/debugger-completions-on-call-frame.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger/debugger-cyclic-reference.html [ Failure ] -crbug.com/591099 inspector/sources/debugger/debugger-disable-enable.html [ Failure ] +crbug.com/591099 inspector/sources/debugger/debugger-disable-enable.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger/debugger-es6-harmony-scopes.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger/debugger-minified-variables-evalution.html [ Failure ] crbug.com/591099 inspector/sources/debugger/debugger-proto-property.html [ Crash Failure ] @@ -17073,7 +17041,7 @@ crbug.com/591099 inspector/sources/debugger/mutation-observer-suspend-while-paused.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger/navigator-view.html [ Failure Timeout ] crbug.com/591099 inspector/sources/debugger/network-uisourcecode-provider.html [ Failure ] -crbug.com/591099 inspector/sources/debugger/open-close-open.html [ Failure ] +crbug.com/591099 inspector/sources/debugger/open-close-open.html [ Crash Failure ] crbug.com/591099 inspector/sources/debugger/properties-special.html [ Failure ] crbug.com/591099 inspector/sources/debugger/resource-script-mapping.html [ Failure ] crbug.com/591099 inspector/sources/debugger/rethrow-error-from-bindings-crash.html [ Failure ] @@ -17084,7 +17052,7 @@ crbug.com/591099 inspector/sources/debugger/sources-panel-content-scripts.html [ Crash Failure ] crbug.com/591099 inspector/sources/formatter-css.html [ Crash Failure ] crbug.com/591099 inspector/sources/formatter-js.html [ Failure ] -crbug.com/591099 inspector/sources/inspect-function.html [ Failure ] +crbug.com/591099 inspector/sources/inspect-function.html [ Crash Failure ] crbug.com/591099 inspector/sources/javascript-outline-dialog.html [ Crash Failure ] crbug.com/591099 inspector/sources/outline-javascript-1.html [ Crash Failure ] crbug.com/591099 inspector/sources/outline-javascript-2.html [ Failure ] @@ -17125,6 +17093,7 @@ crbug.com/591099 inspector/tabbed-pane-max-tab-width-calculation.html [ Failure ] crbug.com/591099 inspector/tabbed-pane-tabs-to-show.html [ Failure Timeout ] crbug.com/591099 inspector/text-autosizing-override.html [ Failure ] +crbug.com/591099 inspector/throttling/mobile-throttling.html [ Failure ] crbug.com/591099 inspector/tracing-browser-thread.html [ Failure ] crbug.com/591099 inspector/tracing-model-async.html [ Failure ] crbug.com/591099 inspector/tracing-model-ids.html [ Failure ] @@ -17706,7 +17675,6 @@ crbug.com/591099 paint/frames/frameset-with-stacking-contexts.html [ Failure ] crbug.com/591099 paint/high-contrast-mode/image-filter-all/text-on-backgrounds.html [ Failure ] crbug.com/591099 paint/images/animated-gif-last-frame-crash.html [ Crash ] -crbug.com/591099 paint/inline/floating-inline.html [ Failure Pass ] crbug.com/591099 paint/inline/focus-ring-under-absolute-with-relative-continuation.html [ Failure ] crbug.com/591099 paint/inline/outline-offset.html [ Failure ] crbug.com/591099 paint/invalidation/4774354.html [ Failure ] @@ -18379,7 +18347,6 @@ crbug.com/591099 plugins/override-node-method.html [ Failure ] crbug.com/591099 plugins/page-scale-does-not-affect-plugin-height.html [ Crash ] crbug.com/591099 plugins/plugin-destroyed-enumerate.html [ Crash ] -crbug.com/591099 plugins/plugin-document-back-forward.html [ Pass Timeout ] crbug.com/591099 plugins/plugin-initiate-popup-window.html [ Timeout ] crbug.com/591099 plugins/plugin-javascript-access.html [ Failure ] crbug.com/591099 plugins/plugin-paint-test.html [ Failure ] @@ -18486,7 +18453,6 @@ crbug.com/591099 scrollbars/basic-scrollbar.html [ Failure ] crbug.com/591099 scrollbars/border-box-rect-clips-scrollbars.html [ Failure Pass ] crbug.com/591099 scrollbars/custom-scrollbar-changing-style-relayout-body-scrollablearea.html [ Crash Pass Timeout ] -crbug.com/591099 scrollbars/custom-scrollbar-changing-style-relayout-div-body-scrollablearea.html [ Crash Pass Timeout ] crbug.com/591099 scrollbars/custom-scrollbar-enable-changes-thickness-with-iframe.html [ Failure Pass ] crbug.com/591099 scrollbars/custom-scrollbar-not-inherited-by-iframe.html [ Crash ] crbug.com/591099 scrollbars/custom-scrollbar-reconstruction-document-write.html [ Crash ] @@ -18523,6 +18489,8 @@ crbug.com/591099 security/block-test-no-port.html [ Crash Failure ] crbug.com/591099 security/block-test.html [ Crash Failure ] crbug.com/591099 security/cannot-read-self-from-file.html [ Crash ] +crbug.com/591099 sensor/accelerometer.html [ Crash ] +crbug.com/591099 sensor/orientation-sensor.html [ Crash ] crbug.com/591099 shadow-dom/crashes/focus-navigation-infinite-loop.html [ Crash ] crbug.com/591099 shadow-dom/css-cascade-inner-scope-important.html [ Failure ] crbug.com/591099 shadow-dom/css-cascade-outer-scope.html [ Failure ] @@ -19108,7 +19076,6 @@ crbug.com/591099 svg/custom/disallow-non-lengths-in-attrs.html [ Crash ] crbug.com/591099 svg/custom/display-none-a-does-not-stop-focus-navigation.html [ Crash ] crbug.com/591099 svg/custom/dominant-baseline-hanging.svg [ Failure ] -crbug.com/591099 svg/custom/draw-image-crash.html [ Crash Pass ] crbug.com/591099 svg/custom/elementTimeControl-nan-crash.html [ Failure ] crbug.com/591099 svg/custom/embedded-svg-allowed-in-dashboard.xml [ Failure ] crbug.com/591099 svg/custom/embedding-external-svgs.xhtml [ Failure Pass ] @@ -19772,7 +19739,6 @@ crbug.com/591099 svg/transforms/transform-boxsize-usecounter-no-trigger-1.html [ Crash ] crbug.com/591099 svg/transforms/transform-boxsize-usecounter-no-trigger-2.html [ Crash ] crbug.com/591099 svg/transforms/transform-origin-presentation-attribute.xhtml [ Failure ] -crbug.com/591099 svg/wicd/rightsizing-grid.html [ Failure Pass ] crbug.com/591099 svg/wicd/test-rightsizing-a.xhtml [ Failure ] crbug.com/591099 svg/wicd/test-rightsizing-b.xhtml [ Failure ] crbug.com/591099 svg/wicd/test-scalable-background-image1.xhtml [ Failure ] @@ -19819,7 +19785,6 @@ crbug.com/591099 tables/mozilla/bugs/bug113235-2.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug11384q.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug12008.html [ Failure ] -crbug.com/591099 tables/mozilla/bugs/bug120364.html [ Failure Pass ] crbug.com/591099 tables/mozilla/bugs/bug126742.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug1271.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug12908-1.html [ Failure ] @@ -19829,7 +19794,7 @@ crbug.com/591099 tables/mozilla/bugs/bug131020_iframe.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug13105.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug13118.html [ Failure ] -crbug.com/591099 tables/mozilla/bugs/bug1318.html [ Failure ] +crbug.com/591099 tables/mozilla/bugs/bug1318.html [ Failure Pass ] crbug.com/591099 tables/mozilla/bugs/bug133756-1.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug133948.html [ Failure ] crbug.com/591099 tables/mozilla/bugs/bug137388-3.html [ Failure ] @@ -20664,7 +20629,6 @@ crbug.com/591099 virtual/disable-spinvalidation/paint/frames/frameset-with-stacking-contexts.html [ Failure ] crbug.com/591099 virtual/disable-spinvalidation/paint/high-contrast-mode/image-filter-all/text-on-backgrounds.html [ Failure ] crbug.com/591099 virtual/disable-spinvalidation/paint/images/animated-gif-last-frame-crash.html [ Crash ] -crbug.com/591099 virtual/disable-spinvalidation/paint/inline/floating-inline.html [ Failure Pass ] crbug.com/591099 virtual/disable-spinvalidation/paint/inline/focus-ring-under-absolute-with-relative-continuation.html [ Failure ] crbug.com/591099 virtual/disable-spinvalidation/paint/inline/outline-offset.html [ Failure ] crbug.com/591099 virtual/disable-spinvalidation/paint/invalidation/4774354.html [ Failure ] @@ -22340,7 +22304,7 @@ crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrollbar-mousedown-mouseup.html [ Failure ] crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrollbar-mousedown-move-mouseup.html [ Failure ] crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrollbar-prevent-default.html [ Failure ] -crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrollbar-tickmarks-hittest.html [ Failure ] +crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrollbar-tickmarks-hittest.html [ Failure Timeout ] crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrolling-apis-nan-scroll-position.html [ Failure ] crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/scrolling-apis-subpixel.html [ Failure ] crbug.com/591099 virtual/rootlayerscrolls/fast/scrolling/set-root-scroller.html [ Failure ] @@ -22415,6 +22379,54 @@ crbug.com/591099 virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing.html [ Timeout ] crbug.com/591099 virtual/service-worker-navigation-preload-disabled/webexposed/nonstable-css-properties.html [ Failure ] crbug.com/591099 virtual/service-worker-navigation-preload-disabled/webexposed/permissions-attribute.html [ Failure ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/ServiceWorkerGlobalScope/extendable-message-event.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/ServiceWorkerGlobalScope/unregister.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/ServiceWorkerGlobalScope/update.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/activation.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/claim-fetch.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/claim-not-using-registration.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/claim-with-redirect.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/client-id.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-get-cross-origin.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-get.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-matchall-exact-controller.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-matchall-include-uncontrolled.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-matchall-order.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-matchall.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/extendable-event-async-waituntil.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-canvas-tainting-cache.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-canvas-tainting.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-cors-xhr.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-event.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-mixed-content-to-inscope.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-mixed-content-to-outscope.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-request-css-images.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-request-redirect.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-response-taint.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/foreign-fetch-basics.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/foreign-fetch-cors.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/foreign-fetch-workers.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/iframe-sandbox-register-link-element.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/multi-globals/url-parsing.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/navigation-preload/redirect.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/navigation-preload/resource-timing.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/navigation-redirect-to-http.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/navigation-redirect.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/ready.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/register-closed-window.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/register-link-header.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/register-same-scope-different-script-url.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/registration-iframe.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/unregister-controller.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/unregister-then-register-new-script.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/unregister-then-register.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/windowclient-navigate.https.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/frame-detached-by-navigation.html [ Crash ] +crbug.com/591099 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/resolve-after-window-close.html [ Failure ] +crbug.com/591099 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/service-worker-gc.html [ Failure ] +crbug.com/591099 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/window-close-during-registration.html [ Failure ] +crbug.com/591099 virtual/service-worker-script-streaming/http/tests/serviceworker/webexposed/global-interface-listing-service-worker.html [ Timeout ] crbug.com/591099 virtual/spv2/compositing/framesets/composited-frame-alignment.html [ Failure ] crbug.com/591099 virtual/spv2/compositing/geometry/outline-change.html [ Failure Pass ] crbug.com/591099 virtual/spv2/paint/invalidation/margin.html [ Failure Pass ] @@ -22435,7 +22447,6 @@ crbug.com/591099 virtual/stable/http/tests/navigation/forward-to-fragment-fires-onload.html [ Crash Failure ] crbug.com/591099 virtual/stable/http/tests/navigation/history-back-across-form-submission-to-fragment.html [ Failure ] crbug.com/591099 virtual/stable/http/tests/navigation/image-load-in-subframe-unload-handler.html [ Crash ] -crbug.com/591099 virtual/stable/http/tests/navigation/image-load-in-unload-handler.html [ Crash Pass ] crbug.com/591099 virtual/stable/http/tests/navigation/javascriptlink-basic.html [ Crash Failure Timeout ] crbug.com/591099 virtual/stable/http/tests/navigation/javascriptlink-goback.html [ Crash Failure Timeout ] crbug.com/591099 virtual/stable/http/tests/navigation/lockedhistory-iframe.html [ Failure ] @@ -22501,7 +22512,7 @@ crbug.com/591099 virtual/threaded/animations/3d/state-at-end-event-transform.html [ Failure Pass ] crbug.com/591099 virtual/threaded/animations/animation-css-rule-types.html [ Failure ] crbug.com/591099 virtual/threaded/animations/animation-events-create.html [ Failure ] -crbug.com/591099 virtual/threaded/animations/animation-inherit-initial-unprefixed.html [ Failure ] +crbug.com/591099 virtual/threaded/animations/prefixed/animation-inherit-initial-unprefixed.html [ Failure ] crbug.com/591099 virtual/threaded/animations/animations-parsing.html [ Timeout ] crbug.com/591099 virtual/threaded/animations/animations-responsive-to-color-change.html [ Crash ] crbug.com/591099 virtual/threaded/animations/clear-svg-animation-effects.html [ Crash ] @@ -22602,8 +22613,8 @@ crbug.com/591099 virtual/threaded/animations/interpolation/webkit-text-stroke-color-interpolation.html [ Crash ] crbug.com/591099 virtual/threaded/animations/interpolation/webkit-transform-interpolation.html [ Crash ] crbug.com/591099 virtual/threaded/animations/interpolation/webkit-transform-origin-interpolation.html [ Crash ] -crbug.com/591099 virtual/threaded/animations/keyframes-cssom-prefixed-02.html [ Failure ] -crbug.com/591099 virtual/threaded/animations/keyframes-cssom-unprefixed-02.html [ Failure ] +crbug.com/591099 virtual/threaded/animations/prefixed/keyframes-cssom-prefixed-02.html [ Failure ] +crbug.com/591099 virtual/threaded/animations/prefixed/keyframes-cssom-unprefixed-02.html [ Failure ] crbug.com/591099 virtual/threaded/animations/keyframes-rule.html [ Failure ] crbug.com/591099 virtual/threaded/animations/lazy-detached-animation-stop.html [ Failure ] crbug.com/591099 virtual/threaded/animations/negative-delay-events.html [ Failure ] @@ -23002,6 +23013,7 @@ crbug.com/591099 vr/getLayers_presenting.html [ Crash ] crbug.com/591099 vr/getLayers_presenting_nondefaultbounds.html [ Crash ] crbug.com/591099 vr/getLayers_update.html [ Crash ] +crbug.com/591099 vr/requestAnimationFrame_consistentTimestamps.html [ Crash ] crbug.com/591099 vr/requestAnimationFrame_handoff.html [ Crash ] crbug.com/591099 vr/requestAnimationFrame_submitFrame_combinations.html [ Crash Timeout ] crbug.com/591099 vr/requestPresent_reject_badleftbounds.html [ Crash ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService index 17e0c13..344378c 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-features=NetworkService
@@ -384,6 +384,7 @@ Bug(none) external/wpt/html/browsers/history/the-location-interface/location-protocol-setter-non-broken.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/history/the-location-interface/location-prototype-setting-cross-origin.sub.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/history/the-location-interface/location-prototype-setting-goes-cross-origin-domain.sub.html [ Failure Timeout ] +Bug(none) external/wpt/html/browsers/offline/appcache/workers/appcache-worker.html [ Timeout ] Bug(none) external/wpt/html/browsers/offline/application-cache-api/api_status_idle.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/the-window-object/Window-document.html [ Failure Timeout ] Bug(none) external/wpt/html/browsers/the-window-object/apis-for-creating-and-navigating-browsing-contexts-by-name/creating_browsing_context_test_01.html [ Failure Timeout ] @@ -2448,7 +2449,7 @@ Bug(none) http/tests/security/media-element-audio-source-node-cross-origin-allowed.html [ Timeout ] Bug(none) http/tests/security/media-element-audio-source-node-cross-origin-with-credentials.html [ Failure Timeout ] Bug(none) http/tests/security/media-element-audio-source-node-cross-origin.html [ Timeout ] -Bug(none) http/tests/security/media-element-audio-source-node-same-origin.html [ Timeout ] +Bug(none) http/tests/security/media-element-audio-source-node-same-origin.html [ Failure Pass ] Bug(none) http/tests/security/mime-type-execute-as-html-01.html [ Failure ] Bug(none) http/tests/security/mime-type-execute-as-html-04.html [ Failure ] Bug(none) http/tests/security/mixedContent/about-blank-iframe-in-main-frame.html [ Timeout ] @@ -3357,3 +3358,4 @@ Bug(none) webshare/share-nonutf8-encoding.html [ Timeout ] Bug(none) webshare/share-success.html [ Timeout ] Bug(none) webshare/share-types.html [ Timeout ] +Bug(none) webshare/share-url-relative.html [ Timeout ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index ee82b8a..076356f 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -1075,7 +1075,6 @@ Bug(none) paint/invalidation/compositing/squash-partial-repaint-inside-squashed-layer.html [ Failure ] Bug(none) paint/invalidation/compositing/squashing-inside-preserve-3d-element.html [ Failure ] Bug(none) paint/invalidation/compositing/stacked-float-under-composited-inline.html [ Failure ] -Bug(none) paint/invalidation/compositing/subpixel-offset-scaled-transform-composited.html [ Failure ] Bug(none) paint/invalidation/compositing/tricky-element-removal-crash.html [ Failure ] Bug(none) paint/invalidation/compositing/updating-scrolling-content.html [ Failure ] Bug(none) paint/invalidation/create-layer-repaint.html [ Failure ] @@ -1741,3 +1740,8 @@ Bug(none) compositing/overflow/ancestor-overflow-layer-of-sticky-child-of-compositing-container.html [ Failure ] Bug(none) fast/block/float/float-change-composited-scrolling.html [ Failure ] + +# See comment regarding this test in NeverFixTests. It also fails for other +# reasons, in particular that the composited layerization algorithm provides +# different results. +Bug(none) paint/invalidation/compositing/subpixel-offset-scaled-transform-composited.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process index c0c3b9f..91c9d6d 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process +++ b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process
@@ -6,6 +6,8 @@ # Both of the bugs above need to be fixed, before enabling the tests below. crbug.com/393285 http/tests/text-autosizing/narrow-iframe.html [ Failure ] crbug.com/393285 http/tests/text-autosizing/wide-iframe.html [ Failure ] +crbug.com/393285 virtual/mojo-loading/http/tests/text-autosizing/narrow-iframe.html [ Failure ] +crbug.com/393285 virtual/mojo-loading/http/tests/text-autosizing/wide-iframe.html [ Failure ] # https://crbug.com/710098: Tests failing because of r462933. crbug.com/710098 http/tests/security/document-all.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/LeakExpectations b/third_party/WebKit/LayoutTests/LeakExpectations index 7a951e73..8c29ea7c 100644 --- a/third_party/WebKit/LayoutTests/LeakExpectations +++ b/third_party/WebKit/LayoutTests/LeakExpectations
@@ -42,9 +42,11 @@ crbug.com/506754 http/tests/serviceworker/chromium/resolve-after-window-close.html [ Leak ] crbug.com/506754 virtual/mojo-loading/http/tests/serviceworker/chromium/resolve-after-window-close.html [ Leak ] crbug.com/506754 virtual/off-main-thread-fetch/http/tests/serviceworker/chromium/resolve-after-window-close.html [ Leak ] +crbug.com/506754 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/resolve-after-window-close.html [ Leak ] crbug.com/506754 http/tests/serviceworker/chromium/window-close-during-registration.html [ Leak ] crbug.com/506754 virtual/mojo-loading/http/tests/serviceworker/chromium/window-close-during-registration.html [ Leak ] crbug.com/506754 virtual/off-main-thread-fetch/http/tests/serviceworker/chromium/window-close-during-registration.html [ Leak ] +crbug.com/506754 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/window-close-during-registration.html [ Leak ] # ----------------------------------------------------------------- # Leaks in external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/*
diff --git a/third_party/WebKit/LayoutTests/MSANExpectations b/third_party/WebKit/LayoutTests/MSANExpectations index 1688d3a0..d58330c 100644 --- a/third_party/WebKit/LayoutTests/MSANExpectations +++ b/third_party/WebKit/LayoutTests/MSANExpectations
@@ -60,3 +60,5 @@ crbug.com/729136 [ Linux ] inspector/components/file-path-scoring.html [ Timeout ] crbug.com/729136 [ Linux ] inspector/elements/styles-4/styles-should-not-force-sync-style-recalc.html [ Timeout ] crbug.com/729136 [ Linux ] webaudio/mixing.html [ Timeout ] + +crbug.com/739365 [ Linux ] virtual/layout_ng/fast/block/float/assert-when-moving-float.html [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/NeverFixTests b/third_party/WebKit/LayoutTests/NeverFixTests index 9bfedb0..5a3e9f1 100644 --- a/third_party/WebKit/LayoutTests/NeverFixTests +++ b/third_party/WebKit/LayoutTests/NeverFixTests
@@ -906,3 +906,8 @@ [ Win7 Debug ] fast/table/backgr_border-table-column-group-collapsed-border.html [ WontFix ] [ Win7 Debug ] virtual/mojo-loading/fast/table/backgr_border-table-column-group-collapsed-border.html [ WontFix ] +# Fails in debug mode, because in debug mode we recompute visual rects after +# changes to subpixel offsets of composited layers to detect under-invalidation +# in testing, whereas otherwise we do not do so if the composited layer has a +# direct compositing reason (for performance). Only applies to SPv1. +Bug(none) paint/invalidation/compositing/subpixel-offset-scaled-transform-composited.html [ WontFix ]
diff --git a/third_party/WebKit/LayoutTests/SlowTests b/third_party/WebKit/LayoutTests/SlowTests index 89e2d00d..136a8465 100644 --- a/third_party/WebKit/LayoutTests/SlowTests +++ b/third_party/WebKit/LayoutTests/SlowTests
@@ -178,7 +178,7 @@ crbug.com/248938 virtual/threaded/animations/missing-values-last-keyframe.html [ Slow ] crbug.com/248938 virtual/threaded/animations/3d/replace-filling-transform.html [ Slow ] crbug.com/311482 virtual/threaded/animations/interpolation/filter-interpolation.html [ Slow ] -crbug.com/311482 virtual/threaded/animations/keyframes-unprefixed-03.html [ Slow ] +crbug.com/311482 virtual/threaded/animations/prefixed/keyframes-unprefixed-03.html [ Slow ] crbug.com/243871 virtual/threaded/fast/scroll-behavior/ [ Slow ] crbug.com/243871 virtual/threaded/fast/idle-callback/idle_periods.html [ Slow ] crbug.com/664857 virtual/threaded/animations/transform-responsive-neutral-keyframe.html [ Slow ] @@ -268,7 +268,7 @@ crbug.com/480769 virtual/mojo-loading/http/tests/inspector/service-workers/service-workers-redundant.html [ Slow ] crbug.com/480769 http/tests/inspector/service-workers/service-worker-agents.html [ Slow ] crbug.com/480769 virtual/mojo-loading/http/tests/inspector/service-workers/service-worker-agents.html [ Slow ] -crbug.com/504703 inspector-protocol/debugger/debugger-step-into-dedicated-worker.html [ Slow ] +crbug.com/504703 inspector-protocol/debugger/debugger-step-into-dedicated-worker.js [ Slow ] crbug.com/535478 [ Win ] virtual/threaded/inspector/tracing/decode-resize.html [ Slow ] crbug.com/548765 http/tests/inspector/console-fetch-logging.html [ Slow ] crbug.com/548765 virtual/mojo-loading/http/tests/inspector/console-fetch-logging.html [ Slow ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 0fd4cfe1..d7ab1fa 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -402,7 +402,7 @@ crbug.com/636993 virtual/layout_ng/external/wpt/css/CSS2/linebox/vertical-align-sub-001.xht [ Failure ] crbug.com/636993 virtual/layout_ng/external/wpt/css/CSS2/linebox/vertical-align-super-001.xht [ Failure ] -# Atomic inline margins. +# Inline: abspos inline static positions. crbug.com/636993 virtual/layout_ng/external/wpt/css/CSS2/linebox/vertical-align-baseline-004a.xht [ Failure ] crbug.com/636993 virtual/layout_ng/external/wpt/css/CSS2/linebox/vertical-align-baseline-005a.xht [ Failure ] @@ -427,12 +427,8 @@ crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/block-in-inline-remove-005.xht [ Failure Pass ] # Inline: vertical-align. -crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/block-non-replaced-height-005.xht [ Failure ] crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/inline-table-zorder-005.xht [ Failure ] -# Inline: atomic inline margins. -crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/inline-block-non-replaced-height-002.xht [ Failure ] - # Inline: atomic inline preferred width. crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/inline-block-valign-001.xht [ Failure ] crbug.com/635619 virtual/layout_ng/external/wpt/css/CSS2/normal-flow/inline-block-valign-002.xht [ Failure ] @@ -874,6 +870,10 @@ crbug.com/487281 [ Mac ] fast/forms/select/menulist-narrow-width.html [ Failure ] +# Mark as Failure until the development is done. +crbug.com/739091 fast/forms/validation-bubble-appearance-edge.html [ Failure ] +crbug.com/739091 fast/forms/validation-bubble-appearance-iframe.html [ Failure ] + crbug.com/543110 [ Mac ] fast/text/international/text-shaping-arabic.html [ Failure ] crbug.com/731731 inspector-protocol/layers/paint-profiler-load-empty.js [ Failure Pass ] @@ -914,8 +914,8 @@ crbug.com/692560 external/wpt/html/semantics/document-metadata/styling/LinkStyle.html [ Failure Pass ] crbug.com/627706 external/wpt/html/semantics/embedded-content/the-img-element/invalid-src.html [ Skip ] # MANIFEST.json contains any *-manual.*. https://github.com/w3c/web-platform-tests/issues/4137 -Bug(github) external/wpt/uievents/keyboard/key-manual.css [ Skip ] -Bug(github) external/wpt/uievents/keyboard/key-manual.js [ Skip ] +Bug(github) external/wpt/uievents/keyboard/key.css [ Skip ] +Bug(github) external/wpt/uievents/keyboard/key.js [ Skip ] crbug.com/698135 external/wpt/editing/run/delete.html [ Crash Failure Timeout ] crbug.com/698165 external/wpt/editing/run/forwarddelete.html [ Pass Timeout ] @@ -952,8 +952,6 @@ crbug.com/652964 [ Linux Win ] fast/text/hyphens/hyphens-orphaned-word.html [ Skip ] crbug.com/652964 [ Linux Win ] fast/text/hyphens/midword-break-priority.html [ Skip ] -crbug.com/729514 paint/invalidation/compositing/subpixel-offset-scaled-transform-composited.html [ Pass Failure ] - crbug.com/405389 external/wpt/css/css-shapes-1/shape-outside/supported-shapes/polygon/shape-outside-polygon-017.html [ Failure ] crbug.com/424365 external/wpt/css/css-shapes-1/shape-outside/shape-image/shape-image-010.html [ Failure ] crbug.com/424365 external/wpt/css/css-shapes-1/shape-outside/shape-image/shape-image-024.html [ Failure ] @@ -2020,6 +2018,7 @@ crbug.com/626703 external/wpt/html/webappapis/idle-callbacks/callback-xhr-sync.html [ Timeout ] crbug.com/626703 external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/626703 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] +crbug.com/626703 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/update-bytecheck.https.html [ Timeout ] crbug.com/626703 [ Mac ] external/wpt/css/css-flexbox-1/auto-margins-001.html [ Failure ] crbug.com/626703 external/wpt/workers/name-property.html [ Timeout ] crbug.com/626703 external/wpt/pointerevents/pointerevent_disabled_form_control-manual.html [ Timeout Pass ] @@ -2378,6 +2377,7 @@ crbug.com/713732 http/tests/serviceworker/chromium/frame-detached-by-navigation.html [ NeedsManualRebaseline ] crbug.com/713732 virtual/mojo-loading/http/tests/serviceworker/chromium/frame-detached-by-navigation.html [ NeedsManualRebaseline ] crbug.com/713732 virtual/off-main-thread-fetch/http/tests/serviceworker/chromium/frame-detached-by-navigation.html [ NeedsManualRebaseline ] +crbug.com/713732 virtual/service-worker-script-streaming/http/tests/serviceworker/chromium/frame-detached-by-navigation.html [ NeedsManualRebaseline ] # Crashes with DCHECK enabled, but not on normal Release builds. crbug.com/626703 external/wpt/workers/opaque-origin.html [ Failure Crash Timeout ] @@ -2442,6 +2442,7 @@ crbug.com/675540 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/claim-with-redirect.https.html [ Skip ] crbug.com/658997 external/wpt/service-workers/service-worker/clients-matchall-client-types.https.html [ Skip ] crbug.com/658997 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/clients-matchall-client-types.https.html [ Skip ] +crbug.com/658997 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/clients-matchall-client-types.https.html [ Skip ] crbug.com/435547 http/tests/cachestorage/serviceworker/ignore-search-with-credentials.html [ Skip ] crbug.com/435547 virtual/mojo-loading/http/tests/cachestorage/serviceworker/ignore-search-with-credentials.html [ Skip ] @@ -2588,16 +2589,20 @@ crbug.com/602693 external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Timeout ] crbug.com/602693 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Timeout ] +crbug.com/602693 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Timeout ] # This test requires a special browser flag and seems not suitable for a wpt test, see bug. crbug.com/691944 external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] crbug.com/691944 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] +crbug.com/691944 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/update-after-oneday.https.html [ Skip ] # These tests (erroneously) see a platform-specific User-Agent header crbug.com/595993 external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] +crbug.com/595993 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-header-visibility.https.html [ Failure ] crbug.com/595993 external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/595993 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] +crbug.com/595993 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/request-end-to-end.https.html [ Failure ] crbug.com/735883 external/wpt/service-workers/service-worker/fetch-canvas-tainting.https.html [ Pass Failure ] crbug.com/735883 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/fetch-canvas-tainting.https.html [ Pass Failure ] @@ -2762,6 +2767,7 @@ # Flaky on trybots crbug.com/688486 external/wpt/service-workers/service-worker/fetch-request-resources.https.html [ Failure Pass ] crbug.com/688486 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/fetch-request-resources.https.html [ Failure Pass ] +crbug.com/688486 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-request-resources.https.html [ Failure Pass ] # Sheriff failures 2017-02-21 crbug.com/73609 http/tests/media/video-play-stall.html [ Pass Timeout ] @@ -2825,6 +2831,7 @@ crbug.com/715718 [ Win ] external/wpt/css/css-flexbox-1/flexbox_flex-natural-mixed-basis-auto.html [ Failure Pass ] crbug.com/723086 virtual/off-main-thread-fetch/external/wpt/service-workers/service-worker/fetch-event-redirect.https.html [ Timeout ] +crbug.com/739367 virtual/service-worker-script-streaming/external/wpt/service-workers/service-worker/fetch-event-redirect.https.html [ Timeout ] # Feature Policy changes same-origin allowpaymentrequest behaviour, tests need updating crbug.com/718155 payments/payment-request-in-iframe.html [ Failure ] @@ -2874,13 +2881,6 @@ crbug.com/729836 [ Win ] fast/workers/worker-document-leak.html [ Pass Failure ] -# Sensor tests fail on Mac swarming -crbug.com/731018 [ Mac ] sensor/accelerometer.html [ Failure Pass Crash ] -crbug.com/731018 [ Mac ] sensor/ambient-light-sensor.html [ Failure Pass Crash ] -crbug.com/731018 [ Mac ] sensor/gyroscope.html [ Failure Pass Crash ] -crbug.com/731018 [ Mac ] sensor/magnetometer.html [ Failure Pass Crash ] -crbug.com/731018 [ Mac ] sensor/orientation-sensor.html [ Failure Pass Crash ] - # More flaky tests on Mac crbug.com/731111 [ Mac ] http/tests/media/progress-events-generated-correctly.html [ Failure Pass Timeout ] crbug.com/731111 [ Mac ] http/tests/media/video-load-metadata-decode-error.html [ Failure Pass Timeout ]
diff --git a/third_party/WebKit/LayoutTests/VirtualTestSuites b/third_party/WebKit/LayoutTests/VirtualTestSuites index 5b456e5..d0da258 100644 --- a/third_party/WebKit/LayoutTests/VirtualTestSuites +++ b/third_party/WebKit/LayoutTests/VirtualTestSuites
@@ -406,6 +406,26 @@ "args": ["--disable-features=ServiceWorkerNavigationPreload"] }, { + "prefix": "service-worker-script-streaming", + "base": "external/wpt/service-workers", + "args": ["--enable-features=ServiceWorkerScriptStreaming"] + }, + { + "prefix": "service-worker-script-streaming", + "base": "http/tests/serviceworker", + "args": ["--enable-features=ServiceWorkerScriptStreaming"] + }, + { + "prefix": "service-worker-script-streaming", + "base": "http/tests/fetch/serviceworker", + "args": ["--enable-features=ServiceWorkerScriptStreaming"] + }, + { + "prefix": "service-worker-script-streaming", + "base": "http/tests/fetch/serviceworker-proxied", + "args": ["--enable-features=ServiceWorkerScriptStreaming"] + }, + { "prefix": "layout_ng", "base": "fast/block/basic", "args": ["--enable-blink-features=LayoutNG"]
diff --git a/third_party/WebKit/LayoutTests/animations/additive-transform-animations.html b/third_party/WebKit/LayoutTests/animations/additive-transform-animations.html index 2c94473..191b1da8 100644 --- a/third_party/WebKit/LayoutTests/animations/additive-transform-animations.html +++ b/third_party/WebKit/LayoutTests/animations/additive-transform-animations.html
@@ -14,7 +14,7 @@ animation-timing-function: linear; } -@-webkit-keyframes anim { +@keyframes anim { from { transform: rotate(0deg) translate(-100px, 0); } to { transform: rotate(180deg) translate(300px, 0); } }
diff --git a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware-expected.txt b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware-expected.txt index 81ec232..30117fb0 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware-expected.txt
@@ -1,17 +1,17 @@ -PASS - "webkitTransform" property for "box1" element at 0.2s saw something close to: 1,0,0,1,20,0 -PASS - "webkitTransform" property for "box2" element at 0.2s saw something close to: 1,0,0,1,20,0 -PASS - "webkitTransform" property for "box3" element at 0.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box4" element at 0.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box5" element at 0.2s saw something close to: 1,0,0,1,40,0 -PASS - "webkitTransform" property for "box6" element at 0.2s saw something close to: 1,0,0,1,40,0 -PASS - "webkitTransform" property for "box7" element at 0.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box8" element at 0.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box1" element at 2.2s saw something close to: 1,0,0,1,20,0 -PASS - "webkitTransform" property for "box2" element at 2.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box3" element at 2.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box4" element at 2.2s saw something close to: 1,0,0,1,20,0 -PASS - "webkitTransform" property for "box5" element at 2.2s saw something close to: 1,0,0,1,40,0 -PASS - "webkitTransform" property for "box6" element at 2.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box7" element at 2.2s saw something close to: 1,0,0,1,180,0 -PASS - "webkitTransform" property for "box8" element at 2.2s saw something close to: 1,0,0,1,40,0 +PASS - "transform" property for "box1" element at 0.2s saw something close to: 1,0,0,1,20,0 +PASS - "transform" property for "box2" element at 0.2s saw something close to: 1,0,0,1,20,0 +PASS - "transform" property for "box3" element at 0.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box4" element at 0.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box5" element at 0.2s saw something close to: 1,0,0,1,40,0 +PASS - "transform" property for "box6" element at 0.2s saw something close to: 1,0,0,1,40,0 +PASS - "transform" property for "box7" element at 0.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box8" element at 0.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box1" element at 2.2s saw something close to: 1,0,0,1,20,0 +PASS - "transform" property for "box2" element at 2.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box3" element at 2.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box4" element at 2.2s saw something close to: 1,0,0,1,20,0 +PASS - "transform" property for "box5" element at 2.2s saw something close to: 1,0,0,1,40,0 +PASS - "transform" property for "box6" element at 2.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box7" element at 2.2s saw something close to: 1,0,0,1,180,0 +PASS - "transform" property for "box8" element at 2.2s saw something close to: 1,0,0,1,40,0
diff --git a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware.html b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware.html index 6d737aa..75b20fb5 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware.html +++ b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-hardware.html
@@ -1,7 +1,7 @@ <!doctype html> <html> <head> - <title>Test of -webkit-animation-direction on composited elements</title> + <title>Test of animation-direction on composited elements</title> <style> body { margin: 0; @@ -14,44 +14,44 @@ height: 50px; width: 250px; margin-bottom: 10px; - -webkit-animation-duration: 2s; - -webkit-animation-timing-function: linear; - -webkit-animation-iteration-count: 8; + animation-duration: 2s; + animation-timing-function: linear; + animation-iteration-count: 8; } .move1 { - -webkit-animation-name: move1; + animation-name: move1; background-color: blue; color: white; } .move2 { - -webkit-animation-name: move2; + animation-name: move2; background-color: orange; } .normal { - -webkit-animation-direction: normal; + animation-direction: normal; } .alternate { - -webkit-animation-direction: alternate; + animation-direction: alternate; } .reverse { - -webkit-animation-direction: reverse; + animation-direction: reverse; } .alternate-reverse { - -webkit-animation-direction: alternate-reverse; + animation-direction: alternate-reverse; } - @-webkit-keyframes move1 { + @keyframes move1 { from { transform: translateX(0px); } to { transform: translateX(200px); } } - @-webkit-keyframes move2 { + @keyframes move2 { 0% { transform: translateX(0px); } 40% { transform: translateX(160px); } 60% { transform: translateX(120px); } @@ -62,22 +62,22 @@ <script> const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.2, "box1", "webkitTransform", [1,0,0,1, 20,0], 20], - [0.2, "box2", "webkitTransform", [1,0,0,1, 20,0], 20], - [0.2, "box3", "webkitTransform", [1,0,0,1, 180,0], 20], - [0.2, "box4", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box1", "webkitTransform", [1,0,0,1, 20,0], 20], - [2.2, "box2", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box3", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box4", "webkitTransform", [1,0,0,1, 20,0], 20], - [0.2, "box5", "webkitTransform", [1,0,0,1, 40,0], 20], - [0.2, "box6", "webkitTransform", [1,0,0,1, 40,0], 20], - [0.2, "box7", "webkitTransform", [1,0,0,1, 180,0], 20], - [0.2, "box8", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box5", "webkitTransform", [1,0,0,1, 40,0], 20], - [2.2, "box6", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box7", "webkitTransform", [1,0,0,1, 180,0], 20], - [2.2, "box8", "webkitTransform", [1,0,0,1, 40,0], 20], + [0.2, "box1", "transform", [1,0,0,1, 20,0], 20], + [0.2, "box2", "transform", [1,0,0,1, 20,0], 20], + [0.2, "box3", "transform", [1,0,0,1, 180,0], 20], + [0.2, "box4", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box1", "transform", [1,0,0,1, 20,0], 20], + [2.2, "box2", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box3", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box4", "transform", [1,0,0,1, 20,0], 20], + [0.2, "box5", "transform", [1,0,0,1, 40,0], 20], + [0.2, "box6", "transform", [1,0,0,1, 40,0], 20], + [0.2, "box7", "transform", [1,0,0,1, 180,0], 20], + [0.2, "box8", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box5", "transform", [1,0,0,1, 40,0], 20], + [2.2, "box6", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box7", "transform", [1,0,0,1, 180,0], 20], + [2.2, "box8", "transform", [1,0,0,1, 40,0], 20], ]; runAnimationTest(expectedValues);
diff --git a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware-expected.txt b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware-expected.txt index 854f735..a70db5c 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware-expected.txt
@@ -1,9 +1,9 @@ -PASS - "webkitTransform" property for "box1" element at 0.2s saw something close to: 1,0,0,1,18,0 -PASS - "webkitTransform" property for "box2" element at 0.2s saw something close to: 1,0,0,1,18,0 -PASS - "webkitTransform" property for "box3" element at 0.2s saw something close to: 1,0,0,1,198,0 -PASS - "webkitTransform" property for "box4" element at 0.2s saw something close to: 1,0,0,1,198,0 -PASS - "webkitTransform" property for "box1" element at 2.2s saw something close to: 1,0,0,1,18,0 -PASS - "webkitTransform" property for "box2" element at 2.2s saw something close to: 1,0,0,1,198,0 -PASS - "webkitTransform" property for "box3" element at 2.2s saw something close to: 1,0,0,1,198,0 -PASS - "webkitTransform" property for "box4" element at 2.2s saw something close to: 1,0,0,1,18,0 +PASS - "transform" property for "box1" element at 0.2s saw something close to: 1,0,0,1,18,0 +PASS - "transform" property for "box2" element at 0.2s saw something close to: 1,0,0,1,18,0 +PASS - "transform" property for "box3" element at 0.2s saw something close to: 1,0,0,1,198,0 +PASS - "transform" property for "box4" element at 0.2s saw something close to: 1,0,0,1,198,0 +PASS - "transform" property for "box1" element at 2.2s saw something close to: 1,0,0,1,18,0 +PASS - "transform" property for "box2" element at 2.2s saw something close to: 1,0,0,1,198,0 +PASS - "transform" property for "box3" element at 2.2s saw something close to: 1,0,0,1,198,0 +PASS - "transform" property for "box4" element at 2.2s saw something close to: 1,0,0,1,18,0
diff --git a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware.html b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware.html index 075aed16..8a98010b 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware.html +++ b/third_party/WebKit/LayoutTests/animations/animation-direction-reverse-timing-functions-hardware.html
@@ -1,7 +1,7 @@ <!doctype html> <html lang="en"> <head> - <title>Test of -webkit-animation-direction timing functions on composited elements</title> + <title>Test of animation-direction timing functions on composited elements</title> <style> body { margin: 0; @@ -14,34 +14,34 @@ height: 50px; width: 250px; margin-bottom: 10px; - -webkit-animation-duration: 2s; - -webkit-animation-timing-function: ease; /* ease is good for testing because it is not symmetric */ - -webkit-animation-iteration-count: 4; + animation-duration: 2s; + animation-timing-function: ease; /* ease is good for testing because it is not symmetric */ + animation-iteration-count: 4; } .move1 { - -webkit-animation-name: move1; + animation-name: move1; background-color: blue; color: white; } .normal { - -webkit-animation-direction: normal; + animation-direction: normal; } .alternate { - -webkit-animation-direction: alternate; + animation-direction: alternate; } .reverse { - -webkit-animation-direction: reverse; + animation-direction: reverse; } .alternate-reverse { - -webkit-animation-direction: alternate-reverse; + animation-direction: alternate-reverse; } - @-webkit-keyframes move1 { + @keyframes move1 { from { transform: translateX(0px); } to { transform: translateX(200px); } } @@ -50,14 +50,14 @@ <script> const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.2, "box1", "webkitTransform", [1,0,0,1, 18, 0], 10], - [0.2, "box2", "webkitTransform", [1,0,0,1, 18, 0], 10], - [0.2, "box3", "webkitTransform", [1,0,0,1, 198, 0], 10], - [0.2, "box4", "webkitTransform", [1,0,0,1, 198, 0], 10], - [2.2, "box1", "webkitTransform", [1,0,0,1, 18, 0], 10], - [2.2, "box2", "webkitTransform", [1,0,0,1, 198, 0], 10], - [2.2, "box3", "webkitTransform", [1,0,0,1, 198, 0], 10], - [2.2, "box4", "webkitTransform", [1,0,0,1, 18, 0], 10], + [0.2, "box1", "transform", [1,0,0,1, 18, 0], 10], + [0.2, "box2", "transform", [1,0,0,1, 18, 0], 10], + [0.2, "box3", "transform", [1,0,0,1, 198, 0], 10], + [0.2, "box4", "transform", [1,0,0,1, 198, 0], 10], + [2.2, "box1", "transform", [1,0,0,1, 18, 0], 10], + [2.2, "box2", "transform", [1,0,0,1, 198, 0], 10], + [2.2, "box3", "transform", [1,0,0,1, 198, 0], 10], + [2.2, "box4", "transform", [1,0,0,1, 18, 0], 10], ]; runAnimationTest(expectedValues);
diff --git a/third_party/WebKit/LayoutTests/animations/animation-matrix-negative-scale-unmatrix.html b/third_party/WebKit/LayoutTests/animations/animation-matrix-negative-scale-unmatrix.html index 4075931..125c28a 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-matrix-negative-scale-unmatrix.html +++ b/third_party/WebKit/LayoutTests/animations/animation-matrix-negative-scale-unmatrix.html
@@ -13,10 +13,10 @@ width: 100px; height: 100px; background-color: blue; - -webkit-animation-duration: 10s; + animation-duration: 10s; } - @-webkit-keyframes anim { + @keyframes anim { from { transform: matrix(1, 0, 0, -1, 0, 0); } to { transform: matrix(1, 0, 0, 1, 0, 0); } } @@ -32,7 +32,7 @@ function snapshot() { var boxComputedStyle = window.getComputedStyle(document.getElementById('box')); - var matrix = new WebKitCSSMatrix(boxComputedStyle.webkitTransform); + var matrix = new WebKitCSSMatrix(boxComputedStyle.transform); // "d" component (scaleY) should be negative. if (matrix["d"] > 0) @@ -45,7 +45,7 @@ function startAnimation() { - document.getElementById("box").style.webkitAnimationName = "anim"; + document.getElementById("box").style.animationName = "anim"; } document.addEventListener('webkitAnimationStart', snapshot, false);
diff --git a/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen-expected.html b/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen-expected.html index cf6a53f..e5af669 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen-expected.html +++ b/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen-expected.html
@@ -20,7 +20,7 @@ <body> <div id="box"></div> <div id="result"> -PASS - "webkitTransform" property for "box" element at 0.5s saw something close to: 1,0,0,1,100,0 +PASS - "transform" property for "box" element at 0.5s saw something close to: 1,0,0,1,100,0 </div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen.html b/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen.html index a5d14f0..2be0703e 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen.html +++ b/third_party/WebKit/LayoutTests/animations/animation-offscreen-to-onscreen.html
@@ -14,12 +14,12 @@ margin: 0; background-color: green; transform: translate(-2000px, 0px); - -webkit-animation-duration: 1s; - -webkit-animation-direction: normal; - -webkit-animation-timing-function: linear; - -webkit-animation-name: anim; + animation-duration: 1s; + animation-direction: normal; + animation-timing-function: linear; + animation-name: anim; } - @-webkit-keyframes anim { + @keyframes anim { 0% { transform: translate(100px, 0px); } 100% { transform: translate(100px, 0px); } } @@ -32,7 +32,7 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.5, "box", "webkitTransform", [1, 0, 0, 1, 100, 0], 0.002], + [0.5, "box", "transform", [1, 0, 0, 1, 100, 0], 0.002], ]; const doPixelTest = true;
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order-expected.txt b/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order-expected.txt index deb1b473..2b32d56 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order-expected.txt
@@ -1,71 +1,71 @@ -PASS Test 1: webkitAnimationName was test -PASS Test 1: webkitAnimationDuration was 3s -PASS Test 1: webkitAnimationTimingFunction was ease -PASS Test 1: webkitAnimationDelay was 0s -PASS Test 1: webkitAnimationIterationCount was 1 -PASS Test 1: webkitAnimationDirection was normal -PASS Test 1: webkitAnimationFillMode was none -PASS Test 2: webkitAnimationName was test -PASS Test 2: webkitAnimationDuration was 3s -PASS Test 2: webkitAnimationTimingFunction was ease -PASS Test 2: webkitAnimationDelay was 0s -PASS Test 2: webkitAnimationIterationCount was 1 -PASS Test 2: webkitAnimationDirection was normal -PASS Test 2: webkitAnimationFillMode was none -PASS Test 3: webkitAnimationName was test -PASS Test 3: webkitAnimationDuration was 3s -PASS Test 3: webkitAnimationTimingFunction was ease -PASS Test 3: webkitAnimationDelay was 0s -PASS Test 3: webkitAnimationIterationCount was 1 -PASS Test 3: webkitAnimationDirection was normal -PASS Test 3: webkitAnimationFillMode was forwards -PASS Test 4: webkitAnimationName was test -PASS Test 4: webkitAnimationDuration was 3s -PASS Test 4: webkitAnimationTimingFunction was ease -PASS Test 4: webkitAnimationDelay was 0s -PASS Test 4: webkitAnimationIterationCount was 1 -PASS Test 4: webkitAnimationDirection was normal -PASS Test 4: webkitAnimationFillMode was forwards -PASS Test 5: webkitAnimationName was test -PASS Test 5: webkitAnimationDuration was 3s -PASS Test 5: webkitAnimationTimingFunction was linear -PASS Test 5: webkitAnimationDelay was 0s -PASS Test 5: webkitAnimationIterationCount was 1 -PASS Test 5: webkitAnimationDirection was normal -PASS Test 5: webkitAnimationFillMode was forwards -PASS Test 6: webkitAnimationName was test -PASS Test 6: webkitAnimationDuration was 3s -PASS Test 6: webkitAnimationTimingFunction was linear -PASS Test 6: webkitAnimationDelay was 0s -PASS Test 6: webkitAnimationIterationCount was 1 -PASS Test 6: webkitAnimationDirection was normal -PASS Test 6: webkitAnimationFillMode was forwards -PASS Test 7: webkitAnimationName was test -PASS Test 7: webkitAnimationDuration was 3s -PASS Test 7: webkitAnimationTimingFunction was linear -PASS Test 7: webkitAnimationDelay was 4s -PASS Test 7: webkitAnimationIterationCount was 5 -PASS Test 7: webkitAnimationDirection was normal -PASS Test 7: webkitAnimationFillMode was forwards -PASS Test 8: webkitAnimationName was test -PASS Test 8: webkitAnimationDuration was 3s -PASS Test 8: webkitAnimationTimingFunction was linear -PASS Test 8: webkitAnimationDelay was 4s -PASS Test 8: webkitAnimationIterationCount was infinite -PASS Test 8: webkitAnimationDirection was alternate -PASS Test 8: webkitAnimationFillMode was forwards -PASS Test 9: webkitAnimationName was test -PASS Test 9: webkitAnimationDuration was 3s -PASS Test 9: webkitAnimationTimingFunction was linear -PASS Test 9: webkitAnimationDelay was 4s -PASS Test 9: webkitAnimationIterationCount was infinite -PASS Test 9: webkitAnimationDirection was alternate -PASS Test 9: webkitAnimationFillMode was none -PASS Test 10: webkitAnimationName was linear -PASS Test 10: webkitAnimationDuration was 3s -PASS Test 10: webkitAnimationTimingFunction was ease -PASS Test 10: webkitAnimationDelay was 4s -PASS Test 10: webkitAnimationIterationCount was infinite -PASS Test 10: webkitAnimationDirection was alternate -PASS Test 10: webkitAnimationFillMode was forwards +PASS Test 1: animationName was test +PASS Test 1: animationDuration was 3s +PASS Test 1: animationTimingFunction was ease +PASS Test 1: animationDelay was 0s +PASS Test 1: animationIterationCount was 1 +PASS Test 1: animationDirection was normal +PASS Test 1: animationFillMode was none +PASS Test 2: animationName was test +PASS Test 2: animationDuration was 3s +PASS Test 2: animationTimingFunction was ease +PASS Test 2: animationDelay was 0s +PASS Test 2: animationIterationCount was 1 +PASS Test 2: animationDirection was normal +PASS Test 2: animationFillMode was none +PASS Test 3: animationName was test +PASS Test 3: animationDuration was 3s +PASS Test 3: animationTimingFunction was ease +PASS Test 3: animationDelay was 0s +PASS Test 3: animationIterationCount was 1 +PASS Test 3: animationDirection was normal +PASS Test 3: animationFillMode was forwards +PASS Test 4: animationName was test +PASS Test 4: animationDuration was 3s +PASS Test 4: animationTimingFunction was ease +PASS Test 4: animationDelay was 0s +PASS Test 4: animationIterationCount was 1 +PASS Test 4: animationDirection was normal +PASS Test 4: animationFillMode was forwards +PASS Test 5: animationName was test +PASS Test 5: animationDuration was 3s +PASS Test 5: animationTimingFunction was linear +PASS Test 5: animationDelay was 0s +PASS Test 5: animationIterationCount was 1 +PASS Test 5: animationDirection was normal +PASS Test 5: animationFillMode was forwards +PASS Test 6: animationName was test +PASS Test 6: animationDuration was 3s +PASS Test 6: animationTimingFunction was linear +PASS Test 6: animationDelay was 0s +PASS Test 6: animationIterationCount was 1 +PASS Test 6: animationDirection was normal +PASS Test 6: animationFillMode was forwards +PASS Test 7: animationName was test +PASS Test 7: animationDuration was 3s +PASS Test 7: animationTimingFunction was linear +PASS Test 7: animationDelay was 4s +PASS Test 7: animationIterationCount was 5 +PASS Test 7: animationDirection was normal +PASS Test 7: animationFillMode was forwards +PASS Test 8: animationName was test +PASS Test 8: animationDuration was 3s +PASS Test 8: animationTimingFunction was linear +PASS Test 8: animationDelay was 4s +PASS Test 8: animationIterationCount was infinite +PASS Test 8: animationDirection was alternate +PASS Test 8: animationFillMode was forwards +PASS Test 9: animationName was test +PASS Test 9: animationDuration was 3s +PASS Test 9: animationTimingFunction was linear +PASS Test 9: animationDelay was 4s +PASS Test 9: animationIterationCount was infinite +PASS Test 9: animationDirection was alternate +PASS Test 9: animationFillMode was none +PASS Test 10: animationName was linear +PASS Test 10: animationDuration was 3s +PASS Test 10: animationTimingFunction was ease +PASS Test 10: animationDelay was 4s +PASS Test 10: animationIterationCount was infinite +PASS Test 10: animationDirection was alternate +PASS Test 10: animationFillMode was forwards
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order.html b/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order.html index 08e03ba..99da086 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order.html +++ b/third_party/WebKit/LayoutTests/animations/animation-shorthand-name-order.html
@@ -11,27 +11,27 @@ margin: 5px; } -@-webkit-keyframes test { +@keyframes test { from { left: 0px; } to { left: 100px; } } -@-webkit-keyframes backwards { +@keyframes backwards { from { left: 0px; } to { left: 100px; } } -@-webkit-keyframes alternate { +@keyframes alternate { from { left: 0px; } to { left: 100px; } } -@-webkit-keyframes linear { +@keyframes linear { from { left: 0px; } to { left: 100px; } } -@-webkit-keyframes ease { +@keyframes ease { from { left: 0px; } to { left: 100px; } } @@ -39,13 +39,13 @@ <script> const PROPERTIES_TO_TEST = [ - "webkitAnimationName", - "webkitAnimationDuration", - "webkitAnimationTimingFunction", - "webkitAnimationDelay", - "webkitAnimationIterationCount", - "webkitAnimationDirection", - "webkitAnimationFillMode" + "animationName", + "animationDuration", + "animationTimingFunction", + "animationDelay", + "animationIterationCount", + "animationDirection", + "animationFillMode" ]; const DEFAULT_VALUES = [ @@ -103,7 +103,7 @@ // Unfortunately need to force a style recalculation before testing. requestAnimationFrame(function () { - element.style.webkitAnimation = TEST_INPUTS[testIndex]; + element.style.animation = TEST_INPUTS[testIndex]; // And another forced style recalculation. requestAnimationFrame(function() {
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed-expected.txt b/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed-expected.txt index c3e0e25..27bb6d3a4 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed-expected.txt
@@ -1,57 +1,57 @@ -Testing webkitAnimationName on a: PASS -Testing webkitAnimationDuration on a: PASS -Testing webkitAnimationTimingFunction on a: PASS -Testing webkitAnimationDelay on a: PASS -Testing webkitAnimationIterationCount on a: PASS -Testing webkitAnimationDirection on a: PASS -Testing webkitAnimationFillMode on a: PASS -Testing webkitAnimationName on b: PASS -Testing webkitAnimationDuration on b: PASS -Testing webkitAnimationTimingFunction on b: PASS -Testing webkitAnimationDelay on b: PASS -Testing webkitAnimationIterationCount on b: PASS -Testing webkitAnimationDirection on b: PASS -Testing webkitAnimationFillMode on b: PASS -Testing webkitAnimationName on c: PASS -Testing webkitAnimationDuration on c: PASS -Testing webkitAnimationTimingFunction on c: PASS -Testing webkitAnimationDelay on c: PASS -Testing webkitAnimationIterationCount on c: PASS -Testing webkitAnimationDirection on c: PASS -Testing webkitAnimationFillMode on c: PASS -Testing webkitAnimationName on d: PASS -Testing webkitAnimationDuration on d: PASS -Testing webkitAnimationTimingFunction on d: PASS -Testing webkitAnimationDelay on d: PASS -Testing webkitAnimationIterationCount on d: PASS -Testing webkitAnimationDirection on d: PASS -Testing webkitAnimationFillMode on d: PASS -Testing webkitAnimationName on e: PASS -Testing webkitAnimationDuration on e: PASS -Testing webkitAnimationTimingFunction on e: PASS -Testing webkitAnimationDelay on e: PASS -Testing webkitAnimationIterationCount on e: PASS -Testing webkitAnimationDirection on e: PASS -Testing webkitAnimationFillMode on e: PASS -Testing webkitAnimationName on f: PASS -Testing webkitAnimationDuration on f: PASS -Testing webkitAnimationTimingFunction on f: PASS -Testing webkitAnimationDelay on f: PASS -Testing webkitAnimationIterationCount on f: PASS -Testing webkitAnimationDirection on f: PASS -Testing webkitAnimationFillMode on f: PASS -Testing webkitAnimationName on g: PASS -Testing webkitAnimationDuration on g: PASS -Testing webkitAnimationTimingFunction on g: PASS -Testing webkitAnimationDelay on g: PASS -Testing webkitAnimationIterationCount on g: PASS -Testing webkitAnimationDirection on g: PASS -Testing webkitAnimationFillMode on g: PASS -Testing webkitAnimationName on h: PASS -Testing webkitAnimationDuration on h: PASS -Testing webkitAnimationTimingFunction on h: PASS -Testing webkitAnimationDelay on h: PASS -Testing webkitAnimationIterationCount on h: PASS -Testing webkitAnimationDirection on h: PASS -Testing webkitAnimationFillMode on h: PASS +Testing animationName on a: PASS +Testing animationDuration on a: PASS +Testing animationTimingFunction on a: PASS +Testing animationDelay on a: PASS +Testing animationIterationCount on a: PASS +Testing animationDirection on a: PASS +Testing animationFillMode on a: PASS +Testing animationName on b: PASS +Testing animationDuration on b: PASS +Testing animationTimingFunction on b: PASS +Testing animationDelay on b: PASS +Testing animationIterationCount on b: PASS +Testing animationDirection on b: PASS +Testing animationFillMode on b: PASS +Testing animationName on c: PASS +Testing animationDuration on c: PASS +Testing animationTimingFunction on c: PASS +Testing animationDelay on c: PASS +Testing animationIterationCount on c: PASS +Testing animationDirection on c: PASS +Testing animationFillMode on c: PASS +Testing animationName on d: PASS +Testing animationDuration on d: PASS +Testing animationTimingFunction on d: PASS +Testing animationDelay on d: PASS +Testing animationIterationCount on d: PASS +Testing animationDirection on d: PASS +Testing animationFillMode on d: PASS +Testing animationName on e: PASS +Testing animationDuration on e: PASS +Testing animationTimingFunction on e: PASS +Testing animationDelay on e: PASS +Testing animationIterationCount on e: PASS +Testing animationDirection on e: PASS +Testing animationFillMode on e: PASS +Testing animationName on f: PASS +Testing animationDuration on f: PASS +Testing animationTimingFunction on f: PASS +Testing animationDelay on f: PASS +Testing animationIterationCount on f: PASS +Testing animationDirection on f: PASS +Testing animationFillMode on f: PASS +Testing animationName on g: PASS +Testing animationDuration on g: PASS +Testing animationTimingFunction on g: PASS +Testing animationDelay on g: PASS +Testing animationIterationCount on g: PASS +Testing animationDirection on g: PASS +Testing animationFillMode on g: PASS +Testing animationName on h: PASS +Testing animationDuration on h: PASS +Testing animationTimingFunction on h: PASS +Testing animationDelay on h: PASS +Testing animationIterationCount on h: PASS +Testing animationDirection on h: PASS +Testing animationFillMode on h: PASS
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed.html b/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed.html index c0978562..9d2af2a 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed.html +++ b/third_party/WebKit/LayoutTests/animations/animation-shorthand-removed.html
@@ -8,7 +8,7 @@ background-color: blue; } -@-webkit-keyframes anim1 { } +@keyframes anim1 { } </style> <script type="text/javascript" charset="utf-8"> if (window.testRunner) { @@ -17,13 +17,13 @@ } const kProperties = [ - "webkitAnimationName", - "webkitAnimationDuration", - "webkitAnimationTimingFunction", - "webkitAnimationDelay", - "webkitAnimationIterationCount", - "webkitAnimationDirection", - "webkitAnimationFillMode" + "animationName", + "animationDuration", + "animationTimingFunction", + "animationDelay", + "animationIterationCount", + "animationDirection", + "animationFillMode" ]; const kElements = [ { id: "a", @@ -66,7 +66,7 @@ function remove() { kElements.forEach(function(curEl) { var el = document.getElementById(curEl.id); - el.style.removeProperty("-webkit-animation"); + el.style.removeProperty("animation"); }); setTimeout(test, 0); }
diff --git a/third_party/WebKit/LayoutTests/animations/change-keyframes.html b/third_party/WebKit/LayoutTests/animations/change-keyframes.html index fc0bef4..b46b6e2 100644 --- a/third_party/WebKit/LayoutTests/animations/change-keyframes.html +++ b/third_party/WebKit/LayoutTests/animations/change-keyframes.html
@@ -51,7 +51,7 @@ keyframes.deleteRule("100%"); keyframes.appendRule("0% { top: 50px; }"); keyframes.appendRule("100% { top: 150px; }"); - box.style.webkitAnimationName = "anim"; + box.style.animationName = "anim"; // The left property should reset and top should be animating. assert_equals(getComputedStyle(box).left, '0px', 'left');
diff --git a/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation-expected.html b/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation-expected.html index a39c1a50..ce07027 100644 --- a/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation-expected.html +++ b/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation-expected.html
@@ -4,7 +4,7 @@ <style> #container { transform: translateZ(0px); - -webkit-perspective: 400; + perspective: 400; } #revealed { @@ -22,7 +22,7 @@ width: 100px; background-color: red; transform: translateZ(200px) translateX(-200px); - -webkit-transform-style: preserve-3d; + transform-style: preserve-3d; } </style> </head>
diff --git a/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation.html b/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation.html index d0f5d9e..e8933c8e 100644 --- a/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation.html +++ b/third_party/WebKit/LayoutTests/animations/change-transform-style-during-animation.html
@@ -4,7 +4,7 @@ <style> #container { transform: translateZ(0px); - -webkit-perspective: 400; + perspective: 400; } #revealed { @@ -22,14 +22,14 @@ width: 100px; background-color: red; transform: translateZ(10px); - -webkit-transform-style: preserve-3d; - -webkit-animation-duration: 100ms; - -webkit-animation-fill-mode: both; - -webkit-animation-timing-function: linear; - -webkit-animation-iteration-count: 1; + transform-style: preserve-3d; + animation-duration: 100ms; + animation-fill-mode: both; + animation-timing-function: linear; + animation-iteration-count: 1; } - @-webkit-keyframes anim { + @keyframes anim { from { transform: translateZ(0px) translateX(0px); } to { transform: translateZ(200px) translateX(-200px); } } @@ -46,7 +46,7 @@ var animated = document.getElementById('animated'); var result; var expected = "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -200, 0, 200, 1)"; - var computed = getPropertyValue("webkitTransform", "animated"); + var computed = getPropertyValue("transform", "animated"); if (comparePropertyValue(computed, expected, 0.002)) { result = "PASS - Computed final position is correct."; } else { @@ -59,13 +59,13 @@ function animationStarted() { var animated = document.getElementById('animated'); - animated.style.webkitTransformStyle = 'flat'; + animated.style.transformStyle = 'flat'; } function startTest() { var animated = document.getElementById('animated'); - animated.style.webkitAnimationName = "anim"; + animated.style.animationName = "anim"; animated.addEventListener('webkitAnimationEnd', animationDone); animated.addEventListener('webkitAnimationStart', animationStarted); }
diff --git a/third_party/WebKit/LayoutTests/animations/compounding-transitions-on-repeatable-list.html b/third_party/WebKit/LayoutTests/animations/compounding-transitions-on-repeatable-list.html new file mode 100644 index 0000000..7436bcd --- /dev/null +++ b/third_party/WebKit/LayoutTests/animations/compounding-transitions-on-repeatable-list.html
@@ -0,0 +1,21 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<style> +#target { + transition-property: stroke-dasharray; + transition-duration: 1s; + transition-delay: -0.5s; +} +</style> +<div id="target"></div> +<script> +test(() => { + const iterations = 13; + for (let i = 0; i < iterations; ++i) { + target.style.strokeDasharray = '1 '.repeat(i); + const animatedValueLength = getComputedStyle(target).strokeDasharray.split(' ').length; + assert_less_than_equal(animatedValueLength, 1000, 'iteration ' + i); + } +}, 'Starting compounded transitions on a repeatable list property should limit how much the animated value gets repeated to runaway memory usage.'); +</script>
diff --git a/third_party/WebKit/LayoutTests/animations/computed-style-expected.txt b/third_party/WebKit/LayoutTests/animations/computed-style-expected.txt index c0d7b3b0..49e5ed1 100644 --- a/third_party/WebKit/LayoutTests/animations/computed-style-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/computed-style-expected.txt
@@ -3,20 +3,20 @@ On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". -PASS test1Style.webkitAnimationName is 'anim1' -PASS test2Style.webkitAnimationName is 'anim2, anim3' -PASS test3Style.webkitAnimationName is 'anim1, anim2, anim3' -PASS test1Style.webkitAnimationDuration is '10s' -PASS test2Style.webkitAnimationDuration is '5s, 2.5s' -PASS test1Style.webkitAnimationFillMode is 'backwards' -PASS test2Style.webkitAnimationFillMode is 'forwards, both' -PASS test1Style.webkitAnimationIterationCount is '10' -PASS test2Style.webkitAnimationIterationCount is '10, infinite' -PASS test1Style.webkitAnimationTimingFunction is 'linear' -PASS test2Style.webkitAnimationTimingFunction is 'linear, ease-in-out' -PASS test3Style.webkitAnimationTimingFunction is 'step-start, step-end, steps(5, end)' -PASS test1Style.webkitAnimationDirection is 'normal' -PASS test2Style.webkitAnimationDirection is 'normal, alternate' +PASS test1Style.animationName is 'anim1' +PASS test2Style.animationName is 'anim2, anim3' +PASS test3Style.animationName is 'anim1, anim2, anim3' +PASS test1Style.animationDuration is '10s' +PASS test2Style.animationDuration is '5s, 2.5s' +PASS test1Style.animationFillMode is 'backwards' +PASS test2Style.animationFillMode is 'forwards, both' +PASS test1Style.animationIterationCount is '10' +PASS test2Style.animationIterationCount is '10, infinite' +PASS test1Style.animationTimingFunction is 'linear' +PASS test2Style.animationTimingFunction is 'linear, ease-in-out' +PASS test3Style.animationTimingFunction is 'step-start, step-end, steps(5, end)' +PASS test1Style.animationDirection is 'normal' +PASS test2Style.animationDirection is 'normal, alternate' PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/animations/computed-style.html b/third_party/WebKit/LayoutTests/animations/computed-style.html index cf7cf52..f30b09d 100644 --- a/third_party/WebKit/LayoutTests/animations/computed-style.html +++ b/third_party/WebKit/LayoutTests/animations/computed-style.html
@@ -6,43 +6,43 @@ height: 20px; background-color: blue; position: relative; - -webkit-animation-name: anim1; - -webkit-animation-duration: 10s; - -webkit-animation-fill-mode: backwards; - -webkit-animation-iteration-count: 10; - -webkit-animation-timing-function: linear; - -webkit-animation-direction: normal; + animation-name: anim1; + animation-duration: 10s; + animation-fill-mode: backwards; + animation-iteration-count: 10; + animation-timing-function: linear; + animation-direction: normal; } #test2 { width: 20px; height: 20px; background-color: blue; position: relative; - -webkit-animation-name: anim2, anim3; - -webkit-animation-duration: 5s, 2500ms; - -webkit-animation-fill-mode: forwards, both; - -webkit-animation-iteration-count: 10, infinite; - -webkit-animation-timing-function: linear, ease-in-out; - -webkit-animation-direction: normal, alternate; + animation-name: anim2, anim3; + animation-duration: 5s, 2500ms; + animation-fill-mode: forwards, both; + animation-iteration-count: 10, infinite; + animation-timing-function: linear, ease-in-out; + animation-direction: normal, alternate; } #test3 { width: 20px; height: 20px; background-color: blue; position: relative; - -webkit-animation-name: anim1, anim2, anim3; - -webkit-animation-duration: 5s; - -webkit-animation-timing-function: step-start, step-end, steps(5, end); + animation-name: anim1, anim2, anim3; + animation-duration: 5s; + animation-timing-function: step-start, step-end, steps(5, end); } - @-webkit-keyframes anim1 { + @keyframes anim1 { from { left: 10px; } to { left: 20px; } } - @-webkit-keyframes anim2 { + @keyframes anim2 { from { width: 20px; } to { width: 25px; } } - @-webkit-keyframes anim3 { + @keyframes anim3 { from { left: 10px; } to { left: 20px; } } @@ -66,25 +66,25 @@ var test2Style = window.getComputedStyle(test2); var test3Style = window.getComputedStyle(test3); -shouldBe("test1Style.webkitAnimationName", "'anim1'"); -shouldBe("test2Style.webkitAnimationName", "'anim2, anim3'"); -shouldBe("test3Style.webkitAnimationName", "'anim1, anim2, anim3'"); +shouldBe("test1Style.animationName", "'anim1'"); +shouldBe("test2Style.animationName", "'anim2, anim3'"); +shouldBe("test3Style.animationName", "'anim1, anim2, anim3'"); -shouldBe("test1Style.webkitAnimationDuration", "'10s'"); -shouldBe("test2Style.webkitAnimationDuration", "'5s, 2.5s'"); +shouldBe("test1Style.animationDuration", "'10s'"); +shouldBe("test2Style.animationDuration", "'5s, 2.5s'"); -shouldBe("test1Style.webkitAnimationFillMode", "'backwards'"); -shouldBe("test2Style.webkitAnimationFillMode", "'forwards, both'"); +shouldBe("test1Style.animationFillMode", "'backwards'"); +shouldBe("test2Style.animationFillMode", "'forwards, both'"); -shouldBe("test1Style.webkitAnimationIterationCount", "'10'"); -shouldBe("test2Style.webkitAnimationIterationCount", "'10, infinite'"); +shouldBe("test1Style.animationIterationCount", "'10'"); +shouldBe("test2Style.animationIterationCount", "'10, infinite'"); -shouldBe("test1Style.webkitAnimationTimingFunction", "'linear'"); -shouldBe("test2Style.webkitAnimationTimingFunction", "'linear, ease-in-out'"); -shouldBe("test3Style.webkitAnimationTimingFunction", "'step-start, step-end, steps(5, end)'"); +shouldBe("test1Style.animationTimingFunction", "'linear'"); +shouldBe("test2Style.animationTimingFunction", "'linear, ease-in-out'"); +shouldBe("test3Style.animationTimingFunction", "'step-start, step-end, steps(5, end)'"); -shouldBe("test1Style.webkitAnimationDirection", "'normal'"); -shouldBe("test2Style.webkitAnimationDirection", "'normal, alternate'"); +shouldBe("test1Style.animationDirection", "'normal'"); +shouldBe("test2Style.animationDirection", "'normal, alternate'"); debug("");
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-background-image.html b/third_party/WebKit/LayoutTests/animations/cross-fade-background-image.html index 5fbdcd5..2c9d796 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-background-image.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-background-image.html
@@ -8,7 +8,7 @@ height: 100px; width: 100px; background-color: red; - -webkit-animation: anim 1s linear infinite; + animation: anim 1s linear infinite; } #boxShorthand { position: absolute; @@ -17,7 +17,7 @@ height: 100px; width: 100px; background-color: red; - -webkit-animation: animShorthand 1s linear infinite; + animation: animShorthand 1s linear infinite; } #boxStatic { position: absolute; @@ -28,11 +28,11 @@ background-color: red; background-image: -webkit-cross-fade(url(resources/blue-100.png), url(resources/green-100.png), 50%); } - @-webkit-keyframes anim { + @keyframes anim { from { background-image: url(resources/blue-100.png); } to { background-image: url(resources/green-100.png); } } - @-webkit-keyframes animShorthand { + @keyframes animShorthand { from { background: url(resources/blue-100.png); } to { background: url(resources/green-100.png); } }
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-border-image-source.html b/third_party/WebKit/LayoutTests/animations/cross-fade-border-image-source.html index 7741ef0..96443d8 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-border-image-source.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-border-image-source.html
@@ -8,7 +8,7 @@ height: 100px; width: 100px; background-color: green; - -webkit-animation: anim 1s linear infinite; + animation: anim 1s linear infinite; border-image: url() 5 5 5 5 /20px stretch stretch; border-style: solid; } @@ -19,7 +19,7 @@ height: 100px; width: 100px; background-color: green; - -webkit-animation: animShorthand 1s linear infinite; + animation: animShorthand 1s linear infinite; border-style: solid; } #boxStatic { @@ -32,11 +32,11 @@ border-image: -webkit-cross-fade(url(resources/stripes-100.png), url(resources/green-100.png), 50%) 5 5 5 5 /20px stretch stretch; border-style: solid; } - @-webkit-keyframes anim { + @keyframes anim { from { border-image-source: url(resources/stripes-100.png); } to { border-image-source: url(resources/green-100.png); } } - @-webkit-keyframes animShorthand { + @keyframes animShorthand { from { border-image: url(resources/stripes-100.png) 5 5 5 5 /20px stretch stretch; } to { border-image: url(resources/green-100.png) 5 5 5 5 /20px stretch stretch; } }
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-list-style-image.html b/third_party/WebKit/LayoutTests/animations/cross-fade-list-style-image.html index 9cc372c1..7282354 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-list-style-image.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-list-style-image.html
@@ -23,11 +23,11 @@ width: 100px; list-style: square -webkit-cross-fade(url(resources/blue-100.png), url(resources/green-100.png), 50%); } - @-webkit-keyframes anim { + @keyframes anim { from { list-style-image: url(resources/blue-100.png); } to { list-style-image: url(resources/green-100.png); } } - @-webkit-keyframes animShorthand { + @keyframes animShorthand { from { list-style: square url(resources/blue-100.png); } to { list-style: square url(resources/green-100.png); } } @@ -35,8 +35,8 @@ <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> function runTest() { - document.querySelector('#box').style.webkitAnimation = "anim 1s linear infinite"; - document.querySelector('#boxShorthand').style.webkitAnimation = "animShorthand 1s linear infinite"; + document.querySelector('#box').style.animation = "anim 1s linear infinite"; + document.querySelector('#boxShorthand').style.animation = "animShorthand 1s linear infinite"; const expectedValues = [ // [time, element-id, property, expected-value, tolerance]
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image-expected.html b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image-expected.html index ec99dc1..76826d2 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image-expected.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image-expected.html
@@ -19,10 +19,6 @@ background-color: red; -webkit-mask-box-image: -webkit-cross-fade(url(resources/stripes-100.png), url(resources/green-100.png), 25%) 50 stretch; } - @-webkit-keyframes anim { - from { -webkit-mask-box-image: url(resources/stripes-100.png) 50 stretch; } - to { -webkit-mask-box-image: url(resources/green-100.png) 50 stretch; } - } </style> </head> <body>
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image.html b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image.html index 40d7eb10..957b377 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-box-image.html
@@ -8,7 +8,7 @@ height: 200px; width: 200px; background-color: red; - -webkit-animation: anim 1s linear infinite; + animation: anim 1s linear infinite; } #boxStatic { position: absolute; @@ -19,7 +19,7 @@ background-color: red; -webkit-mask-box-image: -webkit-cross-fade(url(resources/stripes-100.png), url(resources/green-100.png), 25%) 50 stretch; } - @-webkit-keyframes anim { + @keyframes anim { from { -webkit-mask-box-image: url(resources/stripes-100.png) 50 stretch; } to { -webkit-mask-box-image: url(resources/green-100.png) 50 stretch; } }
diff --git a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-image.html b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-image.html index a9674113..4fa481f 100644 --- a/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-image.html +++ b/third_party/WebKit/LayoutTests/animations/cross-fade-webkit-mask-image.html
@@ -8,7 +8,7 @@ height: 100px; width: 100px; background-color: red; - -webkit-animation: anim 1s linear infinite; + animation: anim 1s linear infinite; } #boxStatic { position: absolute; @@ -19,7 +19,7 @@ background-color: red; -webkit-mask-image: -webkit-cross-fade(url(resources/stripes-100.png), url(resources/green-100.png), 25%); } - @-webkit-keyframes anim { + @keyframes anim { from { -webkit-mask-image: url(resources/stripes-100.png); } to { -webkit-mask-image: url(resources/green-100.png); } }
diff --git a/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading-expected.txt b/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading-expected.txt index af672fe..9c32cde 100644 --- a/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading-expected.txt
@@ -1,3 +1,3 @@ Warning this test is running in real-time and may be flaky. -PASS - "webkitTransform.5" property for "splash" element at 0.3s saw something close to: 100 +PASS - "transform.5" property for "splash" element at 0.3s saw something close to: 100
diff --git a/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading.html b/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading.html index d33de9c..2fca26c 100644 --- a/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading.html +++ b/third_party/WebKit/LayoutTests/animations/dynamic-stylesheet-loading.html
@@ -9,7 +9,7 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.3, "splash", "webkitTransform.5", 100, 0.1], + [0.3, "splash", "transform.5", 100, 0.1], ]; var controller = {};
diff --git a/third_party/WebKit/LayoutTests/animations/fill-mode-forwards2.html b/third_party/WebKit/LayoutTests/animations/fill-mode-forwards2.html index 04dde40..804459b 100644 --- a/third_party/WebKit/LayoutTests/animations/fill-mode-forwards2.html +++ b/third_party/WebKit/LayoutTests/animations/fill-mode-forwards2.html
@@ -33,11 +33,11 @@ top: 100px; background-color: blue; opacity: 0; - -webkit-animation-name: pop; - -webkit-animation-duration: 1s; - -webkit-animation-fill-mode: forwards; + animation-name: pop; + animation-duration: 1s; + animation-fill-mode: forwards; } - @-webkit-keyframes pop { + @keyframes pop { 0% { transform: scale(0.05); opacity: 0; } 33% { transform: scale(1.00); opacity: 1; } 66% { transform: scale(1.66); opacity: 1; }
diff --git a/third_party/WebKit/LayoutTests/animations/filter-responsive-neutral-keyframe.html b/third_party/WebKit/LayoutTests/animations/filter-responsive-neutral-keyframe.html index 782192b..45a776e 100644 --- a/third_party/WebKit/LayoutTests/animations/filter-responsive-neutral-keyframe.html +++ b/third_party/WebKit/LayoutTests/animations/filter-responsive-neutral-keyframe.html
@@ -7,14 +7,14 @@ } #target { background: red; - -webkit-filter: opacity(1); + filter: opacity(1); animation: test 1e8s; } #green { background: green; } @keyframes test { - to { -webkit-filter: opacity(0); } + to { filter: opacity(0); } } </style> <div id="green"></div> @@ -28,7 +28,7 @@ } waitForCompositor().then(() => { - target.style.webkitFilter = 'opacity(0)'; + target.style.filter = 'opacity(0)'; }).then(() => waitForCompositor()).then(() => { if (window.testRunner) testRunner.notifyDone();
diff --git a/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform-expected.txt b/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform-expected.txt index 51719cc..b412404 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform-expected.txt
@@ -1,7 +1,7 @@ -PASS - "webkitTransform" property for "box" element at 0.5s saw something close to: 1,0,0,1,50,0 +PASS - "transform" property for "box" element at 0.5s saw something close to: 1,0,0,1,50,0 PASS - "opacity" property for "box" element at 0.5s saw something close to: 1 PASS - "opacity" property for "box" element at 0.9s saw something close to: 1 -PASS - "webkitTransform" property for "box" element at 1s saw something close to: 1,0,0,1,100,0 -PASS - "webkitTransform" property for "box" element at 1.5s saw something close to: 1,0,0,1,150,0 +PASS - "transform" property for "box" element at 1s saw something close to: 1,0,0,1,100,0 +PASS - "transform" property for "box" element at 1.5s saw something close to: 1,0,0,1,150,0 PASS - "opacity" property for "box" element at 1.5s saw something close to: 1
diff --git a/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform.html b/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform.html index 172bd3b..9f7472eb 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform.html +++ b/third_party/WebKit/LayoutTests/animations/keyframe-multiple-timing-functions-transform.html
@@ -9,17 +9,17 @@ margin: 20px; background-color: red; transform: translateZ(0); - -webkit-animation: + animation: horizontal 2s linear 1 alternate, fade 2s steps(1, end) 1 alternate; } - @-webkit-keyframes horizontal { + @keyframes horizontal { from { transform: translateX(0px); } to { transform: translateX(200px); } } - @-webkit-keyframes fade { + @keyframes fade { from { opacity: 1.0; } to { opacity: 0.0; } } @@ -28,9 +28,9 @@ <script type="text/javascript" charset="utf-8"> const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.5, "box", "webkitTransform", [1,0,0,1, 50,0], 20], - [1.0, "box", "webkitTransform", [1,0,0,1,100,0], 20], - [1.5, "box", "webkitTransform", [1,0,0,1,150,0], 20], + [0.5, "box", "transform", [1,0,0,1, 50,0], 20], + [1.0, "box", "transform", [1,0,0,1,100,0], 20], + [1.5, "box", "transform", [1,0,0,1,150,0], 20], [0.5, "box", "opacity", 1.0, 0.15], [0.9, "box", "opacity", 1.0, 0.15], [1.5, "box", "opacity", 1.0, 0.15],
diff --git a/third_party/WebKit/LayoutTests/animations/keyframe-selector-negative-percentage.html b/third_party/WebKit/LayoutTests/animations/keyframe-selector-negative-percentage.html index 29de1c6..1830703 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframe-selector-negative-percentage.html +++ b/third_party/WebKit/LayoutTests/animations/keyframe-selector-negative-percentage.html
@@ -4,7 +4,7 @@ <title>Check that negative (out of range) key frame percentage doesn't cause subsequent first or second ruleset to be skipped.</title> <style> #test { background-color: red; color: black } -@-webkit-keyframes fade { -10% { color: red; } } +@keyframes fade { -10% { color: red; } } #test { background-color: green; } /* if skipped, then background will be red */ #test { color: white; } /* if skipped, then text will be black */ </style>
diff --git a/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe-expected.html b/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe-expected.html index 45cd90a..1170b86 100644 --- a/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe-expected.html +++ b/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe-expected.html
@@ -50,7 +50,7 @@ <div id="result"> PASS - "left" property for "box1" element at 0.5s saw something close to: 100<br> - PASS - "webkitTransform.4" property for "box2" element at 0.5s saw something close to: 100 + PASS - "transform.4" property for "box2" element at 0.5s saw something close to: 100 </div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe.html b/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe.html index e8368ed..06afdd9 100644 --- a/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe.html +++ b/third_party/WebKit/LayoutTests/animations/missing-values-first-keyframe.html
@@ -30,15 +30,15 @@ #box1 { left: 200px; - -webkit-animation: move-left 2s linear; + animation: move-left 2s linear; } #box2 { transform: translateX(200px); - -webkit-animation: move-transform 2s linear; + animation: move-transform 2s linear; } - @-webkit-keyframes move-left { + @keyframes move-left { 0% { opacity: 1; } @@ -55,7 +55,7 @@ } } - @-webkit-keyframes move-transform { + @keyframes move-transform { 0% { opacity: 1; } @@ -78,7 +78,7 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] [0.5, "box1", "left", 100, 15], - [0.5, "box2", "webkitTransform.4", 100, 15], + [0.5, "box2", "transform.4", 100, 15], ]; var doPixelTest = true;
diff --git a/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe-expected.html b/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe-expected.html index 4589020..bccfc51 100644 --- a/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe-expected.html +++ b/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe-expected.html
@@ -49,7 +49,7 @@ <div id="result"> PASS - "left" property for "box1" element at 1.5s saw something close to: 100<br> - PASS - "webkitTransform.4" property for "box2" element at 1.5s saw something close to: 100 + PASS - "transform.4" property for "box2" element at 1.5s saw something close to: 100 </div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe.html b/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe.html index b1732e9..2e318aa 100644 --- a/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe.html +++ b/third_party/WebKit/LayoutTests/animations/missing-values-last-keyframe.html
@@ -30,15 +30,15 @@ #box1 { left: 200px; - -webkit-animation: move-left 2s linear; + animation: move-left 2s linear; } #box2 { transform: translateX(200px); - -webkit-animation: move-transform 2s linear; + animation: move-transform 2s linear; } - @-webkit-keyframes move-left { + @keyframes move-left { 0% { left: 0; opacity: 0; @@ -55,7 +55,7 @@ } } - @-webkit-keyframes move-transform { + @keyframes move-transform { 0% { transform: translateX(0); opacity: 0; @@ -78,7 +78,7 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] [1.5, "box1", "left", 100, 15], - [1.5, "box2", "webkitTransform.4", 100, 15], + [1.5, "box2", "transform.4", 100, 15], ]; var doPixelTest = true;
diff --git a/third_party/WebKit/LayoutTests/animations/opacity-transform-animation-expected.html b/third_party/WebKit/LayoutTests/animations/opacity-transform-animation-expected.html index 3c27ed9..2ef5b47 100644 --- a/third_party/WebKit/LayoutTests/animations/opacity-transform-animation-expected.html +++ b/third_party/WebKit/LayoutTests/animations/opacity-transform-animation-expected.html
@@ -24,6 +24,6 @@ <div class="target" id="indicator"></div> <div class="target" id="box"></div> <div id="result"> -PASS - "webkitTransform.4" property for "box" element at 0.5s saw something close to: 200</div> +PASS - "transform.4" property for "box" element at 0.5s saw something close to: 200</div> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/animations/opacity-transform-animation.html b/third_party/WebKit/LayoutTests/animations/opacity-transform-animation.html index 88525023..a49da48 100644 --- a/third_party/WebKit/LayoutTests/animations/opacity-transform-animation.html +++ b/third_party/WebKit/LayoutTests/animations/opacity-transform-animation.html
@@ -11,12 +11,12 @@ } #box { background-color: green; - -webkit-animation-name: move; - -webkit-animation-duration: 1s; - -webkit-animation-timing-function: linear; - -webkit-animation-iteration-count: 1; + animation-name: move; + animation-duration: 1s; + animation-timing-function: linear; + animation-iteration-count: 1; } - @-webkit-keyframes move { + @keyframes move { from { transform: translateX(0) scale(1); opacity: 0.0; @@ -36,7 +36,7 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [0.5, "box", "webkitTransform.4", 200, 5], + [0.5, "box", "transform.4", 200, 5], ]; var disablePauseAnimationAPI = false;
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-01.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-01.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-02.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-02.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-03-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-03-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-03-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-03-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-03.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-03.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-03.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-03.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-04-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-04-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-04-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-04-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-prefixed-04.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-04.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-prefixed-04.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-prefixed-04.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-01.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-01.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-02.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-02.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-03-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-03-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-03-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-03-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-03.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-03.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-03.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-03.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-04-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-04-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-04-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-04-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-04.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-04.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-events-unprefixed-04.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-events-unprefixed-04.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-inherit-initial-unprefixed-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-inherit-initial-unprefixed-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-inherit-initial-unprefixed-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-inherit-initial-unprefixed-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-inherit-initial-unprefixed.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-inherit-initial-unprefixed.html similarity index 98% rename from third_party/WebKit/LayoutTests/animations/animation-inherit-initial-unprefixed.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-inherit-initial-unprefixed.html index aab0458b..0b29c35 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-inherit-initial-unprefixed.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/animation-inherit-initial-unprefixed.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <html> <head> -<script src="../resources/js-test.js"></script> +<script src="../../resources/js-test.js"></script> <style> #base { animation-name: anim;
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-prefixed-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-shorthand-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-prefixed-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-prefixed.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-shorthand.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-prefixed.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-unprefixed-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-unprefixed-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-shorthand-unprefixed-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-unprefixed-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/animation-shorthand-unprefixed.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-unprefixed.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/animation-shorthand-unprefixed.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-shorthand-unprefixed.html
diff --git a/third_party/WebKit/LayoutTests/animations/animation-unprefixed-string.html b/third_party/WebKit/LayoutTests/animations/prefixed/animation-unprefixed-string.html similarity index 76% rename from third_party/WebKit/LayoutTests/animations/animation-unprefixed-string.html rename to third_party/WebKit/LayoutTests/animations/prefixed/animation-unprefixed-string.html index 96c3f76..66417adc 100644 --- a/third_party/WebKit/LayoutTests/animations/animation-unprefixed-string.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/animation-unprefixed-string.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <style> @keyframes anim { from { background: red; }
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-01.html similarity index 92% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-01.html index 6e1cadb..25a0673 100644 --- a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-01.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-01.html
@@ -31,7 +31,7 @@ to { left: 300px; } } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-02.html similarity index 92% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-02.html index 47917c5..7f2f245 100644 --- a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-02.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-02.html
@@ -35,7 +35,7 @@ to { left: 300px; } } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-03-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-03-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-03-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-03-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-03.html b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-03.html similarity index 92% rename from third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-03.html rename to third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-03.html index 567f4a0..aa6a270 100644 --- a/third_party/WebKit/LayoutTests/animations/duplicated-keyframes-name-unprefixed-03.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/duplicated-keyframes-name-unprefixed-03.html
@@ -35,7 +35,7 @@ to { left: 700px; } } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-01.html similarity index 91% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-01.html index 2f7cda42..cc516d8e 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-01.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-01.html
@@ -16,7 +16,7 @@ animation-fill-mode: forwards; } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-02.html similarity index 97% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-02.html index 311c149..5a27907f1b 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-prefixed-02.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-prefixed-02.html
@@ -4,7 +4,7 @@ <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <script src="../resources/js-test.js"></script> + <script src="../../resources/js-test.js"></script> <style type="text/css" media="screen"> #test { position: absolute;
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-01.html similarity index 92% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-01.html index 687c9712..9b804c3 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-01.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-01.html
@@ -19,7 +19,7 @@ animation-fill-mode: forwards; } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-02.html similarity index 97% rename from third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-02.html index 6b8c111..d9a4fb0 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-cssom-unprefixed-02.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-cssom-unprefixed-02.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <html lang="en"> <head> - <script src="../resources/js-test.js"></script> + <script src="../../resources/js-test.js"></script> <style type="text/css" media="screen"> #test { position: absolute;
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-01-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-01-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-01-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-01-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-01.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-01.html similarity index 90% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-01.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-01.html index 5494eb01..6a96a0e6 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-01.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-01.html
@@ -23,7 +23,7 @@ to { left: 300px; } } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-02-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-02-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-02-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-02-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-02.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-02.html similarity index 91% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-02.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-02.html index fc908103..575aa16 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-02.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-02.html
@@ -28,7 +28,7 @@ to { left: 300px; } } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-03-expected.txt b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-03-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-03-expected.txt rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-03-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-03.html b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-03.html similarity index 91% rename from third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-03.html rename to third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-03.html index 66ccf2f..f22d1f2b 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframes-unprefixed-03.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/keyframes-unprefixed-03.html
@@ -30,7 +30,7 @@ } </style> - <script src="resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> + <script src="../resources/animation-test-helpers.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> const expectedValues = [
diff --git a/third_party/WebKit/LayoutTests/animations/string-keyframes-identifier.html b/third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-prefixed.html similarity index 63% rename from third_party/WebKit/LayoutTests/animations/string-keyframes-identifier.html rename to third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-prefixed.html index 0b9bc740..32c5f6a 100644 --- a/third_party/WebKit/LayoutTests/animations/string-keyframes-identifier.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-prefixed.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <style> @-webkit-keyframes "string id" { from { background: green; } @@ -15,5 +15,5 @@ <script> test(function() { assert_equals(getComputedStyle(target).backgroundColor, 'rgb(0, 128, 0)'); -}, 'Check that strings are permitted as @keyframes identifiers'); +}, 'Check that strings are permitted as @-webkit-keyframes identifiers'); </script>
diff --git a/third_party/WebKit/LayoutTests/animations/keyframe-unprefixed-string.html b/third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-unprefixed.html similarity index 76% rename from third_party/WebKit/LayoutTests/animations/keyframe-unprefixed-string.html rename to third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-unprefixed.html index ca22dae..a5a4f0d 100644 --- a/third_party/WebKit/LayoutTests/animations/keyframe-unprefixed-string.html +++ b/third_party/WebKit/LayoutTests/animations/prefixed/string-keyframes-identifier-unprefixed.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <style> @keyframes "anim" { from { background: red; }
diff --git a/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform-expected.txt b/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform-expected.txt index fa061fcc..8ba2169e 100644 --- a/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform-expected.txt
@@ -1,10 +1,10 @@ -PASS - "webkitTransform" property for "box1" element at 2s saw something close to: 0.309017,0.951057,-0.951057,0.309017,0,0 -PASS - "webkitTransform" property for "box2" element at 2s saw something close to: 0.309017,0.951057,-0.951057,0.309017,0,0 -PASS - "webkitTransform" property for "box1" and "box2" elements at 2s are close enough to each other -PASS - "webkitTransform" property for "box1" element at 5s saw something close to: -1,0,0,-1,0,0 -PASS - "webkitTransform" property for "box2" element at 5s saw something close to: -1,0,0,-1,0,0 -PASS - "webkitTransform" property for "box1" and "box2" elements at 5s are close enough to each other -PASS - "webkitTransform" property for "box1" element at 8s saw something close to: 0.309017,-0.951057,0.951057,0.309017,0,0 -PASS - "webkitTransform" property for "box2" element at 8s saw something close to: 0.309017,-0.951057,0.951057,0.309017,0,0 -PASS - "webkitTransform" property for "box1" and "box2" elements at 8s are close enough to each other +PASS - "transform" property for "box1" element at 2s saw something close to: 0.309017,0.951057,-0.951057,0.309017,0,0 +PASS - "transform" property for "box2" element at 2s saw something close to: 0.309017,0.951057,-0.951057,0.309017,0,0 +PASS - "transform" property for "box1" and "box2" elements at 2s are close enough to each other +PASS - "transform" property for "box1" element at 5s saw something close to: -1,0,0,-1,0,0 +PASS - "transform" property for "box2" element at 5s saw something close to: -1,0,0,-1,0,0 +PASS - "transform" property for "box1" and "box2" elements at 5s are close enough to each other +PASS - "transform" property for "box1" element at 8s saw something close to: 0.309017,-0.951057,0.951057,0.309017,0,0 +PASS - "transform" property for "box2" element at 8s saw something close to: 0.309017,-0.951057,0.951057,0.309017,0,0 +PASS - "transform" property for "box1" and "box2" elements at 8s are close enough to each other
diff --git a/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform.html b/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform.html index 4a8e413..ef385f3 100644 --- a/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform.html +++ b/third_party/WebKit/LayoutTests/animations/simultaneous-start-transform.html
@@ -12,11 +12,11 @@ height: 100px; width: 100px; background-color: blue; - -webkit-animation-duration: 10s; - -webkit-animation-timing-function: linear; - -webkit-animation-name: anim; + animation-duration: 10s; + animation-timing-function: linear; + animation-name: anim; } - @-webkit-keyframes anim { + @keyframes anim { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @@ -34,15 +34,15 @@ const expectedValues = [ // [time, element-id, property, expected-value, tolerance] - [2, "box1", "webkitTransform", [ 0.309017, 0.951057, -0.951057, 0.309017, 0, 0 ], 0.05], - [2, "box2", "webkitTransform", [ 0.309017, 0.951057, -0.951057, 0.309017, 0, 0 ], 0.05], - [2, ["box1", "box2"], "webkitTransform", "", 0], - [5, "box1", "webkitTransform", [ -1, 0, 0, -1, 0, 0 ], 0.05], - [5, "box2", "webkitTransform", [ -1, 0, 0, -1, 0, 0 ], 0.05], - [5, ["box1", "box2"], "webkitTransform", "", 0], - [8, "box1", "webkitTransform", [ 0.309017, -0.951057, 0.951057, 0.309017, 0, 0 ], 0.05], - [8, "box2", "webkitTransform", [ 0.309017, -0.951057, 0.951057, 0.309017, 0, 0 ], 0.05], - [8, ["box1", "box2"], "webkitTransform", "", 0], + [2, "box1", "transform", [ 0.309017, 0.951057, -0.951057, 0.309017, 0, 0 ], 0.05], + [2, "box2", "transform", [ 0.309017, 0.951057, -0.951057, 0.309017, 0, 0 ], 0.05], + [2, ["box1", "box2"], "transform", "", 0], + [5, "box1", "transform", [ -1, 0, 0, -1, 0, 0 ], 0.05], + [5, "box2", "transform", [ -1, 0, 0, -1, 0, 0 ], 0.05], + [5, ["box1", "box2"], "transform", "", 0], + [8, "box1", "transform", [ 0.309017, -0.951057, 0.951057, 0.309017, 0, 0 ], 0.05], + [8, "box2", "transform", [ 0.309017, -0.951057, 0.951057, 0.309017, 0, 0 ], 0.05], + [8, ["box1", "box2"], "transform", "", 0], ]; runAnimationTest(expectedValues);
diff --git a/third_party/WebKit/LayoutTests/animations/the-effect-value-of-a-keyframe-effect.html b/third_party/WebKit/LayoutTests/animations/the-effect-value-of-a-keyframe-effect.html index bb01d321..ebcfb37b 100644 --- a/third_party/WebKit/LayoutTests/animations/the-effect-value-of-a-keyframe-effect.html +++ b/third_party/WebKit/LayoutTests/animations/the-effect-value-of-a-keyframe-effect.html
@@ -14,7 +14,7 @@ test(function(t) { var div = createDiv(t); div.style.color = 'rgb(0, 0, 0)'; - var anim = div.animate({ color: [ '-webkit-text', '-webkit-text'] }, 1000); + var anim = div.animate({ color: [ 'banana-text', 'apple-text'] }, 1000); anim.pause(); anim.currentTime = 0; @@ -23,4 +23,4 @@ }, 'Tests keyframes with property values which are unsupported are removed'); </script> -</body> \ No newline at end of file +</body>
diff --git a/third_party/WebKit/LayoutTests/animations/timing-model.html b/third_party/WebKit/LayoutTests/animations/timing-model.html index bf839fc..1b3991472 100644 --- a/third_party/WebKit/LayoutTests/animations/timing-model.html +++ b/third_party/WebKit/LayoutTests/animations/timing-model.html
@@ -283,9 +283,8 @@ document.body.appendChild(child); } -var prefix = 'animation' in document.body.style ? '' : '-webkit-'; function assertIterationTime(animation, expectations) { - testElement.style.setProperty(prefix + 'animation', 'invalid ' + animation); + testElement.style.setProperty('animation', 'invalid ' + animation); update(); expectations.forEach(function(expectation) { @@ -293,18 +292,12 @@ console.log('ERROR: Test requires too much precision. ' + JSON.stringify(expectation)); return; } - testElement.style.setProperty(prefix + 'animation-name', 'invalid'); + testElement.style.setProperty('animation-name', 'invalid'); update(); var delay = expectation.at * -1; - testElement.style.setProperty(prefix + 'animation-delay', delay + 's'); - testElement.style.setProperty(prefix + 'animation-name', 'test'); - update(); - // FIXME: Set play-state: paused before starting the animation. - // For now, updating the style another two times makes this work in WebKit/Blink - testElement.style.setProperty(prefix + 'animation-name', 'test'); - update(); - testElement.style.setProperty(prefix + 'animation-name', 'test'); + testElement.style.setProperty('animation-delay', delay + 's'); + testElement.style.setProperty('animation-name', 'test'); update(); var result = getComputedStyle(testElement).left; @@ -330,14 +323,6 @@ font-weight: bold; color: red; } -@-webkit-keyframes test { - 0% { - left: 0px; - } - 100% { - left: 1px; - } -} @keyframes test { 0% { left: 0px;
diff --git a/third_party/WebKit/LayoutTests/animations/transition-zoomed-length.html b/third_party/WebKit/LayoutTests/animations/transition-zoomed-length.html index 516d4d9..07ed463 100644 --- a/third_party/WebKit/LayoutTests/animations/transition-zoomed-length.html +++ b/third_party/WebKit/LayoutTests/animations/transition-zoomed-length.html
@@ -48,16 +48,16 @@ 'strokeWidth', 'top', 'verticalAlign', - 'webkitBorderHorizontalSpacing', - 'webkitBorderVerticalSpacing', + 'borderHorizontalSpacing', + 'borderVerticalSpacing', 'columnGap', 'columnRuleWidth', 'columnWidth', - 'webkitPerspectiveOriginX', - 'webkitPerspectiveOriginY', - 'webkitTransformOriginX', - 'webkitTransformOriginY', - 'webkitTransformOriginZ', + 'perspectiveOriginX', + 'perspectiveOriginY', + 'transformOriginX', + 'transformOriginY', + 'transformOriginZ', 'width', 'wordSpacing', 'x',
diff --git a/third_party/WebKit/LayoutTests/animations/unsigned-underflow-expected.txt b/third_party/WebKit/LayoutTests/animations/unsigned-underflow-expected.txt index dcf6c95..69f523e8 100644 --- a/third_party/WebKit/LayoutTests/animations/unsigned-underflow-expected.txt +++ b/third_party/WebKit/LayoutTests/animations/unsigned-underflow-expected.txt
@@ -1,5 +1,5 @@ PASS - "border-top-width" property for "target" element at 0.5s saw something close to: 0 PASS - "outline-width" property for "target" element at 0.5s saw something close to: 0 -PASS - "-webkit-column-count" property for "target" element at 0.5s saw something close to: 1 -PASS - "-webkit-column-rule-width" property for "target" element at 0.5s saw something close to: 0 +PASS - "column-count" property for "target" element at 0.5s saw something close to: 1 +PASS - "column-rule-width" property for "target" element at 0.5s saw something close to: 0
diff --git a/third_party/WebKit/LayoutTests/animations/unsigned-underflow.html b/third_party/WebKit/LayoutTests/animations/unsigned-underflow.html index 3be4bdc7..b5c903e 100644 --- a/third_party/WebKit/LayoutTests/animations/unsigned-underflow.html +++ b/third_party/WebKit/LayoutTests/animations/unsigned-underflow.html
@@ -4,22 +4,22 @@ height: 100px; width: 100px; border: solid blue 0px; - -webkit-animation-duration: 1s; - -webkit-animation-timing-function: cubic-bezier(0,-1,1,-1); - -webkit-animation-name: anim; + animation-duration: 1s; + animation-timing-function: cubic-bezier(0,-1,1,-1); + animation-name: anim; } -@-webkit-keyframes anim { +@keyframes anim { from { border-top-width: 0px; outline-width: 0px; - -webkit-column-count: 1; - -webkit-column-rule-width: 0px; + column-count: 1; + column-rule-width: 0px; } to { border-top-width: 10px; outline-width: 10px; - -webkit-column-count: 10; - -webkit-column-rule-width: 10px; + column-count: 10; + column-rule-width: 10px; } } </style> @@ -32,8 +32,8 @@ // [time, element-id, property, expected-value, tolerance] [0.5, 'target', 'border-top-width', 0, 0], [0.5, 'target', 'outline-width', 0, 0], - [0.5, 'target', '-webkit-column-count', 1, 0], - [0.5, 'target', '-webkit-column-rule-width', 0, 0], + [0.5, 'target', 'column-count', 1, 0], + [0.5, 'target', 'column-rule-width', 0, 0], ]; runAnimationTest(expectedValues);
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/animated-css-property-usecounter-for-transitions.html b/third_party/WebKit/LayoutTests/animations/usecounters/animated-css-property-usecounter-for-transitions.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/animated-css-property-usecounter-for-transitions.html rename to third_party/WebKit/LayoutTests/animations/usecounters/animated-css-property-usecounter-for-transitions.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/animated-css-property-usecounter.html b/third_party/WebKit/LayoutTests/animations/usecounters/animated-css-property-usecounter.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/animated-css-property-usecounter.html rename to third_party/WebKit/LayoutTests/animations/usecounters/animated-css-property-usecounter.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-linear.html b/third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-linear.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-linear.html rename to third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-linear.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-other1.html b/third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-other1.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-other1.html rename to third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-other1.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-other2.html b/third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-other2.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/function-easing-use-counters-other2.html rename to third_party/WebKit/LayoutTests/animations/usecounters/function-easing-use-counters-other2.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-keyword-timing-function-deprecated-expected.txt b/third_party/WebKit/LayoutTests/animations/usecounters/step-middle-keyword-timing-function-deprecated-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-keyword-timing-function-deprecated-expected.txt rename to third_party/WebKit/LayoutTests/animations/usecounters/step-middle-keyword-timing-function-deprecated-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-keyword-timing-function-deprecated.html b/third_party/WebKit/LayoutTests/animations/usecounters/step-middle-keyword-timing-function-deprecated.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-keyword-timing-function-deprecated.html rename to third_party/WebKit/LayoutTests/animations/usecounters/step-middle-keyword-timing-function-deprecated.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-timing-function-deprecated-expected.txt b/third_party/WebKit/LayoutTests/animations/usecounters/step-middle-timing-function-deprecated-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-timing-function-deprecated-expected.txt rename to third_party/WebKit/LayoutTests/animations/usecounters/step-middle-timing-function-deprecated-expected.txt
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-timing-function-deprecated.html b/third_party/WebKit/LayoutTests/animations/usecounters/step-middle-timing-function-deprecated.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/step-middle-timing-function-deprecated.html rename to third_party/WebKit/LayoutTests/animations/usecounters/step-middle-timing-function-deprecated.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/use-count-SyntheticKeyframesInCompositedCSSAnimation.html b/third_party/WebKit/LayoutTests/animations/usecounters/use-count-SyntheticKeyframesInCompositedCSSAnimation.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/use-count-SyntheticKeyframesInCompositedCSSAnimation.html rename to third_party/WebKit/LayoutTests/animations/usecounters/use-count-SyntheticKeyframesInCompositedCSSAnimation.html
diff --git a/third_party/WebKit/LayoutTests/animations/usecounter-tests/use-count-stacked-neutral-keyframe.html b/third_party/WebKit/LayoutTests/animations/usecounters/use-count-stacked-neutral-keyframe.html similarity index 100% rename from third_party/WebKit/LayoutTests/animations/usecounter-tests/use-count-stacked-neutral-keyframe.html rename to third_party/WebKit/LayoutTests/animations/usecounters/use-count-stacked-neutral-keyframe.html
diff --git a/third_party/WebKit/LayoutTests/editing/selection/user-select/user-select-all.html b/third_party/WebKit/LayoutTests/editing/selection/user-select/user-select-all.html index ed94f5a..db1f4f86 100644 --- a/third_party/WebKit/LayoutTests/editing/selection/user-select/user-select-all.html +++ b/third_party/WebKit/LayoutTests/editing/selection/user-select/user-select-all.html
@@ -40,39 +40,63 @@ selection => selection.modify('move', 'left', 'character'), '<div>foo<span style="-webkit-user-select:all">ba|r</span>baz</div>'); }, 'Modify move is not affected by user-select:all.'); -test(() => { - function mouseMoveFromTo(selection, fromX, toX) { - eventSender.dragMode = false; - var document = selection.document; - var root = document.getElementById('div'); - eventSender.mouseMoveTo(document.offsetLeft + fromX, document.offsetTop + root.offsetTop + 5); - eventSender.mouseDown(); - eventSender.leapForward(100); - eventSender.mouseMoveTo(document.offsetLeft + toX, document.offsetTop + root.offsetTop + 5); - eventSender.mouseUp(); - }; - assert_selection( - '<div id="div">foo<span style="-webkit-user-select:all">bar<span id="middle">bar</span>bar</span>baz</div>', - selection => { - var middle = selection.document.getElementById('middle'); - mouseMoveFromTo(selection, middle.offsetLeft, middle.offsetLeft + middle.offsetWidth);}, - '<div id="div">foo<span style="-webkit-user-select:all">^bar<span id="middle">bar</span>bar|</span>baz</div>'); - assert_selection( - '<div id="div">foo<span style="-webkit-user-select:all">bar<span id="middle">bar</span>bar</span>baz</div>', - selection => { - var document = selection.document; - mouseMoveFromTo(selection, document.getElementById('div').offsetLeft, document.getElementById('middle').offsetLeft);}, - '<div id="div">^foo<span style="-webkit-user-select:all">bar<span id="middle">bar</span>bar|</span>baz</div>'); - assert_selection( - '<div id="div">foo<span style="-webkit-user-select:all">bar<span id="middle">bar</span>bar</span>baz</div>', - selection => { - var document = selection.document; - var middle = document.getElementById('middle'); - var div = document.getElementById('div'); - mouseMoveFromTo(selection, div.offsetLeft + div.offsetWidth, middle.offsetLeft);}, - '<div id="div">foo<span style="-webkit-user-select:all">|bar<span id="middle">bar</span>bar</span>baz^</div>'); -}, 'Mouse move selects over user-select:all.'); +function mouseDownAt(x, y) { + assert_exists(window, 'eventSender'); + eventSender.dragMode = false; + eventSender.mouseMoveTo(x, y); + eventSender.mouseDown(); +} + +function mouseMoveFromTo(y, fromX, toX) { + mouseDownAt(fromX, y); + eventSender.leapForward(100); + eventSender.mouseMoveTo(toX, y); + eventSender.mouseUp(); +} + +const kSample = [ + '<div id="div">', + 'abc <span style="user-select:all">', + 'def <span id="middle">ghi </span>jkl ', + '</span>mno', + '</div>' +].join(''); + +test(() => assert_selection( + kSample, + selection => { + const div = selection.document.getElementById('div'); + const middle = selection.document.getElementById('middle'); + mouseDownAt(selection.computeLeft(middle), selection.computeTop(div)); + }, + '<div id="div">abc <span style="user-select:all">^def <span id="middle">ghi </span>jkl |</span>mno</div>'), + 'Click inside user-select:all'); + +test(() => assert_selection( + kSample, + selection => { + const div = selection.document.getElementById('div'); + const middle = selection.document.getElementById('middle'); + mouseMoveFromTo(selection.computeTop(div), + selection.computeLeft(div), + selection.computeLeft(middle)); + }, + '<div id="div">^abc <span style="user-select:all">def <span id="middle">ghi </span>jkl |</span>mno</div>'), + 'Drag from left of user-select:all to inside user-select:all'); + +test(() => assert_selection( + kSample, + selection => { + const div = selection.document.getElementById('div'); + const middle = selection.document.getElementById('middle'); + mouseMoveFromTo(selection.computeTop(div), + selection.computeLeft(div) + div.offsetWidth, + selection.computeLeft(middle)); + }, + '<div id="div">abc <span style="user-select:all">|def <span id="middle">ghi </span>jkl </span>mno^</div>'), + 'Drag from right of user-select:all to inside user-select:all'); + test(() => { assert_selection( '<div>foo<span style="-webkit-user-select:all">bar<span id="middle">bar</span>bar</span>|baz</div>',
diff --git a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json index 093e9f8..dd643821 100644 --- a/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json +++ b/third_party/WebKit/LayoutTests/external/WPT_BASE_MANIFEST.json
@@ -3967,18 +3967,6 @@ {} ] ], - "uievents/keyboard/key-manual.css": [ - [ - "/uievents/keyboard/key-manual.css", - {} - ] - ], - "uievents/keyboard/key-manual.js": [ - [ - "/uievents/keyboard/key-manual.js", - {} - ] - ], "uievents/mouse/mouseevent_move_button-manual.html": [ [ "/uievents/mouse/mouseevent_move_button-manual.html", @@ -84205,6 +84193,11 @@ {} ] ], + "dom/nodes/Element-matches-init.js": [ + [ + {} + ] + ], "dom/nodes/Element-matches.js": [ [ {} @@ -87640,6 +87633,36 @@ {} ] ], + "html/browsers/offline/appcache/workers/resources/appcache-dedicated-worker-not-in-cache.js": [ + [ + {} + ] + ], + "html/browsers/offline/appcache/workers/resources/appcache-shared-worker-not-in-cache.js": [ + [ + {} + ] + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker-data.py": [ + [ + {} + ] + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker-import.py": [ + [ + {} + ] + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker.manifest": [ + [ + {} + ] + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker.py": [ + [ + {} + ] + ], "html/browsers/offline/application-cache-api/.gitkeep": [ [ {} @@ -105400,6 +105423,16 @@ {} ] ], + "uievents/keyboard/key.css": [ + [ + {} + ] + ], + "uievents/keyboard/key.js": [ + [ + {} + ] + ], "uievents/legacy-domevents-tests/Status.html": [ [ {} @@ -130450,6 +130483,12 @@ {} ] ], + "html/browsers/offline/appcache/workers/appcache-worker.html": [ + [ + "/html/browsers/offline/appcache/workers/appcache-worker.html", + {} + ] + ], "html/browsers/offline/application-cache-api/api_status_idle.html": [ [ "/html/browsers/offline/application-cache-api/api_status_idle.html", @@ -219671,8 +219710,12 @@ "792eff6ef501669e9302c4d055f9c6d6c68b9410", "support" ], + "dom/nodes/Element-matches-init.js": [ + "ddce738f5820e51c5132356273e62235f2c8d0e4", + "support" + ], "dom/nodes/Element-matches.html": [ - "1c3babeb4f7c2a9f2a35d96aa6eb456f88966cbd", + "c3d29ce89418e989a6ecba94771f643298128a26", "testharness" ], "dom/nodes/Element-matches.js": [ @@ -219732,7 +219775,7 @@ "support" ], "dom/nodes/Element-webkitMatchesSelector.html": [ - "31934621453740439f9b318c0bb8b180ac3071c3", + "4893646fbb75af660d00070d704bf41a7ba77078", "testharness" ], "dom/nodes/MutationObserver-attributes.html": [ @@ -225787,6 +225830,34 @@ "da39a3ee5e6b4b0d3255bfef95601890afd80709", "support" ], + "html/browsers/offline/appcache/workers/appcache-worker.html": [ + "d4dc559a600b1d197e7b31f960b396da3faa4e42", + "testharness" + ], + "html/browsers/offline/appcache/workers/resources/appcache-dedicated-worker-not-in-cache.js": [ + "4f2e89ef4b23ff17d6c333831cdd81ebf46a9315", + "support" + ], + "html/browsers/offline/appcache/workers/resources/appcache-shared-worker-not-in-cache.js": [ + "e0ca1027ad1077119b95f6a56055417452ab4b04", + "support" + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker-data.py": [ + "5686f9536fc98675e737d703d054370b1398399a", + "support" + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker-import.py": [ + "8dced5671671d536c1e0bb554bf919f7f2f3861e", + "support" + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker.manifest": [ + "284dcbf9adad4bc5d823e654ca889c08f679735c", + "support" + ], + "html/browsers/offline/appcache/workers/resources/appcache-worker.py": [ + "8681ab72485c543d1e22de75cee685478090a848", + "support" + ], "html/browsers/offline/application-cache-api/.gitkeep": [ "da39a3ee5e6b4b0d3255bfef95601890afd80709", "support" @@ -228644,7 +228715,7 @@ "support" ], "html/editing/activation/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/activation/click-manual.html": [ @@ -232016,7 +232087,7 @@ "support" ], "html/editing/editing-0/contenteditable/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/editing-0/contenteditable/contentEditable-invalidvalue.html": [ @@ -232036,7 +232107,7 @@ "support" ], "html/editing/editing-0/making-entire-documents-editable-the-designmode-idl-attribute/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/editing-0/making-entire-documents-editable-the-designmode-idl-attribute/original-id.json": [ @@ -232052,7 +232123,7 @@ "support" ], "html/editing/editing-0/spelling-and-grammar-checking/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/editing-0/spelling-and-grammar-checking/references/spelling-markers-001-ref.html": [ @@ -232112,7 +232183,7 @@ "support" ], "html/editing/focus/document-level-focus-apis/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/focus/document-level-focus-apis/document-level-apis.html": [ @@ -232132,7 +232203,7 @@ "support" ], "html/editing/focus/focus-management/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/focus/focus-management/focus-event-targets-simple.html": [ @@ -232152,7 +232223,7 @@ "support" ], "html/editing/focus/sequential-focus-navigation-and-the-tabindex-attribute/OWNERS": [ - "e3e7f3973cf8f9b466d4f22d1ec3b9b9241fb906", + "2764978ea7b3de2789f3e5c8ad8e819a697cedd9", "support" ], "html/editing/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-default-value.html": [ @@ -262048,20 +262119,20 @@ "support" ], "uievents/keyboard/key-101en-us-manual.html": [ - "8c4bedcea88fd39cfe291e40b11c3b0cb510267a", + "0b54b880246409466d57dcbe941b89d74587e8e4", "manual" ], "uievents/keyboard/key-102fr-fr-manual.html": [ - "74ec4ae6f0cfa8ddc2f296d058a70d64977eb28a", + "65b31e543203b36d6a1026ba9da3e60de507cf67", "manual" ], - "uievents/keyboard/key-manual.css": [ + "uievents/keyboard/key.css": [ "54d5f8a452d8bbbd040e66af7594debacb6d0377", - "manual" + "support" ], - "uievents/keyboard/key-manual.js": [ + "uievents/keyboard/key.js": [ "d189977c13fcff73f9604a56a919676930176db4", - "manual" + "support" ], "uievents/legacy-domevents-tests/Status.html": [ "b4cfc46993f2349beca9aa583b1eaf24a1bdfe63", @@ -262524,7 +262595,7 @@ "testharness" ], "url/urltestdata.json": [ - "dad11f4fb0275d1900f3d2362628bff54814c6dc", + "0d888ff45fc4575ac193410701c08f05e58a5364", "support" ], "user-timing/clear_all_marks.any.js": [
diff --git a/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches-init.js b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches-init.js new file mode 100644 index 0000000..254af615 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches-init.js
@@ -0,0 +1,65 @@ +function init(e, method) { + /* + * This test suite tests Selectors API methods in 4 different contexts: + * 1. Document node + * 2. In-document Element node + * 3. Detached Element node (an element with no parent, not in the document) + * 4. Document Fragment node + * + * For each context, the following tests are run: + * + * The interface check tests ensure that each type of node exposes the Selectors API methods. + * + * The matches() tests are run + * All the selectors tested for both the valid and invalid selector tests are found in selectors.js. + * See comments in that file for documentation of the format used. + * + * The level2-lib.js file contains all the common test functions for running each of the aforementioned tests + */ + + var docType = "html"; // Only run tests suitable for HTML + + // Prepare the nodes for testing + var doc = e.target.contentDocument; // Document Node tests + + var element = doc.getElementById("root"); // In-document Element Node tests + + //Setup the namespace tests + setupSpecialElements(doc, element); + + var outOfScope = element.cloneNode(true); // Append this to the body before running the in-document + // Element tests, but after running the Document tests. This + // tests that no elements that are not descendants of element + // are selected. + + traverse(outOfScope, function(elem) { // Annotate each element as being a clone; used for verifying + elem.setAttribute("data-clone", ""); // that none of these elements ever match. + }); + + + var detached = element.cloneNode(true); // Detached Element Node tests + + var fragment = doc.createDocumentFragment(); // Fragment Node tests + fragment.appendChild(element.cloneNode(true)); + + // Setup Tests + interfaceCheckMatches(method, "Document", doc); + interfaceCheckMatches(method, "Detached Element", detached); + interfaceCheckMatches(method, "Fragment", fragment); + interfaceCheckMatches(method, "In-document Element", element); + + runSpecialMatchesTests(method, "DIV Element", element); + runSpecialMatchesTests(method, "NULL Element", document.createElement("null")); + runSpecialMatchesTests(method, "UNDEFINED Element", document.createElement("undefined")); + + runInvalidSelectorTestMatches(method, "Document", doc, invalidSelectors); + runInvalidSelectorTestMatches(method, "Detached Element", detached, invalidSelectors); + runInvalidSelectorTestMatches(method, "Fragment", fragment, invalidSelectors); + runInvalidSelectorTestMatches(method, "In-document Element", element, invalidSelectors); + + runMatchesTest(method, "In-document", doc, validSelectors, "html"); + runMatchesTest(method, "Detached", detached, validSelectors, "html"); + runMatchesTest(method, "Fragment", fragment, validSelectors, "html"); + + runMatchesTest(method, "In-document", doc, scopedSelectors, "html"); +}
diff --git a/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches.html b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches.html index b5d92748..de234b6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches.html +++ b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-matches.html
@@ -7,83 +7,16 @@ <script src="/dom/nodes/selectors.js"></script> <script src="/dom/nodes/ParentNode-querySelector-All.js"></script> <script src="Element-matches.js"></script> +<script src="Element-matches-init.js"></script> <style>iframe { visibility: hidden; position: absolute; }</style> <div id="log">This test requires JavaScript.</div> <script> -async_test(function() { - var frame = document.createElement("iframe"); - frame.onload = this.step_func_done(init); - frame.src = "/dom/nodes/ParentNode-querySelector-All-content.html#target"; - document.body.appendChild(frame); -}); - -function init(e) { - /* - * This test suite tests Selectors API methods in 4 different contexts: - * 1. Document node - * 2. In-document Element node - * 3. Detached Element node (an element with no parent, not in the document) - * 4. Document Fragment node - * - * For each context, the following tests are run: - * - * The interface check tests ensure that each type of node exposes the Selectors API methods. - * - * The matches() tests are run - * All the selectors tested for both the valid and invalid selector tests are found in selectors.js. - * See comments in that file for documentation of the format used. - * - * The level2-lib.js file contains all the common test functions for running each of the aforementioned tests - */ - - var method = "matches"; - - var docType = "html"; // Only run tests suitable for HTML - - // Prepare the nodes for testing - var doc = e.target.contentDocument; // Document Node tests - - var element = doc.getElementById("root"); // In-document Element Node tests - - //Setup the namespace tests - setupSpecialElements(doc, element); - - var outOfScope = element.cloneNode(true); // Append this to the body before running the in-document - // Element tests, but after running the Document tests. This - // tests that no elements that are not descendants of element - // are selected. - - traverse(outOfScope, function(elem) { // Annotate each element as being a clone; used for verifying - elem.setAttribute("data-clone", ""); // that none of these elements ever match. + async_test(function() { + var frame = document.createElement("iframe"); + frame.onload = this.step_func_done(e => init(e, "matches" )); + frame.src = "/dom/nodes/ParentNode-querySelector-All-content.html#target"; + document.body.appendChild(frame); }); - - - var detached = element.cloneNode(true); // Detached Element Node tests - - var fragment = doc.createDocumentFragment(); // Fragment Node tests - fragment.appendChild(element.cloneNode(true)); - - // Setup Tests - interfaceCheckMatches(method, "Document", doc); - interfaceCheckMatches(method, "Detached Element", detached); - interfaceCheckMatches(method, "Fragment", fragment); - interfaceCheckMatches(method, "In-document Element", element); - - runSpecialMatchesTests(method, "DIV Element", element); - runSpecialMatchesTests(method, "NULL Element", document.createElement("null")); - runSpecialMatchesTests(method, "UNDEFINED Element", document.createElement("undefined")); - - runInvalidSelectorTestMatches(method, "Document", doc, invalidSelectors); - runInvalidSelectorTestMatches(method, "Detached Element", detached, invalidSelectors); - runInvalidSelectorTestMatches(method, "Fragment", fragment, invalidSelectors); - runInvalidSelectorTestMatches(method, "In-document Element", element, invalidSelectors); - - runMatchesTest(method, "In-document", doc, validSelectors, "html"); - runMatchesTest(method, "Detached", detached, validSelectors, "html"); - runMatchesTest(method, "Fragment", fragment, validSelectors, "html"); - - runMatchesTest(method, "In-document", doc, scopedSelectors, "html"); -} </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-webkitMatchesSelector.html b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-webkitMatchesSelector.html index d37d723..107f810 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-webkitMatchesSelector.html +++ b/third_party/WebKit/LayoutTests/external/wpt/dom/nodes/Element-webkitMatchesSelector.html
@@ -7,83 +7,16 @@ <script src="/dom/nodes/selectors.js"></script> <script src="/dom/nodes/ParentNode-querySelector-All.js"></script> <script src="Element-matches.js"></script> +<script src="Element-matches-init.js"></script> <style>iframe { visibility: hidden; position: absolute; }</style> <div id="log">This test requires JavaScript.</div> <script> -async_test(function() { - var frame = document.createElement("iframe"); - frame.onload = this.step_func_done(init); - frame.src = "/dom/nodes/ParentNode-querySelector-All-content.html#target"; - document.body.appendChild(frame); -}); - -function init(e) { - /* - * This test suite tests Selectors API methods in 4 different contexts: - * 1. Document node - * 2. In-document Element node - * 3. Detached Element node (an element with no parent, not in the document) - * 4. Document Fragment node - * - * For each context, the following tests are run: - * - * The interface check tests ensure that each type of node exposes the Selectors API methods. - * - * The matches() tests are run - * All the selectors tested for both the valid and invalid selector tests are found in selectors.js. - * See comments in that file for documentation of the format used. - * - * The level2-lib.js file contains all the common test functions for running each of the aforementioned tests - */ - - var method = "webkitMatchesSelector"; - - var docType = "html"; // Only run tests suitable for HTML - - // Prepare the nodes for testing - var doc = e.target.contentDocument; // Document Node tests - - var element = doc.getElementById("root"); // In-document Element Node tests - - //Setup the namespace tests - setupSpecialElements(doc, element); - - var outOfScope = element.cloneNode(true); // Append this to the body before running the in-document - // Element tests, but after running the Document tests. This - // tests that no elements that are not descendants of element - // are selected. - - traverse(outOfScope, function(elem) { // Annotate each element as being a clone; used for verifying - elem.setAttribute("data-clone", ""); // that none of these elements ever match. + async_test(function() { + var frame = document.createElement("iframe"); + frame.onload = this.step_func_done(e => init(e, "webkitMatchesSelector" )); + frame.src = "/dom/nodes/ParentNode-querySelector-All-content.html#target"; + document.body.appendChild(frame); }); - - - var detached = element.cloneNode(true); // Detached Element Node tests - - var fragment = doc.createDocumentFragment(); // Fragment Node tests - fragment.appendChild(element.cloneNode(true)); - - // Setup Tests - interfaceCheckMatches(method, "Document", doc); - interfaceCheckMatches(method, "Detached Element", detached); - interfaceCheckMatches(method, "Fragment", fragment); - interfaceCheckMatches(method, "In-document Element", element); - - runSpecialMatchesTests(method, "DIV Element", element); - runSpecialMatchesTests(method, "NULL Element", document.createElement("null")); - runSpecialMatchesTests(method, "UNDEFINED Element", document.createElement("undefined")); - - runInvalidSelectorTestMatches(method, "Document", doc, invalidSelectors); - runInvalidSelectorTestMatches(method, "Detached Element", detached, invalidSelectors); - runInvalidSelectorTestMatches(method, "Fragment", fragment, invalidSelectors); - runInvalidSelectorTestMatches(method, "In-document Element", element, invalidSelectors); - - runMatchesTest(method, "In-document", doc, validSelectors, "html"); - runMatchesTest(method, "Detached", detached, validSelectors, "html"); - runMatchesTest(method, "Fragment", fragment, validSelectors, "html"); - - runMatchesTest(method, "In-document", doc, scopedSelectors, "html"); -} </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resource-timing/test_resource_timing.js b/third_party/WebKit/LayoutTests/external/wpt/resource-timing/test_resource_timing.js index d632a0d..51a3d2c 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/resource-timing/test_resource_timing.js +++ b/third_party/WebKit/LayoutTests/external/wpt/resource-timing/test_resource_timing.js
@@ -162,7 +162,11 @@ assert_equals(entries_by_name_type.length, 1, "should have a single entry for each resource (with type)"); assert_not_equals(entries_by_name, entries_by_name_type, "values should be copies"); for (p in entries_by_name[0]) { - assert_equals(entries_by_name[0][p], entries_by_name_type[0][p], "Property " + p + " should match"); + var assertMethod = assert_equals + if (Array.isArray(entries_by_name[0][p]) && Array.isArray(entries_by_name_type[0][p])) { + assertMethod = assert_array_equals + } + assertMethod(entries_by_name[0][p], entries_by_name_type[0][p], "Property " + p + " should match"); } this.done(); });
diff --git a/third_party/WebKit/LayoutTests/external/wpt/server-timing/test_server_timing.html b/third_party/WebKit/LayoutTests/external/wpt/server-timing/test_server_timing.html index 2a6ffa2..43164d69 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/server-timing/test_server_timing.html +++ b/third_party/WebKit/LayoutTests/external/wpt/server-timing/test_server_timing.html
@@ -10,35 +10,27 @@ window.addEventListener('load', function() { // there should be exactly two server-timing entries, 1 for document, 1 for img#one - test_entries(performance.getEntriesByType('server'), [{ - name: document.location.href, - entryType: 'server', - startTime: 0, - duration: 1.2, + test_entries(performance.getEntriesByType('navigation')[0].serverTiming, [{ + value: 1.2, metric: 'metric1', description: 'document', - }, { - name: document.querySelector('img#one').src, - entryType: 'server', - startTime: 0, - duration: 3.4, + }]) + test_entries(performance.getEntriesByName(document.querySelector('img#one').src)[0].serverTiming, [{ + value: 3.4, metric: 'metric2', description: 'blue.png', }]) new PerformanceObserver(function(entryList, observer) { // there should be exactly one server-timing entry, 1 for img#two - test_entries(entryList.getEntriesByType('server'), [{ - name: document.querySelector('img#two').src, - entryType: 'server', - startTime: 0, - duration: 5.6, + test_entries(entryList.getEntriesByName(document.querySelector('img#two').src)[0].serverTiming, [{ + value: 5.6, metric: 'metric3', description: 'green.png', }]) observer.disconnect() done() - }).observe({entryTypes: ['server']}) + }).observe({entryTypes: ['resource']}) var img = document.createElement('img') img.id = 'two'
diff --git a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-101en-us-manual.html b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-101en-us-manual.html index 8b9cb46..3228c65 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-101en-us-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-101en-us-manual.html
@@ -5,8 +5,8 @@ <title>Keyboard Event Manual Test</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> -<script type="text/javascript" src="key-manual.js" ></script> -<link rel="stylesheet" type="text/css" href="key-manual.css" /> +<script type="text/javascript" src="key.js" ></script> +<link rel="stylesheet" type="text/css" href="key.css" /> </head>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-102fr-fr-manual.html b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-102fr-fr-manual.html index 6521681..c5b51c47 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-102fr-fr-manual.html +++ b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-102fr-fr-manual.html
@@ -5,8 +5,8 @@ <title>Keyboard Event Manual Test</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> -<script type="text/javascript" src="key-manual.js" ></script> -<link rel="stylesheet" type="text/css" href="key-manual.css" /> +<script type="text/javascript" src="key.js" ></script> +<link rel="stylesheet" type="text/css" href="key.css" /> </head>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-manual.css b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key.css similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-manual.css rename to third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key.css
diff --git a/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-manual.js b/third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key.js similarity index 100% rename from third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key-manual.js rename to third_party/WebKit/LayoutTests/external/wpt/uievents/keyboard/key.js
diff --git a/third_party/WebKit/LayoutTests/external/wpt/url/urltestdata.json b/third_party/WebKit/LayoutTests/external/wpt/url/urltestdata.json index 974b408..86560b8 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/url/urltestdata.json +++ b/third_party/WebKit/LayoutTests/external/wpt/url/urltestdata.json
@@ -6382,6 +6382,88 @@ "search": "?a", "hash": "#%GH" }, + "Bad bases", + { + "input": "test-a.html", + "base": "a", + "failure": true + }, + { + "input": "test-a-slash.html", + "base": "a/", + "failure": true + }, + { + "input": "test-a-slash-slash.html", + "base": "a//", + "failure": true + }, + { + "input": "test-a-colon.html", + "base": "a:", + "failure": true + }, + { + "input": "test-a-colon-slash.html", + "base": "a:/", + "href": "a:/test-a-colon-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash.html", + "base": "a://", + "href": "a:///test-a-colon-slash-slash.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-slash.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-b.html", + "base": "a:b", + "failure": true + }, + { + "input": "test-a-colon-slash-b.html", + "base": "a:/b", + "href": "a:/test-a-colon-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "/test-a-colon-slash-b.html", + "search": "", + "hash": "" + }, + { + "input": "test-a-colon-slash-slash-b.html", + "base": "a://b", + "href": "a://b/test-a-colon-slash-slash-b.html", + "protocol": "a:", + "username": "", + "password": "", + "host": "b", + "hostname": "b", + "port": "", + "pathname": "/test-a-colon-slash-slash-b.html", + "search": "", + "hash": "" + }, "Null code point in fragment", { "input": "http://example.org/test?a#b\u0000c",
diff --git a/third_party/WebKit/LayoutTests/fast/dom/custom/register-element-with-U212A.html b/third_party/WebKit/LayoutTests/fast/dom/custom/register-element-with-U212A.html new file mode 100644 index 0000000..2f10600 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/dom/custom/register-element-with-U212A.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<script> +test(function () { + + var A = document.registerElement('x-tkent'); + assert_true(document.createElement('x-tkent') instanceof A); + + var B = document.registerElement('x-t\u212Aent'); + assert_true(document.createElement('x-t\u212Aent') instanceof B); + +}, 'registerElement should register type with U+212A'); + +</script> +
diff --git a/third_party/WebKit/LayoutTests/fast/forms/date/date-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/date/date-interactive-validation-required-expected.txt index 5f1e570..af050ec2 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/date/date-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/date/date-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/datetimelocal/datetimelocal-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/datetimelocal/datetimelocal-interactive-validation-required-expected.txt index 0a56dd8f..ff144c2 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/datetimelocal/datetimelocal-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/datetimelocal/datetimelocal-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/file/file-input-empty-validation-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/file/file-input-empty-validation-expected.txt index d4bb668..67319f36 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/file/file-input-empty-validation-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/file/file-input-empty-validation-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please select a file. sub-message= This tests that a file input cleared of its (required) value doesn't validate.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/file/file-input-reset-validation-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/file/file-input-reset-validation-expected.txt index eca2d436..aec1d33f 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/file/file-input-reset-validation-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/file/file-input-reset-validation-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please select a file. sub-message= This tests that a reset file input with a required value doesn't validate.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-assertion-by-validate-twice-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-assertion-by-validate-twice-expected.txt index b33a6c5..1a4a62b 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-assertion-by-validate-twice-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-assertion-by-validate-twice-expected.txt
@@ -1,5 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test a bug that an assertion fails by invoking interactive validation twice very quickly.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-attach-assertion-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-attach-assertion-expected.txt index 121bae9..335a715 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-attach-assertion-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-attach-assertion-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-prevented-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-prevented-expected.txt index 95e094a4a..5b1263fb 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-prevented-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-prevented-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= CONSOLE ERROR: line 27: An invalid form control with name='i1' is not focusable. Test if an invalid control prevents interactive form submission, and the first invalid focusable control gets focus.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-select-crash-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-select-crash-expected.txt index 8884629..73c9960 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-select-crash-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/interactive-validation-select-crash-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please select an item in the list. sub-message= Test for a bug that LayoutBlockFlow crashed when a validation message bubble for a select element with float:left was closing. PASS Not crashed.
diff --git a/third_party/WebKit/LayoutTests/fast/forms/month/month-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/month/month-interactive-validation-required-expected.txt index ba186e91..974ba801 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/month/month-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/month/month-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/number/number-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/number/number-interactive-validation-required-expected.txt index 239aada3..82d9bee 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/number/number-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/number/number-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-cancel-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-cancel-expected.txt index 4f99cb51..aab9693 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-cancel-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-cancel-expected.txt
@@ -1,5 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= Tests for reportValidity() with invalid event canceling On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-handler-updates-dom-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-handler-updates-dom-expected.txt index 561d5d9..01c1f08 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-handler-updates-dom-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-handler-updates-dom-expected.txt
@@ -1,7 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= HTMLFormElement::reportValidity() with cases that event handlers called by reportValidity() updates DOM structure. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-invalid-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-invalid-expected.txt index 21727c0..48c0dad 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/reportValidity-invalid-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/reportValidity-invalid-expected.txt
@@ -1,8 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please match the requested format. sub-message=Should type 'Lorem ipsum' -ValidationMessageClient: main-message=Please fill out this field. sub-message= -ValidationMessageClient: main-message=Please select an item in the list. sub-message= -ValidationMessageClient: main-message=Please fill out this field. sub-message= This test checks if reportValidity() returns correctly a false (meaning error) result on invalid elements, and returns a true result on a blank but valid elements. Blank but non-placeholder label options are valid. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/submit-onFocus-invalidForm-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/submit-onFocus-invalidForm-expected.txt index c28cd4f..19bda8e6 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/submit-onFocus-invalidForm-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/submit-onFocus-invalidForm-expected.txt
@@ -1,5 +1,3 @@ -ValidationMessageClient: main-message=Please match the requested format. sub-message= -ValidationMessageClient: main-message=Please match the requested format. sub-message= Test that form.submit() when called on "focus" event for invalid form should submit the form On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/time/time-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/time/time-interactive-validation-required-expected.txt index 1eba433..6fe0e4c01 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/time/time-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/time/time-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.png b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.png new file mode 100644 index 0000000..ec414a90 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.txt new file mode 100644 index 0000000..36877905 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge-expected.txt
@@ -0,0 +1,15 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x50 + LayoutBlockFlow {HTML} at (0,0) size 800x50 + LayoutBlockFlow {BODY} at (8,16) size 784x18 + LayoutBlockFlow {P} at (0,0) size 784x18 + LayoutText {#text} at (0,0) size 377x18 + text run at (0,0) width 377: "Check if a validation bubble is shown at a correct position." +layer at (661,573) size 131x19 clip at (663,575) size 127x15 + LayoutTextControl (positioned) {INPUT} at (661,573) size 131x19 [bgcolor=#FFFFFF] [border: (2px inset #EEEEEE)] +layer at (664,576) size 125x13 + LayoutBlockFlow {DIV} at (3,3) size 125x13 + LayoutText {#text} at (0,0) size 19x13 + text run at (0,0) width 19: "abc" +caret: position 0 of child 0 {#text} of child 0 {DIV} of {#document-fragment} of child 3 {INPUT} of body
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge.html b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge.html new file mode 100644 index 0000000..3411897 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-edge.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<body> +<p>Check if a validation bubble is shown at a correct position.</p> +<input pattern="\d{4}" title="Please specify four digits." value="abc" style="position:absolute; right:8px; bottom: 8px;"> +<script> +document.querySelector('input').reportValidity(); +</script> +<body>
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.png b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.png new file mode 100644 index 0000000..80755b9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.txt new file mode 100644 index 0000000..4946765 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe-expected.txt
@@ -0,0 +1,27 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x216 + LayoutBlockFlow {HTML} at (0,0) size 800x216 + LayoutBlockFlow {BODY} at (8,16) size 784x192 + LayoutBlockFlow {P} at (0,0) size 784x18 + LayoutText {#text} at (0,0) size 406x18 + text run at (0,0) width 406: "Check if a validation bubble is shown over IFRAME boundary." + LayoutBlockFlow (anonymous) at (0,34) size 784x158 + LayoutText {#text} at (0,0) size 0x0 +layer at (8,50) size 304x154 + LayoutIFrame {IFRAME} at (0,0) size 304x154 [border: (2px inset #EEEEEE)] + layer at (0,0) size 300x150 + LayoutView at (0,0) size 300x150 + layer at (0,0) size 300x68 + LayoutBlockFlow {HTML} at (0,0) size 300x68 + LayoutBlockFlow {BODY} at (8,16) size 284x36 + LayoutBlockFlow {P} at (0,0) size 284x36 + LayoutText {#text} at (0,0) size 269x36 + text run at (0,0) width 269: "Check if a validation bubble is shown at a" + text run at (0,18) width 104: "correct position." + layer at (161,123) size 131x19 clip at (163,125) size 127x15 + LayoutTextControl (positioned) {INPUT} at (161,123) size 131x19 [bgcolor=#FFFFFF] [border: (2px inset #EEEEEE)] + layer at (164,126) size 125x13 + LayoutBlockFlow {DIV} at (3,3) size 125x13 + LayoutText {#text} at (0,0) size 19x13 + text run at (0,0) width 19: "abc"
diff --git a/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe.html b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe.html new file mode 100644 index 0000000..a62cdbf --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/forms/validation-bubble-appearance-iframe.html
@@ -0,0 +1,5 @@ +<!DOCTYPE html> +<body> +<p>Check if a validation bubble is shown over IFRAME boundary.</p> +<iframe src="validation-bubble-appearance-edge.html"></iframe> +<body>
diff --git a/third_party/WebKit/LayoutTests/fast/forms/week/week-interactive-validation-required-expected.txt b/third_party/WebKit/LayoutTests/fast/forms/week/week-interactive-validation-required-expected.txt index 74fda04..f226ee1 100644 --- a/third_party/WebKit/LayoutTests/fast/forms/week/week-interactive-validation-required-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/forms/week/week-interactive-validation-required-expected.txt
@@ -1,4 +1,3 @@ -ValidationMessageClient: main-message=Please fill out this field. sub-message= Test interactive validation with required attribute. This test checks if an empty required field prevents form submission and checks if a non-empty required field doesn't prevent form submission. On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE".
diff --git a/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin-expected.txt b/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin-expected.txt new file mode 100644 index 0000000..83ce1cf --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin-expected.txt
@@ -0,0 +1,2 @@ +Downloading URL with suggested filename "" +
diff --git a/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin.html b/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin.html new file mode 100644 index 0000000..cc88f698 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/media/video-controls-download-button-saves-media-cross-origin.html
@@ -0,0 +1,31 @@ +<!DOCTYPE html> +<title>Clicking on the download button should download cross-origin media.</title> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="../../media-resources/media-controls.js"></script> +<script src="../../media-resources/media-file.js"></script> +<script src="../../media-resources/overflow-menu.js"></script> +<!--Padding ensures the overflow menu is visible for the tests. --> +<body style="padding-top: 200px; padding-left: 100px"> +<video controls></video> +<script> +if (window.testRunner) { + // Ensures that a file is downloaded and the printed output of the test + // is the same as video-controls-download-button-saves-media-expected.txt + testRunner.waitUntilExternalURLLoad(); +} +async_test(function(t) { + // Set up video + var video = document.querySelector("video"); + video.src = findMediaFile("video", "http://localhost:8000/media/resources/test"); + var controlID = "-internal-media-controls-download-button"; + var downloadButton = mediaControlsElement(internals.shadowRoot(video).firstChild, controlID); + + video.onloadeddata = t.step_func(function() { + // Click on the download button + var coords = elementCoordinates(downloadButton); + clickAtCoordinates(coords[0], coords[1]); + }); +}); +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/misc/performance-entry-serializer.html b/third_party/WebKit/LayoutTests/http/tests/misc/performance-entry-serializer.html index 9ae14b8..9cbb1d8 100644 --- a/third_party/WebKit/LayoutTests/http/tests/misc/performance-entry-serializer.html +++ b/third_party/WebKit/LayoutTests/http/tests/misc/performance-entry-serializer.html
@@ -14,7 +14,11 @@ var serialized = JSON.parse(JSON.stringify(entry)); for (var attr in entry) { if (typeof entry[attr] != 'function') { - assert_equals(serialized[attr], entry[attr], entry.constructor.name + '.' + attr); + var assertMethod = assert_equals + if (Array.isArray(serialized[attr]) && Array.isArray(entry[attr])) { + assertMethod = assert_array_equals + } + assertMethod(serialized[attr], entry[attr], entry.constructor.name + '.' + attr); } } }
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 6b00495..3b541306 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -692,6 +692,59 @@ method start setter onmessage setter onmessageerror +interface Mojo + static method bindInterface + static method createDataPipe + static method createMessagePipe + static method createSharedBuffer + attribute @@toStringTag + attribute RESULT_ABORTED + attribute RESULT_ALREADY_EXISTS + attribute RESULT_BUSY + attribute RESULT_CANCELLED + attribute RESULT_DATA_LOSS + attribute RESULT_DEADLINE_EXCEEDED + attribute RESULT_FAILED_PRECONDITION + attribute RESULT_INTERNAL + attribute RESULT_INVALID_ARGUMENT + attribute RESULT_NOT_FOUND + attribute RESULT_OK + attribute RESULT_OUT_OF_RANGE + attribute RESULT_PERMISSION_DENIED + attribute RESULT_RESOURCE_EXHAUSTED + attribute RESULT_SHOULD_WAIT + attribute RESULT_UNAVAILABLE + attribute RESULT_UNIMPLEMENTED + attribute RESULT_UNKNOWN + method constructor +interface MojoHandle + attribute @@toStringTag + method close + method constructor + method discardData + method duplicateBufferHandle + method mapBuffer + method queryData + method readData + method readMessage + method watch + method writeData + method writeMessage +interface MojoInterfaceInterceptor : EventTarget + attribute @@toStringTag + getter oninterfacerequest + method constructor + method start + method stop + setter oninterfacerequest +interface MojoInterfaceRequestEvent : Event + attribute @@toStringTag + getter handle + method constructor +interface MojoWatcher + attribute @@toStringTag + method cancel + method constructor interface NavigationPreloadManager attribute @@toStringTag method constructor
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame-expected.txt index 856e153..87741ca 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame-expected.txt
@@ -1,3 +1,4 @@ + Paused on 'debugger;' resume restartFrame
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.html deleted file mode 100644 index 7d1ba5d..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.html +++ /dev/null
@@ -1,76 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function testFunction() -{ - debugger; -} - -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedOne; - - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "setTimeout(testFunction, 0)" }); - - var obsoleteTopFrameId; - - function handleDebuggerPausedOne(messageObject) - { - InspectorTest.log("Paused on 'debugger;'"); - - var topFrame = messageObject.params.callFrames[0]; - obsoleteTopFrameId = topFrame.callFrameId; - - InspectorTest.eventHandler["Debugger.paused"] = undefined; - - InspectorTest.sendCommand("Debugger.resume", { }, callbackResume); - } - - function callbackResume(response) - { - InspectorTest.log("resume"); - InspectorTest.log("restartFrame"); - InspectorTest.sendCommand("Debugger.restartFrame", { callFrameId: obsoleteTopFrameId }, callbackRestartFrame); - } - - function callbackRestartFrame(response) - { - logErrorResponse(response); - InspectorTest.log("evaluateOnFrame"); - InspectorTest.sendCommand("Debugger.evaluateOnCallFrame", { callFrameId: obsoleteTopFrameId, expression: "0"} , callbackEvaluate); - } - - function callbackEvaluate(response) - { - logErrorResponse(response); - InspectorTest.log("setVariableValue"); - InspectorTest.sendCommand("Debugger.setVariableValue", { callFrameId: obsoleteTopFrameId, scopeNumber: 0, variableName: "a", newValue: { value: 0 } }, callbackSetVariableValue); - } - - function callbackSetVariableValue(response) - { - logErrorResponse(response); - InspectorTest.completeTest(); - } - - function logErrorResponse(response) - { - if (response.error) { - if (response.error.message.indexOf("Can only perform operation while paused.") != -1) { - InspectorTest.log("PASS, error message as expected"); - return; - } - } - InspectorTest.log("FAIL, unexpected error message"); - InspectorTest.log(JSON.stringify(response)); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.js new file mode 100644 index 0000000..b9ec2d0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/access-obsolete-frame.js
@@ -0,0 +1,35 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + function logErrorResponse(response) { + if (response.error) { + if (response.error.message.indexOf('Can only perform operation while paused.') != -1) { + testRunner.log('PASS, error message as expected'); + return; + } + } + testRunner.log('FAIL, unexpected error message'); + testRunner.log(JSON.stringify(response)); + } + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: 'setTimeout(() => { debugger; }, 0)' }); + + var messageObject = await dp.Debugger.oncePaused(); + testRunner.log(`Paused on 'debugger;'`); + var topFrame = messageObject.params.callFrames[0]; + var obsoleteTopFrameId = topFrame.callFrameId; + + await dp.Debugger.resume(); + testRunner.log('resume'); + testRunner.log('restartFrame'); + + logErrorResponse(await dp.Debugger.restartFrame({callFrameId: obsoleteTopFrameId})); + testRunner.log('evaluateOnFrame'); + + logErrorResponse(await dp.Debugger.evaluateOnCallFrame({callFrameId: obsoleteTopFrameId, expression: '0'})); + testRunner.log('setVariableValue'); + + logErrorResponse(await dp.Debugger.setVariableValue({callFrameId: obsoleteTopFrameId, scopeNumber: 0, variableName: 'a', newValue: { value: 0 }})); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation-expected.txt index d309d42..ccc8515 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation-expected.txt
@@ -1,3 +1,4 @@ + Paused on 'debugger;' Top frame location: {"scriptId":"42","lineNumber":8,"columnNumber":4} Top frame functionLocation: {"scriptId":"42","lineNumber":5,"columnNumber":21}
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.html deleted file mode 100644 index 84fab01dd..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.html +++ /dev/null
@@ -1,33 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function testFunction() -{ - var a = 2; - debugger; -} - -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPaused; - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "setTimeout(testFunction, 0)" }); - - function handleDebuggerPaused(messageObject) - { - InspectorTest.log("Paused on 'debugger;'"); - var topFrame = messageObject.params.callFrames[0]; - topFrame.location.scriptId = "42"; - topFrame.functionLocation.scriptId = "42"; - InspectorTest.log("Top frame location: " + JSON.stringify(topFrame.location)); - InspectorTest.log("Top frame functionLocation: " + JSON.stringify(topFrame.functionLocation)); - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.js new file mode 100644 index 0000000..f7f3db31 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/call-frame-functionLocation.js
@@ -0,0 +1,26 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: ` + + + + +function testFunction() +{ + var a = 2; + debugger; +} +setTimeout(testFunction, 0); + `}); + + var messageObject = await dp.Debugger.oncePaused(); + testRunner.log(`Paused on 'debugger;'`); + var topFrame = messageObject.params.callFrames[0]; + topFrame.location.scriptId = '42'; + topFrame.functionLocation.scriptId = '42'; + testRunner.log('Top frame location: ' + JSON.stringify(topFrame.location)); + testRunner.log('Top frame functionLocation: ' + JSON.stringify(topFrame.functionLocation)); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation-expected.txt index d0c6ce7..404cd9ac 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation-expected.txt
@@ -1,3 +1,4 @@ + Paused on debugger statement Paused after continueToLocation Stopped on line 8, expected 8, requested 8, (0-based numbers).
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.html deleted file mode 100644 index 5ae2992..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.html +++ /dev/null
@@ -1,103 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script type="text/javascript" src="resources/statements.js"></script> -<script> - -function test() -{ - var scenario = [ - // requested line number, expected control parameter 'step', expected line number - [ 8, 1, 8 ], - [ 8, 1, 8 ], - [ 12, 6, 17 ], - [ 13, 6, 17 ], - [ 17, 6, 17 ], - [ 17, 6, 17 ], - ]; - - InspectorTest.sendCommand("Debugger.enable", {}); - - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "statementsExample" }, callbackEvalFunctionObject); - - function callbackEvalFunctionObject(response) - { - var functionObjectId = response.result.result.objectId; - InspectorTest.sendCommand("Runtime.getProperties", { objectId: functionObjectId }, callbackFunctionDetails); - } - - function callbackFunctionDetails(response) - { - var result = response.result; - var scriptId; - for (var prop of result.internalProperties) { - if (prop.name === "[[FunctionLocation]]") - scriptId = prop.value.value.scriptId; - } - - nextScenarioStep(0); - - function nextScenarioStep(pos) - { - if (pos < scenario.length) - gotoSinglePassChain(scriptId, scenario[pos][0], scenario[pos][1], scenario[pos][2], nextScenarioStep.bind(this, pos + 1)); - else - InspectorTest.completeTest(); - } - } - - function gotoSinglePassChain(scriptId, lineNumber, expectedResult, expectedLineNumber, next) - { - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedOne; - - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "setTimeout(statementsExample, 0)" }); - - function handleDebuggerPausedOne(messageObject) - { - InspectorTest.log("Paused on debugger statement"); - - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedTwo; - - InspectorTest.sendCommand("Debugger.continueToLocation", { location: { scriptId: scriptId, lineNumber: lineNumber, columnNumber: 0} }, logContinueToLocation); - - function logContinueToLocation(response) - { - if (response.error) { - InspectorTest.log("Failed to execute continueToLocation " + JSON.stringify(response.error)); - InspectorTest.completeTest(); - } - } - } - function handleDebuggerPausedTwo(messageObject) - { - InspectorTest.log("Paused after continueToLocation"); - var actualLineNumber = messageObject.params.callFrames[0].location.lineNumber; - - InspectorTest.log("Stopped on line " + actualLineNumber + ", expected " + expectedLineNumber + ", requested " + lineNumber + ", (0-based numbers)."); - - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedUnexpected; - - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "statementsExample.step" }, callbackStepEvaluate); - } - - function callbackStepEvaluate(response) - { - var resultValue = response.result.result.value; - InspectorTest.log("Control parameter 'step' calculation result: " + resultValue + ", expected: " + expectedResult); - InspectorTest.log(resultValue == expectedResult ? "SUCCESS" : "FAIL"); - InspectorTest.sendCommand("Debugger.resume", { }); - next(); - } - - function handleDebuggerPausedUnexpected(messageObject) - { - InspectorTest.log("Unexpected debugger pause"); - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.js new file mode 100644 index 0000000..466535a --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/continueToLocation.js
@@ -0,0 +1,79 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + function statementsExample() + { + var self = arguments.callee; + + debugger; + + self.step = 1; + + self.step = 2; + + void [ + self.step = 3, + self.step = 4, + self.step = 5, + self.step = 6 + ]; + + self.step = 7; + } + + var scenarios = [ + // requested line number, expected control parameter 'step', expected line number + [ 8, 1, 8 ], + [ 8, 1, 8 ], + [ 12, 6, 17 ], + [ 13, 6, 17 ], + [ 17, 6, 17 ], + [ 17, 6, 17 ], + ]; + + dp.Debugger.enable(); + var functionResponse = await dp.Runtime.evaluate({expression: statementsExample.toString() + '; statementsExample'}); + var functionObjectId = functionResponse.result.result.objectId; + + var detailsResponse = await dp.Runtime.getProperties({objectId: functionObjectId}); + var scriptId; + for (var prop of detailsResponse.result.internalProperties) { + if (prop.name === '[[FunctionLocation]]') + scriptId = prop.value.value.scriptId; + } + + for (var scenario of scenarios) { + var lineNumber = scenario[0]; + var expectedResult = scenario[1]; + var expectedLineNumber = scenario[2]; + dp.Runtime.evaluate({expression: 'setTimeout(statementsExample, 0)' }); + await dp.Debugger.oncePaused(); + testRunner.log('Paused on debugger statement'); + + var continueToLocationResponse = await dp.Debugger.continueToLocation({location: {scriptId, lineNumber, columnNumber: 0}}); + if (continueToLocationResponse.error) { + testRunner.log('Failed to execute continueToLocation ' + JSON.stringify(continueToLocationResponse.error)); + testRunner.completeTest(); + return; + } + + var messageObject = await dp.Debugger.oncePaused(); + testRunner.log('Paused after continueToLocation'); + var actualLineNumber = messageObject.params.callFrames[0].location.lineNumber; + testRunner.log('Stopped on line ' + actualLineNumber + ', expected ' + expectedLineNumber + ', requested ' + lineNumber + ', (0-based numbers).'); + + dp.Debugger.onPaused(handleDebuggerPausedUnexpected); + var resultValue = (await dp.Runtime.evaluate({expression: 'statementsExample.step' })).result.result.value; + testRunner.log(`Control parameter 'step' calculation result: ${resultValue}, expected: ${expectedResult}`); + testRunner.log(resultValue == expectedResult ? 'SUCCESS' : 'FAIL'); + dp.Debugger.resume(); + dp.Debugger.offPaused(handleDebuggerPausedUnexpected); + + function handleDebuggerPausedUnexpected() { + testRunner.log('Unexpected debugger pause'); + testRunner.completeTest(); + } + } + + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.html deleted file mode 100644 index 5bacfae..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.html +++ /dev/null
@@ -1,39 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function foo() -{ - return 239; -} - -function test() -{ - InspectorTest.sendCommandOrDie("Debugger.enable", {}); - InspectorTest.eventHandler["Debugger.paused"] = debuggerPaused; - InspectorTest.sendCommandOrDie("Runtime.evaluate", { "expression": "(function boo() { setTimeout(foo, 0); debugger; })()" }); - - var actions = [ "stepInto", "stepInto", "stepInto" ]; - function debuggerPaused(result) - { - InspectorTest.log("Stack trace:"); - for (var callFrame of result.params.callFrames) - InspectorTest.log(callFrame.functionName + ':' + callFrame.location.lineNumber + ":" + callFrame.location.columnNumber); - InspectorTest.log(""); - - var action = actions.shift(); - if (!action) { - InspectorTest.sendCommandOrDie("Debugger.resume", {}, () => InspectorTest.completeTest()); - return; - } - InspectorTest.log("Perform " + action); - InspectorTest.sendCommandOrDie("Debugger." + action, {}); - } -} -</script> -</head> -<body onLoad="runTest();"> -Check that stepInto at then end of the script go to next user script instead InjectedScriptSource.js. -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.js new file mode 100644 index 0000000..64fd2d3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-doesnt-step-into-injected-script.js
@@ -0,0 +1,38 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank('Check that stepInto at then end of the script go to next user script instead InjectedScriptSource.js.'); + + function logStack(event) { + testRunner.log('Stack trace:'); + for (var callFrame of event.params.callFrames) + testRunner.log(callFrame.functionName + ':' + callFrame.location.lineNumber + ':' + callFrame.location.columnNumber); + testRunner.log(''); + } + + dp.Debugger.enable(); + await session.evaluate(` + + + + + + function foo() { + return 239; + }`); + dp.Runtime.evaluate({expression: '(function boo() { setTimeout(foo, 0); debugger; })()' }); + + logStack(await dp.Debugger.oncePaused()); + testRunner.log('Perform stepInto'); + dp.Debugger.stepInto(); + + logStack(await dp.Debugger.oncePaused()); + testRunner.log('Perform stepInto'); + dp.Debugger.stepInto(); + + logStack(await dp.Debugger.oncePaused()); + testRunner.log('Perform stepInto'); + dp.Debugger.stepInto(); + + logStack(await dp.Debugger.oncePaused()); + await dp.Debugger.resume(); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page-expected.txt index 81e00ce..aa6355b6 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page-expected.txt
@@ -1,3 +1,4 @@ + Started worker Paused on 'debugger;' Worker created
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.html deleted file mode 100644 index ddae332..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.html +++ /dev/null
@@ -1,80 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -var worker; - -function testFunction() -{ - debugger; -} - -function startWorkerAndRunTest() -{ - worker = new Worker("resources/dedicated-worker.js"); - worker.onmessage = function(event) { }; - worker.postMessage(1); - log("Started worker"); - runTest(); -} - -function test() -{ - var workerId; - var workerRequestId = 1; - - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId }) - }); - return workerRequestId++; - } - - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedInTestFunction; - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "testFunction()" }); - - function handleDebuggerPausedInTestFunction(messageObject) - { - InspectorTest.log("Paused on 'debugger;'"); - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: false}, didEnableWorkerDebugging); - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - - var savedWorkerRequestId = -1; - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - InspectorTest.log("didConnectToWorker"); - savedWorkerRequestId = sendCommandToWorker("Runtime.evaluate", { "expression": "1+1"}); - } - - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["id"] === savedWorkerRequestId) { - var value = message["result"]["result"]["value"]; - InspectorTest.log("Successfully evaluated, result: " + value); - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="startWorkerAndRunTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.js new file mode 100644 index 0000000..76ede5e --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-evaluate-in-worker-while-pause-in-page.js
@@ -0,0 +1,39 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: 'debugger;' }); + await dp.Debugger.oncePaused(); + testRunner.log(`Paused on 'debugger;'`); + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); + + var messageObject = await dp.Target.onceAttachedToTarget(); + var workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + testRunner.log('didConnectToWorker'); + + var savedWorkerRequestId = sendCommandToWorker('Runtime.evaluate', {expression: '1+1'}); + dp.Target.onReceivedMessageFromTarget(messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.id === savedWorkerRequestId) { + var value = message.result.result.value; + testRunner.log('Successfully evaluated, result: ' + value); + testRunner.completeTest(); + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-expected.txt index e412394..bd6d733 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-expected.txt
@@ -1,3 +1,4 @@ + Started worker Worker created didConnectToWorker
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop-expected.txt index ab9d5310a..0b8048b 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop-expected.txt
@@ -1,3 +1,4 @@ + Started worker Worker created didConnectToWorker
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.html deleted file mode 100644 index 5d3c19d..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.html +++ /dev/null
@@ -1,86 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -var worker; -function startWorkerAndRunTest() -{ - worker = new Worker("resources/dedicated-worker-loop.js"); - worker.onmessage = function(event) - { - if (event.data === "WorkerMessageReceived") - evaluateInFrontend("InspectorTest.workerMessageReceived()"); - }; - log("Started worker"); - runTest(); -} - -function test() -{ - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId }) - }); - return workerRequestId++; - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: false}, didEnableWorkerDebugging); - - var evaluateRequestId = -1; - var debuggerEnableRequestId = -1; - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - InspectorTest.log("didConnectToWorker"); - // Enable debugger so that V8 can interrupt and handle inspector commands while there is a script running in a tight loop. - debuggerEnableRequestId = sendCommandToWorker("Debugger.enable", {}); - } - - InspectorTest.workerMessageReceived = function() - { - evaluateRequestId = sendCommandToWorker("Runtime.evaluate", { "expression": "message_id > 1"}); - } - - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["id"] === debuggerEnableRequestId) { - InspectorTest.log("Did enable debugger"); - // Start tight loop in the worker. - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "worker.postMessage(1)" }, didPostMessageToWorker); - function didPostMessageToWorker() - { - InspectorTest.log("Did post message to worker"); - } - } - if (message["id"] === evaluateRequestId) { - var value = message["result"]["result"]["value"]; - if (value === true) - InspectorTest.log("SUCCESS: evaluated, result: " + value); - else - InspectorTest.log("FAIL: evaluated, result: " + value); - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="startWorkerAndRunTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.js new file mode 100644 index 0000000..ec3325f --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker-loop.js
@@ -0,0 +1,54 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker-loop.js')}'); + var resolve; + window.workerMessageReceivedPromise = new Promise(f => resolve = f); + window.worker.onmessage = function(event) { + if (event.data === 'WorkerMessageReceived') + resolve(); + }; + `); + testRunner.log('Started worker'); + + var workerId; + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); + + var debuggerEnableRequestId = -1; + var evaluateRequestId = -1; + + dp.Target.onReceivedMessageFromTarget(async messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.id === debuggerEnableRequestId) { + testRunner.log('Did enable debugger'); + // Start tight loop in the worker. + await dp.Runtime.evaluate({expression: 'worker.postMessage(1)' }); + testRunner.log('Did post message to worker'); + } + if (message.id === evaluateRequestId) { + var value = message.result.result.value; + if (value === true) + testRunner.log('SUCCESS: evaluated, result: ' + value); + else + testRunner.log('FAIL: evaluated, result: ' + value); + testRunner.completeTest(); + } + }); + + workerId = (await dp.Target.onceAttachedToTarget()).params.targetInfo.targetId; + testRunner.log('Worker created'); + testRunner.log('didConnectToWorker'); + // Enable debugger so that V8 can interrupt and handle inspector commands while there is a script running in a tight loop. + debuggerEnableRequestId = sendCommandToWorker('Debugger.enable', {}); + + await session.evaluateAsync('workerMessageReceivedPromise'); + evaluateRequestId = sendCommandToWorker('Runtime.evaluate', { 'expression': 'message_id > 1'}); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.html deleted file mode 100644 index 1d33b8d..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.html +++ /dev/null
@@ -1,69 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - - -var worker; - -function startWorkerAndRunTest() -{ - worker = new Worker("resources/dedicated-worker.js"); - worker.onmessage = function(event) { }; - worker.postMessage(1); - log("Started worker"); - runTest(); -} - - -function test() -{ - - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId++ }) - }); - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: false}, didEnableWorkerDebugging); - - - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - InspectorTest.log("didConnectToWorker"); - sendCommandToWorker("Debugger.enable", {}); - sendCommandToWorker("Debugger.pause", {}); - } - - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["method"] === "Debugger.paused") { - InspectorTest.log("SUCCESS: Worker paused"); - sendCommandToWorker("Debugger.disable", {}); - InspectorTest.completeTest(); - } - } - -} -</script> -</head> -<body onLoad="startWorkerAndRunTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.js new file mode 100644 index 0000000..90542a2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-dedicated-worker.js
@@ -0,0 +1,35 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); + + var messageObject = await dp.Target.onceAttachedToTarget(); + var workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + testRunner.log('didConnectToWorker'); + sendCommandToWorker('Debugger.enable', {}); + sendCommandToWorker('Debugger.pause', {}); + + dp.Target.onReceivedMessageFromTarget(messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.method === 'Debugger.paused') { + testRunner.log('SUCCESS: Worker paused'); + sendCommandToWorker('Debugger.disable', {}); + testRunner.completeTest(); + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop-expected.txt index 938e588..a769f3e 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop-expected.txt
@@ -1,4 +1,6 @@ + didEval didFireTimer SUCCESS: Paused +SUCCESS: Resumed
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.html deleted file mode 100644 index fac7b51..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.html +++ /dev/null
@@ -1,62 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function testFunction() -{ - setTimeout(hotFunction, 0); -} - -var terminated = false; -function hotFunction() { - evaluateInFrontend("InspectorTest.didFireTimer()"); - - var message_id = 1; - var ts = Date.now(); - while (!terminated) { - // Without this try/catch v8 will optimize the function and break will not work. - try { - if (Date.now() - ts > 1000) { - ts = Date.now(); - console.error("Message #" + message_id++); - } - } catch (e) { - } - } -} - -function test() -{ - InspectorTest.sendCommand("Inspector.enable", {}); - InspectorTest.sendCommand("Debugger.enable", {}, didEnableDebugger); - function didEnableDebugger() - { - // Start tight loop in page. - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "testFunction()" }, didEval); - function didEval() - { - InspectorTest.log("didEval"); - } - } - - InspectorTest.didFireTimer = function() - { - InspectorTest.log("didFireTimer"); - InspectorTest.sendCommand("Debugger.pause", { }); - } - - InspectorTest.eventHandler["Debugger.paused"] = function(messageObject) - { - var message = messageObject["params"]["message"]; - InspectorTest.log("SUCCESS: Paused"); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "terminated = true;" }); - InspectorTest.sendCommand("Debugger.resume", { }); - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.js new file mode 100644 index 0000000..f56dc97e --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-pause-in-tight-loop.js
@@ -0,0 +1,41 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await dp.Runtime.enable(); + await dp.Debugger.enable(); + + // Start tight loop in page. + session.evaluate(` + var terminated = false; + function hotFunction() { + console.log('hi'); + var message_id = 1; + var ts = Date.now(); + while (!terminated) { + // Without this try/catch v8 will optimize the function and break will not work. + try { + if (Date.now() - ts > 1000) { + ts = Date.now(); + console.error('Message #' + message_id++); + } + } catch (e) { + } + } + } + setTimeout(hotFunction, 0); + `); + testRunner.log('didEval'); + + await dp.Runtime.onceConsoleAPICalled(); + testRunner.log('didFireTimer'); + + dp.Debugger.pause(); + await dp.Debugger.oncePaused(); + testRunner.log('SUCCESS: Paused'); + + dp.Runtime.evaluate({expression: 'terminated = true;' }); + dp.Debugger.resume(); + await dp.Debugger.onceResumed(); + testRunner.log('SUCCESS: Resumed'); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name-expected.txt index 4b7e1a3..f1a2108 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name-expected.txt
@@ -1,3 +1,4 @@ + { result : [ [0] : {
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.html deleted file mode 100644 index a0357b3..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.html +++ /dev/null
@@ -1,50 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function testFunction() -{ - for (var a of [1]) { - ++a; - debugger; - } -} - -function test() -{ - InspectorTest.sendCommandOrDie("Debugger.enable", {}); - InspectorTest.eventHandler["Debugger.paused"] = dumpScopeOnPause; - InspectorTest.sendCommandOrDie("Runtime.evaluate", { "expression": "testFunction()" }); - - var waitScopeObjects = 0; - function dumpScopeOnPause(message) - { - var scopeChain = message.params.callFrames[0].scopeChain; - var localScopeObjectIds = []; - for (var scope of scopeChain) { - if (scope.type === "local") - localScopeObjectIds.push(scope.object.objectId); - } - waitScopeObjects = localScopeObjectIds.length; - if (!waitScopeObjects) { - InspectorTest.completeTest(); - } else { - for (var objectId of localScopeObjectIds) - InspectorTest.sendCommandOrDie("Runtime.getProperties", { "objectId" : objectId }, dumpProperties); - } - } - - function dumpProperties(message) - { - InspectorTest.logObject(message); - --waitScopeObjects; - if (!waitScopeObjects) - InspectorTest.sendCommandOrDie("Debugger.resume", {}, () => InspectorTest.completeTest()); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.js new file mode 100644 index 0000000..a9e8871 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-scope-skip-variables-with-empty-name.js
@@ -0,0 +1,28 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: ` + function testFunction() { + for (var a of [1]) { + ++a; + debugger; + } + } + testFunction(); + `}); + + var message = await dp.Debugger.oncePaused(); + var scopeChain = message.params.callFrames[0].scopeChain; + var localScopeObjectIds = []; + for (var scope of scopeChain) { + if (scope.type === 'local') + localScopeObjectIds.push(scope.object.objectId); + } + + for (var objectId of localScopeObjectIds) + testRunner.logObject((await dp.Runtime.getProperties({objectId})).result); + + await dp.Debugger.resume(); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns-expected.txt index 9b5bec7..287712b 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns-expected.txt
@@ -1,25 +1,26 @@ + Pattern parser error: Uncaught SyntaxError: Invalid regular expression: /(foo([)/: Unterminated character class Paused in (...):1 Paused in (...):1 Paused in -qwe:21 -baz:29 +qwe:4 +baz:4 (...):1 Paused in -bar:7 -foo:13 -qwe:21 -baz:29 +bar:4 +foo:4 +qwe:4 +baz:4 (...):1 Paused in -qwe:22 -baz:29 +qwe:5 +baz:4 (...):1 Paused in -qwe:23 -baz:29 +qwe:6 +baz:4 (...):1 Paused in (...):1
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.html deleted file mode 100644 index 07ec913271..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.html +++ /dev/null
@@ -1,67 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> -function bar() -{ - return 42; -} -</script> -<script> -function foo() -{ - var a = bar(); - return a + 1; -} -//# sourceURL=foo.js -</script> -<script> -function qwe() -{ - var a = foo(); - return a + 1; -} -//# sourceURL=qwe.js -</script> -<script> -function baz() -{ - var a = qwe(); - return a + 1; -} -//# sourceURL=baz.js -</script> -<script> -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.sendCommand("Debugger.setBlackboxPatterns", { patterns: [ "foo([" ] }, dumpError); - - function dumpError(message) - { - InspectorTest.log(message.error.message); - InspectorTest.eventHandler["Debugger.paused"] = dumpStackAndRunNextCommand; - InspectorTest.sendCommandOrDie("Debugger.setBlackboxPatterns", { patterns: [ "baz\.js", "foo\.js" ] }); - InspectorTest.sendCommandOrDie("Runtime.evaluate", { "expression": "debugger;baz()" }); - } - - var commands = [ "stepInto", "stepInto", "stepInto", "stepOut", "stepInto", "stepInto" ]; - function dumpStackAndRunNextCommand(message) - { - InspectorTest.log("Paused in"); - var callFrames = message.params.callFrames; - for (var callFrame of callFrames) - InspectorTest.log((callFrame.functionName || "(...)") + ":" + (callFrame.location.lineNumber + 1)); - var command = commands.shift(); - if (!command) { - InspectorTest.completeTest(); - return; - } - InspectorTest.sendCommandOrDie("Debugger." + command, {}); - } - -} -</script> -</head> -<body onLoad="runTest();"></body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.js new file mode 100644 index 0000000..65cc402 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setBlackboxPatterns.js
@@ -0,0 +1,74 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await session.evaluate(` + function bar() + { + return 42; + } + `); + + await session.evaluate(` + function foo() + { + var a = bar(); + return a + 1; + } + //# sourceURL=foo.js + `); + + await session.evaluate(` + function qwe() + { + var a = foo(); + return a + 1; + } + //# sourceURL=qwe.js + `); + + await session.evaluate(` + function baz() + { + var a = qwe(); + return a + 1; + } + //# sourceURL=baz.js + `); + + function logStack(message) { + testRunner.log('Paused in'); + var callFrames = message.params.callFrames; + for (var callFrame of callFrames) + testRunner.log((callFrame.functionName || '(...)') + ':' + (callFrame.location.lineNumber + 1)); + } + + dp.Debugger.enable(); + var message = await dp.Debugger.setBlackboxPatterns({patterns: ['foo([']}); + testRunner.log(message.error.message); + + dp.Debugger.setBlackboxPatterns({patterns: ['baz\.js', 'foo\.js']}); + dp.Runtime.evaluate({expression: 'debugger;baz()' }); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepInto(); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepInto(); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepInto(); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepOut(); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepInto(); + logStack(await dp.Debugger.oncePaused()); + + dp.Debugger.stepInto(); + logStack(await dp.Debugger.oncePaused()); + + await dp.Debugger.resume(); + testRunner.completeTest(); +}) +
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint-expected.txt index 3b141a7..77c15196 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint-expected.txt
@@ -1,3 +1,4 @@ + PASS: Debugger was enabled Error on attempt to set event listener breakpoint when DOM is disabled: undefined PASS: DOM was enabled
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.html deleted file mode 100644 index cafebf4f..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.html +++ /dev/null
@@ -1,69 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}, setEventListenerBreakpointWhenDOMDisabled); - - function finishIfError(message) - { - if (message.result) - return; - InspectorTest.log("FAIL: " + JSON.stringify(message)); - InspectorTest.completeTest(); - } - - function setEventListenerBreakpointWhenDOMDisabled(message) - { - finishIfError(message); - InspectorTest.log("PASS: Debugger was enabled"); - InspectorTest.sendCommand("DOMDebugger.setEventListenerBreakpoint", {'eventName':'click'}, enableDOMAgent); - } - - function enableDOMAgent(message) - { - InspectorTest.log("Error on attempt to set event listener breakpoint when DOM is disabled: " + JSON.stringify(message.error)); - InspectorTest.sendCommand("DOM.enable", {}, setEventListenerBreakpoint); - } - - function setEventListenerBreakpoint(message) - { - finishIfError(message); - InspectorTest.log("PASS: DOM was enabled"); - InspectorTest.sendCommand("DOMDebugger.setEventListenerBreakpoint", {'eventName':'click'}, disableDOMAgent); - } - - - function disableDOMAgent(message) - { - finishIfError(message); - InspectorTest.log("PASS: Listener was set."); - InspectorTest.sendCommand("DOM.disable", {}, disableDOMAgent2); - } - - function disableDOMAgent2(message) - { - finishIfError(message); - InspectorTest.log("PASS: DOM agent was disabled successfully."); - InspectorTest.sendCommand("DOM.disable", {}, finish); - } - - function finish(message) - { - if (!message.error) { - InspectorTest.log("FAIL: we expected an error but it wasn't happen."); - InspectorTest.completeTest(); - return; - } - - InspectorTest.log("PASS: The second attempt to disable DOM agent failed as expected."); - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.js new file mode 100644 index 0000000..15ff82f --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setEventListenerBreakpoint.js
@@ -0,0 +1,32 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + function finishIfError(message) { + if (message.result) + return; + testRunner.log('FAIL: ' + JSON.stringify(message)); + testRunner.completeTest(); + } + + finishIfError(await dp.Debugger.enable()); + testRunner.log('PASS: Debugger was enabled'); + + var errorResponse = dp.DOMDebugger.setEventListenerBreakpoint({eventName: 'click'}); + testRunner.log('Error on attempt to set event listener breakpoint when DOM is disabled: ' + JSON.stringify(errorResponse.error)); + + finishIfError(await dp.DOM.enable()); + testRunner.log('PASS: DOM was enabled'); + + finishIfError(await dp.DOMDebugger.setEventListenerBreakpoint({eventName:'click'})); + testRunner.log('PASS: Listener was set.'); + + finishIfError(await dp.DOM.disable()); + testRunner.log('PASS: DOM agent was disabled successfully.'); + + var message = await dp.DOM.disable(); + if (!message.error) + testRunner.log(`FAIL: we expected an error but it wasn't happen.`); + else + testRunner.log('PASS: The second attempt to disable DOM agent failed as expected.'); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop-expected.txt index 1eb72fb6..c4ac494d 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop-expected.txt
@@ -1,3 +1,4 @@ + Started worker Worker created didConnectToWorker
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.html deleted file mode 100644 index fd20f46..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.html +++ /dev/null
@@ -1,78 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -var worker; -function startWorkerAndRunTest() -{ - worker = new Worker("resources/dedicated-worker-string-setTimeout.js"); - log("Started worker"); - runTest(); -} - -function test() -{ - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId }) - }); - return workerRequestId++; - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: false}, didEnableWorkerDebugging); - - var debuggerEnableRequestId = -1; - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - InspectorTest.log("didConnectToWorker"); - debuggerEnableRequestId = sendCommandToWorker("Debugger.enable", {}); - } - - var postMessageToWorker = false; - - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["id"] === debuggerEnableRequestId) { - InspectorTest.log("Did enable debugger"); - // Start setTimeout. - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "worker.postMessage(1)" }, didPostMessageToWorker); - function didPostMessageToWorker() - { - postMessageToWorker = true; - InspectorTest.log("Did post message to worker"); - } - } - - if (postMessageToWorker && message["method"] === "Debugger.scriptParsed") { - var sourceUrl = message["params"]["url"]; - if (!sourceUrl) - InspectorTest.log("SUCCESS: script created from string parameter of setTimeout has no url"); - else - InspectorTest.log("FAIL: script created from string parameter of setTimeout has url " + sourceUrl); - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="startWorkerAndRunTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.js new file mode 100644 index 0000000..7133bb2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-setTimeout-sourceUrl-dedicated-worker-loop.js
@@ -0,0 +1,47 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker-string-setTimeout.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var workerId; + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); + + var messageObject = await dp.Target.onceAttachedToTarget(); + workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + testRunner.log('didConnectToWorker'); + + var debuggerEnableRequestId = sendCommandToWorker('Debugger.enable', {}); + var postMessageToWorker = false; + dp.Target.onReceivedMessageFromTarget(async messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.id === debuggerEnableRequestId) { + testRunner.log('Did enable debugger'); + // Start setTimeout. + await dp.Runtime.evaluate({expression: 'worker.postMessage(1)'}); + postMessageToWorker = true; + testRunner.log('Did post message to worker'); + } + + if (postMessageToWorker && message.method === 'Debugger.scriptParsed') { + var sourceUrl = message.params.url; + if (!sourceUrl) + testRunner.log('SUCCESS: script created from string parameter of setTimeout has no url'); + else + testRunner.log('FAIL: script created from string parameter of setTimeout has url ' + sourceUrl); + testRunner.completeTest(); + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker-expected.txt index ecdb5d20..776e622 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker-expected.txt
@@ -1,5 +1,4 @@ Tests that dedicated worker won't crash on attempt to step into.Bug 232392. - Started worker Worker created SUCCESS: Worker paused
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html deleted file mode 100644 index 6822980..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html +++ /dev/null
@@ -1,73 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> -var worker; - -function startWorker() -{ - worker = new Worker("resources/dedicated-worker-step-into.js"); - worker.onmessage = function(event) { }; - worker.postMessage(1); - log("Started worker"); -} - - -function test() -{ - - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId++ }) - }); - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: true}, didEnableWorkerDebugging); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "startWorker()" }); - - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - sendCommandToWorker("Debugger.enable", {}); - sendCommandToWorker("Runtime.runIfWaitingForDebugger", {}); - } - - var pauseCount = 0; - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["method"] === "Debugger.paused") { - InspectorTest.log("SUCCESS: Worker paused"); - if (++pauseCount === 1) { - InspectorTest.log("Stepping into..."); - sendCommandToWorker("Debugger.stepInto", {}); - } else { - sendCommandToWorker("Debugger.disable", {}); - InspectorTest.completeTest(); - } - } - } - -} -</script> -</head> -<body onLoad="runTest();"> -<p>Tests that dedicated worker won't crash on attempt to step into.<a href="https://code.google.com/p/chromium/issues/detail?id=232392">Bug 232392.</a> -</p> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.js new file mode 100644 index 0000000..bfb43c7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.js
@@ -0,0 +1,41 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(`Tests that dedicated worker won't crash on attempt to step into.Bug 232392.`); + + var workerId; + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true}); + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker-step-into.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var messageObject = await dp.Target.onceAttachedToTarget(); + workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + + sendCommandToWorker('Debugger.enable', {}); + sendCommandToWorker('Runtime.runIfWaitingForDebugger', {}); + + var pauseCount = 0; + dp.Target.onReceivedMessageFromTarget(async messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.method === 'Debugger.paused') { + testRunner.log('SUCCESS: Worker paused'); + if (++pauseCount === 1) { + testRunner.log('Stepping into...'); + sendCommandToWorker('Debugger.stepInto', {}); + } else { + sendCommandToWorker('Debugger.disable', {}); + testRunner.completeTest(); + } + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.html deleted file mode 100644 index 3919a0f..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.html +++ /dev/null
@@ -1,75 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - - -var worker; - -function startWorkerAndRunTest() -{ - worker = new Worker("resources/dedicated-worker.js"); - worker.onmessage = function(event) { }; - worker.postMessage(1); - log("Started worker"); - runTest(); -} - - -function test() -{ - - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": workerRequestId++ }) - }); - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: false}, didEnableWorkerDebugging); - - - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - InspectorTest.log("didConnectToWorker"); - sendCommandToWorker("Debugger.enable", {}); - sendCommandToWorker("Debugger.pause", {}); - } - - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["method"] === "Debugger.paused") { - InspectorTest.log("Worker paused"); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "worker.terminate()" }, didTerminateWorker); - } - } - - function didTerminateWorker(messageObject) - { - InspectorTest.log("SUCCESS: Did terminate paused worker"); - InspectorTest.completeTest(); - } - -} -</script> -</head> -<body onLoad="startWorkerAndRunTest();">Test that inspected page won't crash if inspected worker is terminated while it is paused. Test passes if it doesn't crash. -<a href="https://bugs.webkit.org/show_bug.cgi?id=101065">Bug 101065.</a> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.js new file mode 100644 index 0000000..9c7bf596 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-terminate-dedicated-worker-while-paused.js
@@ -0,0 +1,37 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank( + `Test that inspected page won't crash if inspected worker is terminated while it is paused. Test passes if it doesn't crash. Bug 101065.`); + + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: false}); + + var messageObject = await dp.Target.onceAttachedToTarget(); + var workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + testRunner.log('didConnectToWorker'); + sendCommandToWorker('Debugger.enable', {}); + sendCommandToWorker('Debugger.pause', {}); + + dp.Target.onReceivedMessageFromTarget(async messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.method === 'Debugger.paused') { + testRunner.log('Worker paused'); + await dp.Runtime.evaluate({expression: 'worker.terminate()' }); + testRunner.log('SUCCESS: Did terminate paused worker'); + testRunner.completeTest(); + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners-expected.txt index c2d3373..231a947 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners-expected.txt
@@ -1,3 +1,4 @@ + Event listeners of window type:click useCapture:true @@ -15,14 +16,6 @@ handler.className:Function handler.description:function hoverHandler(event) { console.log("hover - button - bubbling"); } - type:load - useCapture:false - lineNumber:164 - columnNumber:18 - handler.type:function - handler.className:Function - handler.description:function onload(event) { runTest();} - type:scroll useCapture:false lineNumber:1 @@ -59,8 +52,8 @@ type:load useCapture:false - lineNumber:162 - columnNumber:33 + lineNumber:0 + columnNumber:38 handler.type:function handler.className:Function handler.description:function onload(event) { return 42;}
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.html deleted file mode 100644 index 856dfc7..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.html +++ /dev/null
@@ -1,167 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function test() -{ - // A general-purpose engine for sending a sequence of protocol commands. - // The clients provide requests and response handlers, while the engine catches - // errors and makes sure that once there's nothing to do completeTest() is called. - // @param step is an object with command, params and callback fields. - function runRequestSeries(step) - { - processStep(step); - - function processStep(s) - { - try { - processStepOrFail(s); - } catch (e) { - InspectorTest.log(e.stack); - InspectorTest.completeTest(); - } - } - - function processStepOrFail(s) - { - if (!s) { - InspectorTest.completeTest(); - return; - } - if (!s.command) { - // A simple loopback step. - var next = s.callback(); - processStep(next); - return; - } - - var innerCallback = function(response) - { - if ("error" in response) { - InspectorTest.log(response.error.message); - InspectorTest.completeTest(); - return; - } - var next; - try { - next = s.callback(response.result); - } catch (e) { - InspectorTest.log(e.stack); - InspectorTest.completeTest(); - return; - } - processStep(next); - } - InspectorTest.sendCommand(s.command, s.params, innerCallback); - } - } - - runRequestSeries({ callback: callbackStartWindow }); - - function callbackStartWindow() - { - var expression = "(function(){\n\ - window.addEventListener('scroll', function(){ consol.log(42) }, false);\n\ - window.addEventListener('scroll', function(){ consol.log(42) }, false);\n\ - function clickHandler(event) { console.log('click - button - bubbling (registered before attribute)'); }\n\ - window.addEventListener(\"click\", clickHandler, true);\n\ - window.addEventListener(\"hover\", function hoverHandler(event) { console.log(\"hover - button - bubbling\"); }, true);\n\ - return window;\n\ - })()"; - return { command: "Runtime.evaluate", params: {expression: expression, objectGroup: "event-listeners-test"}, callback: callbackEvalWindow }; - } - function callbackEvalWindow(result) - { - var id = result.result.objectId; - if (id === undefined) - throw new Error("objectId is expected"); - return { - command: "DOMDebugger.getEventListeners", params: {objectId: id}, callback: callbackListenersWindow - }; - } - function callbackListenersWindow(result) - { - logGetListenersResult("window", result); - return {callback: calbackStartDivWithListeners}; - } - - function calbackStartDivWithListeners() - { - var expression = "(function(){\n\ - var div = document.getElementById(\"listeners1\");\n\ - function clickHandler(event) { console.log('click - button - bubbling (registered before attribute)'); }\n\ - div.addEventListener(\"click\", clickHandler, true);\n\ - div.addEventListener(\"hover\", function hoverHandler(event) { console.log(\"hover - button - bubbling\"); }, true);\n\ - return div;\n\ - })()"; - return { command: "Runtime.evaluate", params: {expression: expression, objectGroup: "event-listeners-test"}, callback: callbackEvalDivWithListeners }; - } - function callbackEvalDivWithListeners(result) - { - var id = result.result.objectId; - if (id === undefined) - throw new Error("objectId is expected"); - return { - command: "DOMDebugger.getEventListeners", params: {objectId: id}, callback: callbackListenersDivWithListeners - }; - } - function callbackListenersDivWithListeners(result) - { - logGetListenersResult("div#listeners1", result); - return {callback: calbackStartDivWithoutListeners}; - } - - function calbackStartDivWithoutListeners() - { - var expression = "(function(){\n\ - return document.getElementById(\"listeners2\");\n\ - })()"; - return { command: "Runtime.evaluate", params: {expression: expression, objectGroup: "event-listeners-test"}, callback: callbackEvalDivWithoutListeners }; - } - function callbackEvalDivWithoutListeners(result) - { - var id = result.result.objectId; - if (id === undefined) - throw new Error("objectId is expected"); - return { - command: "DOMDebugger.getEventListeners", params: {objectId: id}, callback: callbackListenersDivWithoutListeners - }; - } - function callbackListenersDivWithoutListeners(result) - { - logGetListenersResult("div#listeners2", result); - } - - function logGetListenersResult(title, protocolResult) - { - InspectorTest.log("Event listeners of " + title); - var listenersArray = protocolResult.listeners; - listenersArray.sort(TypedThingComparator); - for (var i = 0; i < listenersArray.length; i++) { - var l = listenersArray[i]; - InspectorTest.log(" type:" + l.type); - InspectorTest.log(" useCapture:" + l.useCapture); - InspectorTest.log(" lineNumber:" + l.lineNumber); - InspectorTest.log(" columnNumber:" + l.columnNumber); - if (l.handler) { - InspectorTest.log(" handler.type:" + l.handler.type); - InspectorTest.log(" handler.className:" + l.handler.className); - InspectorTest.log(" handler.description:" + l.handler.description.replace(/(\r\n|\n|\r)/gm,"")); - } - InspectorTest.log(""); - } - InspectorTest.log(""); - function TypedThingComparator(o1, o2) - { - return o1.type === o2.type ? 0 : (o1.type < o2.type ? -1 : 1); - } - } -} -</script> -</head> -<div id="listeners1" onload="return 42;"></div> -<div id="listeners2"></div> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.js new file mode 100644 index 0000000..3a7b1dd2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-getEventListeners.js
@@ -0,0 +1,57 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startHTML(` + <div id='listeners1' onload='return 42;'></div> + <div id='listeners2'></div> + `, ``); + + function logGetListenersResult(title, response) { + testRunner.log('Event listeners of ' + title); + var listenersArray = response.result.listeners; + listenersArray.sort((o1, o2) => o1.type === o2.type ? 0 : (o1.type < o2.type ? -1 : 1)); + for (var l of listenersArray) { + testRunner.log(' type:' + l.type); + testRunner.log(' useCapture:' + l.useCapture); + testRunner.log(' lineNumber:' + l.lineNumber); + testRunner.log(' columnNumber:' + l.columnNumber); + if (l.handler) { + testRunner.log(' handler.type:' + l.handler.type); + testRunner.log(' handler.className:' + l.handler.className); + testRunner.log(' handler.description:' + l.handler.description.replace(/(\r\n|\n|\r)/gm,'')); + } + testRunner.log(''); + } + testRunner.log(''); + } + + var objectId = (await dp.Runtime.evaluate({expression: + `(function(){ + window.addEventListener('scroll', function(){ consol.log(42) }, false); + window.addEventListener('scroll', function(){ consol.log(42) }, false); + function clickHandler(event) { console.log('click - button - bubbling (registered before attribute)'); } + window.addEventListener('click', clickHandler, true); + window.addEventListener('hover', function hoverHandler(event) { console.log("hover - button - bubbling"); }, true); + return window; + })() + `, objectGroup: 'event-listeners-test'})).result.result.objectId; + logGetListenersResult('window', await dp.DOMDebugger.getEventListeners({objectId})); + + var objectId = (await dp.Runtime.evaluate({expression: + `(function(){ + var div = document.getElementById('listeners1'); + function clickHandler(event) { console.log('click - button - bubbling (registered before attribute)'); } + div.addEventListener('click', clickHandler, true); + div.addEventListener('hover', function hoverHandler(event) { console.log("hover - button - bubbling"); }, true); + return div; + })() + `, objectGroup: 'event-listeners-test'})).result.result.objectId; + logGetListenersResult('div#listeners1', await dp.DOMDebugger.getEventListeners({objectId})); + + var objectId = (await dp.Runtime.evaluate({expression: + `(function(){ + return document.getElementById('listeners2'); + })() + `, objectGroup: 'event-listeners-test'})).result.result.objectId; + logGetListenersResult('div#listeners2', await dp.DOMDebugger.getEventListeners({objectId})); + + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp-expected.txt index 0c0a485..a6902f5 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp-expected.txt
@@ -1,10 +1,4 @@ -CONSOLE ERROR: line 2: Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. -CONSOLE ERROR: line 4: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI='), or a nonce ('nonce-...') is required to enable inline execution. - -CONSOLE ERROR: line 5: Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. - -Button ------- blockedEventHandler
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.html deleted file mode 100644 index 1fb01011..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.html +++ /dev/null
@@ -1,10 +0,0 @@ -<html> -<head> -<meta http-equiv="Content-Security-Policy" content="script-src 'self';"> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script type="text/javascript" src="resources/script-blocked-by-csp.js"></script> -</head> -<body> -<button id="testButton" onclick="alert(1);">Button</button> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.js new file mode 100644 index 0000000..8f700db --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-script-blocked-by-csp.js
@@ -0,0 +1,55 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startHTML(` + <html> + <head> + <meta http-equiv='Content-Security-Policy' content="script-src 'self';"> + </head> + <body> + <button id='testButton' onclick='alert(1);'>Button</button> + </body> + </html> + `, ``); + + dp.Debugger.enable(); + dp.DOM.enable(); + dp.DOMDebugger.enable(); + dp.DOMDebugger.setInstrumentationBreakpoint({eventName: 'scriptBlockedByCSP'}); + + var expressions = [ + ` + document.getElementById('testButton').click(); + `, + + ` + var script = document.createElement('script'); + script.innerText = 'alert(1)'; + document.body.appendChild(script); + `, + + ` + var a = document.createElement('a'); + a.setAttribute('href', 'javascript:alert(1);'); + var dummy = 1; + document.body.appendChild(a); a.click(); + ` + ]; + var descriptions = [ + 'blockedEventHandler', + 'blockedScriptInjection', + 'blockedScriptUrl' + ]; + + for (var i = 0; i < expressions.length; i++) { + var funcName = descriptions[i]; + testRunner.log('\n-------\n' + funcName); + dp.Runtime.evaluate({expression: 'function ' + funcName + '() {' + expressions[i] + '}\n' + funcName + '()'}); + var messageObject = await dp.Debugger.oncePaused(); + var params = messageObject.params; + testRunner.log('Paused at: ' + params.callFrames[0].functionName + '@' + params.callFrames[0].location.lineNumber); + testRunner.log('Reason: ' + params.reason + '; Data:'); + testRunner.logObject(params.data); + await dp.Debugger.resume(); + } + + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML-expected.txt index a97b8e52..4dce98314 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML-expected.txt
@@ -1,3 +1,3 @@ -innerHTML + Paused on the innerHTML assignment: modifyHTML@:7
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.html deleted file mode 100644 index bb8c99d63..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.html +++ /dev/null
@@ -1,36 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function modifyHTML() -{ - document.getElementById("divUnderTest").innerHTML = "innerHTML"; -} - -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.sendCommand("DOM.enable", {}); - InspectorTest.sendCommand("DOMDebugger.enable", {}); - InspectorTest.sendCommand("DOMDebugger.setInstrumentationBreakpoint", {"eventName":"Element.setInnerHTML"}); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "modifyHTML()" }); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedOne; - - function handleDebuggerPausedOne(messageObject) - { - var callFrame = messageObject.params.callFrames[0]; - InspectorTest.log("Paused on the innerHTML assignment: " + callFrame.functionName + "@:" + callFrame.location.lineNumber); - InspectorTest.sendCommand("Debugger.resume", { }, didResume); - function didResume() - { - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="runTest();"> -<div id="divUnderTest"></div> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.js new file mode 100644 index 0000000..486242e --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/domdebugger-setInnerHTML.js
@@ -0,0 +1,25 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startHTML(` + <div id='divUnderTest'></div> + `, ``); + + dp.Debugger.enable(); + dp.DOM.enable(); + dp.DOMDebugger.enable(); + dp.DOMDebugger.setInstrumentationBreakpoint({eventName: 'Element.setInnerHTML'}); + dp.Runtime.evaluate({expression: ` + + + + + + (function modifyHTML() { + document.getElementById('divUnderTest').innerHTML = 'innerHTML'; + })() + ` }); + var messageObject = await dp.Debugger.oncePaused(); + var callFrame = messageObject.params.callFrames[0]; + testRunner.log('Paused on the innerHTML assignment: ' + callFrame.functionName + '@:' + callFrame.location.lineNumber); + await dp.Debugger.resume(); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause-expected.txt index 568693f..96cf4515 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause-expected.txt
@@ -1,3 +1,4 @@ + Paused on 'debugger;' PASS: message has not been dispatched yet. PASS: message has not been dispatched yet.
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.html deleted file mode 100644 index 7cb5fbc..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.html +++ /dev/null
@@ -1,72 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -var messageDispatched = false; -window.addEventListener("message", function(event) -{ - messageDispatched = true; - debugger; -}, true); - -function testFunction() -{ - window.postMessage("test", "*"); - debugger; -} - -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedInTestFunction; - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "testFunction()" }); - - function handleDebuggerPausedInTestFunction(messageObject) - { - InspectorTest.log("Paused on 'debugger;'"); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "messageDispatched" }, didEvaluateOnPause1); - } - - function didEvaluateOnPause1(messageObject) - { - var r = messageObject.result.result; - if (r.type === "boolean" && r.value === false) - InspectorTest.log("PASS: message has not been dispatched yet."); - else - InspectorTest.log("FAIL: unexpected response " + JSON.stringify(messageObject, null, 2)); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "messageDispatched" }, didEvaluateOnPause2); - } - - function didEvaluateOnPause2(messageObject) - { - var r = messageObject.result.result; - if (r.type === "boolean" && r.value === false) - InspectorTest.log("PASS: message has not been dispatched yet."); - else - InspectorTest.log("FAIL: unexpected response " + JSON.stringify(messageObject, null, 2)); - InspectorTest.sendCommand("Debugger.resume", { }, didResume); - } - - function didResume(messageObject) - { - InspectorTest.log("Resumed, now waiting for pause in the event listener..."); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPausedInEventListener; - } - - function handleDebuggerPausedInEventListener(messageObject) - { - InspectorTest.log("PASS: pasued in the event listener."); - InspectorTest.sendCommand("Debugger.resume", { }, didResume2); - } - - function didResume2(messageObject) - { - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.js new file mode 100644 index 0000000..6a2b7b1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/postMessage-on-pause.js
@@ -0,0 +1,42 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: ` + var messageDispatched = false; + window.addEventListener('message', event => { + messageDispatched = true; + debugger; + }, true); + + (function testFunction() { + window.postMessage('test', '*'); + debugger; + })() + `}); + + await dp.Debugger.oncePaused(); + testRunner.log(`Paused on 'debugger;'`); + + var messageObject = await dp.Runtime.evaluate({expression: 'messageDispatched' }); + var r = messageObject.result.result; + if (r.type === 'boolean' && r.value === false) + testRunner.log('PASS: message has not been dispatched yet.'); + else + testRunner.log('FAIL: unexpected response ' + JSON.stringify(messageObject, null, 2)); + + messageObject = await dp.Runtime.evaluate({expression: 'messageDispatched' }); + r = messageObject.result.result; + if (r.type === 'boolean' && r.value === false) + testRunner.log('PASS: message has not been dispatched yet.'); + else + testRunner.log('FAIL: unexpected response ' + JSON.stringify(messageObject, null, 2)); + + await dp.Debugger.resume(); + testRunner.log('Resumed, now waiting for pause in the event listener...'); + + await dp.Debugger.oncePaused(); + testRunner.log('PASS: pasued in the event listener.'); + await dp.Debugger.resume(); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/blackboxed.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/blackboxed.js deleted file mode 100644 index 51da71a..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/blackboxed.js +++ /dev/null
@@ -1,7 +0,0 @@ -function blackboxedBoo() -{ - var a = 42; - var b = foo(); - return a + b; -} -//# sourceURL=blackboxed-script.js
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/mixed.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/mixed.js deleted file mode 100644 index df01a0e9..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/mixed.js +++ /dev/null
@@ -1,21 +0,0 @@ -function notBlackboxedFoo() -{ - var a = 42; - var b = blackboxedBoo(); - return a + b; -} - -function blackboxedFoo() -{ - var a = 42; - var b = notBlackboxedFoo(); - return a + b; -} - -function notBlackboxedBoo() -{ - var a = 42; - var b = blackboxedFoo(); - return a + b; -} -//# sourceURL=mixed-source.js
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/script-blocked-by-csp.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/script-blocked-by-csp.js deleted file mode 100644 index 31a5ce5..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/script-blocked-by-csp.js +++ /dev/null
@@ -1,50 +0,0 @@ -function test() -{ - InspectorTest.sendCommand("Debugger.enable", {}); - InspectorTest.sendCommand("DOM.enable", {}); - InspectorTest.sendCommand("DOMDebugger.enable", {}); - InspectorTest.sendCommand("DOMDebugger.setInstrumentationBreakpoint", {"eventName":"scriptBlockedByCSP"}); - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPaused; - - var expressions = [ - "\n document.getElementById('testButton').click();", - - "\n var script = document.createElement('script');" + - "\n script.innerText = 'alert(1)';" + - "\n document.body.appendChild(script);", - - "\n var a = document.createElement('a');" + - "\n a.setAttribute('href', 'javascript:alert(1);');" + - "\n var dummy = 1; " + - "\n document.body.appendChild(a); a.click();" - ]; - var descriptions = [ - "blockedEventHandler", - "blockedScriptInjection", - "blockedScriptUrl" - ]; - - function nextExpression() - { - if (!expressions.length) { - InspectorTest.completeTest(); - return; - } - var description = descriptions.shift(); - InspectorTest.log("\n-------\n" + description); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "function " + description + "() {" + expressions.shift() + "}\n" + description + "()"}); - } - - function handleDebuggerPaused(messageObject) - { - var params = messageObject.params; - InspectorTest.log("Paused at: " + params.callFrames[0].functionName + "@" + params.callFrames[0].location.lineNumber); - InspectorTest.log("Reason: " + params.reason + "; Data:"); - InspectorTest.logObject(params.data); - InspectorTest.sendCommand("Debugger.resume", { }, nextExpression); - } - - nextExpression(); -} - -window.addEventListener("load", runTest.bind(null, false));
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/statements.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/statements.js deleted file mode 100644 index cec8a12..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/resources/statements.js +++ /dev/null
@@ -1,19 +0,0 @@ -function statementsExample() -{ - var self = arguments.callee; - - debugger; - - self.step = 1; - - self.step = 2; - - void [ - self.step = 3, - self.step = 4, - self.step = 5, - self.step = 6 - ]; - - self.step = 7; -} \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash-expected.txt index 237f325..b5a0f54 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash-expected.txt
@@ -1,3 +1,4 @@ + Hash received: 1C6D2E82E4E4F1BA4CB5762843D429DC872EBA18 Hash received: EBF1ECD351E7A3294CB5762843D429DC872EBA18 Hash received: 22D0043331237371241FC675A984B967025A3DC0
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.html deleted file mode 100644 index d441cb1..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.html +++ /dev/null
@@ -1,37 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> -function test() -{ - var hashes = new Set(["1C6D2E82E4E4F1BA4CB5762843D429DC872EBA18", - "EBF1ECD351E7A3294CB5762843D429DC872EBA18", - "22D0043331237371241FC675A984B967025A3DC0"]); - InspectorTest.sendCommandOrDie("Debugger.enable", {}, function() { - InspectorTest.eventHandler["Debugger.scriptParsed"] = function(messageObject) - { - if (hashes.has(messageObject.params.hash)) - InspectorTest.log("Hash received: " + messageObject.params.hash); - } - }); - - function longScript() { - var longScript = "var b = 1;"; - for (var i = 0; i < 2024; ++i) - longScript += "++b;"; - } - - InspectorTest.sendCommandOrDie("Runtime.evaluate", { expression: "1" }); - InspectorTest.sendCommandOrDie("Runtime.evaluate", { expression: "239" }); - InspectorTest.sendCommandOrDie("Runtime.evaluate", { expression: "(" + longScript + ")()" }, step2); - - function step2() - { - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.js new file mode 100644 index 0000000..8e5db35c --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/scriptParsedHash.js
@@ -0,0 +1,24 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + var hashes = new Set(['1C6D2E82E4E4F1BA4CB5762843D429DC872EBA18', + 'EBF1ECD351E7A3294CB5762843D429DC872EBA18', + '22D0043331237371241FC675A984B967025A3DC0']); + + dp.Debugger.enable(); + dp.Debugger.onScriptParsed(messageObject => { + if (hashes.has(messageObject.params.hash)) + testRunner.log('Hash received: ' + messageObject.params.hash); + }); + + function longScript() { + var longScript = "var b = 1;"; + for (var i = 0; i < 2024; ++i) + longScript += "++b;"; + } + + dp.Runtime.evaluate({expression: '1'}); + dp.Runtime.evaluate({expression: '239'}); + await dp.Runtime.evaluate({expression: '(' + longScript + ')()' }); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource-expected.txt index 1b76ec5..9e355e2 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource-expected.txt
@@ -1,3 +1,4 @@ + Function evaluate: {"type":"number","value":6,"description":"6"} PASS, result value: 6 Function evaluate: {"type":"number","value":8,"description":"8"}
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.html deleted file mode 100644 index 9bdb671..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.html +++ /dev/null
@@ -1,156 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script type="text/javascript" src="resources/liveedit-me.js"></script> -<script> - -function test() -{ - // A general-purpose engine for sending a sequence of protocol commands. - // The clients provide requests and response handlers, while the engine catches - // errors and makes sure that once there's nothing to do completeTest() is called. - // @param step is an object with command, params and callback fields - function runRequestSeries(step) { - processStep(step); - - function processStep(currentStep) { - try { - processStepOrFail(currentStep); - } catch (e) { - InspectorTest.log(e.stack); - InspectorTest.completeTest(); - } - } - - function processStepOrFail(currentStep) { - if (!currentStep) { - InspectorTest.completeTest(); - return; - } - if (!currentStep.command) { - // A simple loopback step. - var next = currentStep.callback(); - processStep(next); - return; - } - - var innerCallback = function(response) { - var next; - if ("error" in response) { - if (!("errorHandler" in currentStep)) { - // Error message is not logged intentionally, it may be platform-specific. - InspectorTest.log("Protocol command '" + currentStep.command + "' failed"); - InspectorTest.completeTest(); - return; - } - try { - next = currentStep.errorHandler(response.error); - } catch (e) { - InspectorTest.log(e.stack); - InspectorTest.completeTest(); - return; - } - } else { - try { - next = currentStep.callback(response.result); - } catch (e) { - InspectorTest.log(e.stack); - InspectorTest.completeTest(); - return; - } - } - processStep(next); - } - InspectorTest.sendCommand(currentStep.command, currentStep.params, innerCallback); - } - } - - function logEqualsCheck(actual, expected) - { - if (actual == expected) { - InspectorTest.log("PASS, result value: " + actual); - } else { - InspectorTest.log("FAIL, actual value: " + actual + ", expected: " + expected); - } - } - function logCheck(description, success) - { - InspectorTest.log(description + ": " + (success ? "PASS" : "FAIL")); - } - - var firstStep = { callback: enableDebugger }; - - runRequestSeries(firstStep); - - function enableDebugger() { - return { command: "Debugger.enable", params: {}, callback: evalFunction }; - } - - function evalFunction(response) { - var expression = "TestExpression(2, 4)"; - return { command: "Runtime.evaluate", params: { expression: expression }, callback: callbackEvalFunction }; - } - - function callbackEvalFunction(result) { - InspectorTest.log("Function evaluate: " + JSON.stringify(result.result)); - logEqualsCheck(result.result.value, 6); - - return { command: "Runtime.evaluate", params: { expression: "TestExpression" }, callback: callbackEvalFunctionObject }; - } - - function callbackEvalFunctionObject(result) { - return { command: "Runtime.getProperties", params: { objectId: result.result.objectId }, callback: callbackFunctionDetails }; - } - - function callbackFunctionDetails(result) - { - var scriptId; - for (var prop of result.internalProperties) { - if (prop.name === "[[FunctionLocation]]") - scriptId = prop.value.value.scriptId; - } - return createScriptManipulationArc(scriptId, null); - } - - // Several steps with scriptId in context. - function createScriptManipulationArc(scriptId, next) { - return { command: "Debugger.getScriptSource", params: { scriptId: scriptId }, callback: callbackGetScriptSource }; - - var originalText; - - function callbackGetScriptSource(result) { - originalText = result.scriptSource; - var patched = originalText.replace("a + b", "a * b"); - - return { command: "Debugger.setScriptSource", params: { scriptId: scriptId, scriptSource: patched }, callback: callbackSetScriptSource }; - } - - function callbackSetScriptSource(result) { - var expression = "TestExpression(2, 4)"; - return { command: "Runtime.evaluate", params: { expression: expression }, callback: callbackEvalFunction2 }; - } - - function callbackEvalFunction2(result) { - InspectorTest.log("Function evaluate: " + JSON.stringify(result.result)); - logEqualsCheck(result.result.value, 8); - - var patched = originalText.replace("a + b", "a # b"); - - return { command: "Debugger.setScriptSource", params: { scriptId: scriptId, scriptSource: patched }, callback: errorCallbackSetScriptSource2 }; - } - - function errorCallbackSetScriptSource2(result) { - var exceptionDetails = result.exceptionDetails; - logCheck("Has error reported", !!exceptionDetails); - logCheck("Reported error is a compile error", !!exceptionDetails); - if (exceptionDetails) - logEqualsCheck(exceptionDetails.lineNumber, 1); - return next; - } - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.js new file mode 100644 index 0000000..31b4f61 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/setScriptSource.js
@@ -0,0 +1,46 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + function logEqualsCheck(actual, expected) { + if (actual == expected) { + testRunner.log('PASS, result value: ' + actual); + } else { + testRunner.log('FAIL, actual value: ' + actual + ', expected: ' + expected); + } + } + + await session.evaluate( + `function TestExpression(a, b) { + return a + b; + }`); + + await dp.Debugger.enable(); + + var response = await dp.Runtime.evaluate({expression: 'TestExpression(2, 4)' }); + testRunner.log('Function evaluate: ' + JSON.stringify(response.result.result)); + logEqualsCheck(response.result.result.value, 6); + + var functionObjectId = (await dp.Runtime.evaluate({expression: 'TestExpression' })).result.result.objectId; + var result = (await dp.Runtime.getProperties({ objectId: functionObjectId})).result; + var scriptId; + for (var prop of result.internalProperties) { + if (prop.name === '[[FunctionLocation]]') + scriptId = prop.value.value.scriptId; + } + + var originalText = (await dp.Debugger.getScriptSource({scriptId})).result.scriptSource; + var patched = originalText.replace('a + b', 'a * b'); + await dp.Debugger.setScriptSource({scriptId, scriptSource: patched}); + + var response = await dp.Runtime.evaluate({expression: 'TestExpression(2, 4)' }); + testRunner.log('Function evaluate: ' + JSON.stringify(response.result.result)); + logEqualsCheck(response.result.result.value, 8); + + patched = originalText.replace('a + b', 'a # b'); + var exceptionDetails = (await dp.Debugger.setScriptSource({scriptId, scriptSource: patched})).result.exceptionDetails; + testRunner.log(`Has error reported: ${!!exceptionDetails ? 'PASS' : 'FAIL'}`, ); + testRunner.log(`Reported error is a compile error: ${!!exceptionDetails ? 'PASS' : 'FAIL'}`, ); + if (exceptionDetails) + logEqualsCheck(exceptionDetails.lineNumber, 1); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.html deleted file mode 100644 index e120131..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.html +++ /dev/null
@@ -1,54 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function testFunction() -{ - var e = document.getElementById("div"); - debugger; - e.click(); -} - -function shouldNotBeThisFunction() -{ - return 239; -} - -function test() -{ - InspectorTest.waitForEventPromise("Debugger.paused").then(makeStepping); - - InspectorTest.sendCommandPromise("Debugger.enable", {}) - .then((result) => InspectorTest.sendCommandPromise("Runtime.evaluate", { expression: "testFunction()" })) - .then(() => InspectorTest.completeTest()); - - function makeStepping() - { - sendCommandAndWaitForPause("Debugger.stepInto") - .then(() => sendCommandAndWaitForPause("Debugger.stepInto")) - .then((result) => dumpTopCallFrame(result)) - .then(() => InspectorTest.sendCommandPromise("Debugger.resume")); - } - - function sendCommandAndWaitForPause(command) - { - InspectorTest.sendCommand(command, {}); - return InspectorTest.waitForEventPromise("Debugger.paused"); - } - - function dumpTopCallFrame(result) - { - var frame = result.params.callFrames[0]; - InspectorTest.log("functionName (should be empty): " + (frame.functionName.length ? frame.functionName : "empty")); - } -} -</script> -</head> -<div id="div" onclick="shouldNotBeThisFunction()"> -</div> -<body onLoad="runTest();"> -Tests that Debugger.stepInto doesn't ignore inline event listeners. -</body> -</html> -
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.js new file mode 100644 index 0000000..9d71b342 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-into-inline-event-handler.js
@@ -0,0 +1,35 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startHTML(` + <script> + function testFunction() { + var e = document.getElementById('div'); + debugger; + e.click(); + } + + function shouldNotBeThisFunction() { + return 239; + } + </script> + <div id='div' onclick='shouldNotBeThisFunction()'></div> + `, `Tests that Debugger.stepInto doesn't ignore inline event listeners.`); + + + function dumpTopCallFrame(result) { + var frame = result.params.callFrames[0]; + testRunner.log('functionName (should be empty): ' + (frame.functionName.length ? frame.functionName : 'empty')); + } + + await dp.Debugger.enable(); + var finished = dp.Runtime.evaluate({expression: 'testFunction()'}); + + await dp.Debugger.oncePaused(); + dp.Debugger.stepInto(); + await dp.Debugger.oncePaused(); + dp.Debugger.stepInto(); + dumpTopCallFrame(await dp.Debugger.oncePaused()); + dp.Debugger.resume(); + + await finished; + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception-expected.txt index 78aaf35..e6ce4af3 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception-expected.txt
@@ -1,5 +1,4 @@ -CONSOLE MESSAGE: line 16: completed -CONSOLE MESSAGE: line 16: completed + testFunction:13 testFunction:15 testFunction:13
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.html deleted file mode 100644 index 1da33950..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.html +++ /dev/null
@@ -1,83 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> -function testFunction() -{ - function foo() - { - try { - throw new Error(); - } catch (e) { - } - } - debugger; - foo(); - console.log("completed"); -} -</script> -<script> -function test() -{ - InspectorTest.sendCommandOrDie("Debugger.enable", {} ); - InspectorTest.sendCommandOrDie("Runtime.enable", {} ); - step1(); - - function step1() - { - InspectorTest.sendCommandOrDie("Runtime.evaluate", { "expression": "setTimeout(testFunction, 0);"} ); - var commands = [ "Print", "stepOver", "stepOver", "Print", "resume" ]; - InspectorTest.eventHandler["Debugger.paused"] = function(messageObject) - { - var command = commands.shift(); - if (command === "Print") { - var callFrames = messageObject.params.callFrames; - for (var callFrame of callFrames) - InspectorTest.log(callFrame.functionName + ":" + callFrame.location.lineNumber); - command = commands.shift(); - } - if (command) - InspectorTest.sendCommandOrDie("Debugger." + command, {}); - } - - InspectorTest.eventHandler["Runtime.consoleAPICalled"] = function(messageObject) - { - if (messageObject.params.args[0].value === "completed") { - if (commands.length) - InspectorTest.log("[FAIL]: execution was resumed too earlier.") - step2(); - } - } - } - - function step2() - { - InspectorTest.sendCommandOrDie("Runtime.evaluate", { "expression": "setTimeout(testFunction, 0);"} ); - var commands = [ "Print", "stepOver", "stepInto", "stepOver", "stepOver", "Print", "resume" ]; - InspectorTest.eventHandler["Debugger.paused"] = function(messageObject) - { - var command = commands.shift(); - if (command === "Print") { - var callFrames = messageObject.params.callFrames; - for (var callFrame of callFrames) - InspectorTest.log(callFrame.functionName + ":" + callFrame.location.lineNumber); - command = commands.shift(); - } - if (command) - InspectorTest.sendCommandOrDie("Debugger." + command, {}); - } - - InspectorTest.eventHandler["Runtime.consoleAPICalled"] = function(messageObject) - { - if (messageObject.params.args[0].value === "completed") { - if (commands.length) - InspectorTest.log("[FAIL]: execution was resumed too earlier.") - InspectorTest.completeTest(); - } - } - } -} -</script> -</head> -<body onLoad="runTest();"></body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.js new file mode 100644 index 0000000..a30526d --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/step-over-caught-exception.js
@@ -0,0 +1,54 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + dp.Debugger.enable(); + dp.Runtime.enable(); + dp.Runtime.evaluate({expression: ` + + + + + + function testFunction() { + function foo() { + try { + throw new Error(); + } catch (e) { + } + } + debugger; + foo(); + console.log('completed'); + } + setTimeout(testFunction, 0); + `}); + + function printCallFrames(messageObject) { + var callFrames = messageObject.params.callFrames; + for (var callFrame of callFrames) + testRunner.log(callFrame.functionName + ':' + callFrame.location.lineNumber); + } + + printCallFrames(await dp.Debugger.oncePaused()); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + dp.Debugger.stepOver(); + printCallFrames(await dp.Debugger.oncePaused()); + dp.Debugger.resume(); + await dp.Runtime.onceConsoleAPICalled(messageObject => messageObject.params.args[0].value === 'completed'); + + dp.Runtime.evaluate({expression: 'setTimeout(testFunction, 0);'} ); + printCallFrames(await dp.Debugger.oncePaused()); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + dp.Debugger.stepInto(); + await dp.Debugger.oncePaused(); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + dp.Debugger.stepOver(); + printCallFrames(await dp.Debugger.oncePaused()); + dp.Debugger.resume(); + await dp.Runtime.onceConsoleAPICalled(messageObject => messageObject.params.args[0].value === 'completed'); + + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges-expected.txt index 2969deb4..10cc9e4 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges-expected.txt
@@ -1,3 +1,4 @@ + foo: 14:4 blackboxedBoo: 3:12 notBlackboxedFoo: 3:12
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.html deleted file mode 100644 index cbb17ec..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.html +++ /dev/null
@@ -1,104 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script type="text/javascript" src="resources/blackboxed.js"></script> -<script type="text/javascript" src="resources/mixed.js"></script> -<script> -function testFunction() -{ - notBlackboxedBoo(); // for setup ranges and stepOut - notBlackboxedBoo(); // for stepIn -} - -function foo() -{ - debugger; - return 239; -} -</script> -<script> -function test() -{ - InspectorTest.eventHandler["Debugger.paused"] = setBlackboxedScriptRanges; - InspectorTest.sendCommandOrDie("Debugger.enable", {}, callTestFunction); - - function callTestFunction(response) - { - InspectorTest.evaluateInInspectedPage("setTimeout(testFunction, 0);"); - } - - function setBlackboxedScriptRanges(response) - { - var callFrames = response.params.callFrames; - printCallFrames(callFrames); - InspectorTest.sendCommand("Debugger.setBlackboxedRanges", { - scriptId: callFrames[1].location.scriptId, - positions: [ { lineNumber: 0, columnNumber: 0 } ] // blackbox ranges for blackboxed.js - }, setIncorrectRanges.bind(null, callFrames[2].location.scriptId)); - } - - var incorrectPositions = [ - [ { lineNumber: 0, columnNumber: 0 }, { lineNumber: 0, columnNumber: 0 } ], - [ { lineNumber: 0, columnNumber: 1 }, { lineNumber: 0, columnNumber: 0 } ], - [ { lineNumber: 0, columnNumber: -1 } ], - ]; - - function setIncorrectRanges(scriptId, response) - { - if (response.error) - InspectorTest.log(response.error.message); - var positions = incorrectPositions.shift(); - if (!positions) { - setMixedSourceRanges(scriptId); - return; - } - InspectorTest.log("Try to set positions: " + JSON.stringify(positions)); - InspectorTest.sendCommand("Debugger.setBlackboxedRanges", { - scriptId: scriptId, - positions: positions - }, setIncorrectRanges.bind(null, scriptId)); - } - - function setMixedSourceRanges(scriptId) - { - InspectorTest.eventHandler["Debugger.paused"] = runAction; - InspectorTest.sendCommandOrDie("Debugger.setBlackboxedRanges", { - scriptId: scriptId, - positions: [ { lineNumber: 6, columnNumber: 0 }, { lineNumber: 14, columnNumber: 0 } ] // blackbox ranges for mixed.js - }, runAction); - } - - var actions = [ "stepOut", "print", "stepOut", "print", "stepOut", "print", - "stepInto", "print", "stepOver", "stepInto", "print", "stepOver", "stepInto", "print", - "stepOver", "stepInto", "print" ]; - - function runAction(response) - { - var action = actions.shift(); - if (!action) - InspectorTest.completeTest(); - - if (action === "print") { - printCallFrames(response.params.callFrames); - runAction({}); - } else { - InspectorTest.log("action: " + action); - InspectorTest.sendCommandOrDie("Debugger." + action, {}); - } - } - - function printCallFrames(callFrames) - { - var topCallFrame = callFrames[0]; - if (topCallFrame.functionName.startsWith("blackboxed")) - InspectorTest.log("FAIL: blackboxed function in top call frame"); - for (var callFrame of callFrames) - InspectorTest.log(callFrame.functionName + ': ' + callFrame.location.lineNumber + ":" + callFrame.location.columnNumber); - InspectorTest.log(""); - } -} -</script> -</head> -<body onload="runTest()"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.js new file mode 100644 index 0000000..49757284 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/stepping-with-blackboxed-ranges.js
@@ -0,0 +1,131 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + function printCallFrames(response) { + var callFrames = response.params.callFrames; + var topCallFrame = callFrames[0]; + if (topCallFrame.functionName.startsWith('blackboxed')) + testRunner.log('FAIL: blackboxed function in top call frame'); + for (var callFrame of callFrames) + testRunner.log(callFrame.functionName + ': ' + callFrame.location.lineNumber + ':' + callFrame.location.columnNumber); + testRunner.log(''); + } + + function printError(response) { + if (response.error) + testRunner.log(response.error.message); + } + + await session.evaluate( +`function blackboxedBoo() +{ + var a = 42; + var b = foo(); + return a + b; +} +//# sourceURL=blackboxed-script.js +`); + + await session.evaluate( +`function notBlackboxedFoo() +{ + var a = 42; + var b = blackboxedBoo(); + return a + b; +} + +function blackboxedFoo() +{ + var a = 42; + var b = notBlackboxedFoo(); + return a + b; +} + +function notBlackboxedBoo() +{ + var a = 42; + var b = blackboxedFoo(); + return a + b; +} +//# sourceURL=mixed-source.js +`); + + await session.evaluate(` + + + + + +function testFunction() +{ + notBlackboxedBoo(); // for setup ranges and stepOut + notBlackboxedBoo(); // for stepIn +} + +function foo() +{ + debugger; + return 239; +} + `); + + await dp.Debugger.enable(); + session.evaluate('setTimeout(testFunction, 0);'); + + var response = await dp.Debugger.oncePaused(); + printCallFrames(response); + var scriptId = response.params.callFrames[2].location.scriptId; + + printError(await dp.Debugger.setBlackboxedRanges({ + scriptId: response.params.callFrames[1].location.scriptId, + positions: [{lineNumber: 0, columnNumber: 0}] // blackbox ranges for blackboxed.js + })); + + var incorrectPositions = [ + [{lineNumber: 0, columnNumber: 0}, {lineNumber: 0, columnNumber: 0}], + [{lineNumber: 0, columnNumber: 1}, {lineNumber: 0, columnNumber: 0}], + [{lineNumber: 0, columnNumber: -1}], + ]; + for (var positions of incorrectPositions) { + testRunner.log('Try to set positions: ' + JSON.stringify(positions)); + printError(await dp.Debugger.setBlackboxedRanges({scriptId, positions})); + } + + await dp.Debugger.setBlackboxedRanges({ + scriptId, + positions: [{lineNumber: 6, columnNumber: 0}, {lineNumber: 14, columnNumber: 0}] // blackbox ranges for mixed.js + }); + + testRunner.log('action: stepOut'); + dp.Debugger.stepOut(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepOut'); + dp.Debugger.stepOut(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepOut'); + dp.Debugger.stepOut(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepInto'); + dp.Debugger.stepInto(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepOver'); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + testRunner.log('action: stepInto'); + dp.Debugger.stepInto(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepOver'); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + testRunner.log('action: stepInto'); + dp.Debugger.stepInto(); + printCallFrames(await dp.Debugger.oncePaused()); + testRunner.log('action: stepOver'); + dp.Debugger.stepOver(); + await dp.Debugger.oncePaused(); + testRunner.log('action: stepInto'); + dp.Debugger.stepInto(); + printCallFrames(await dp.Debugger.oncePaused()); + await dp.Debugger.resume(); + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker-expected.txt index d6da87d7..492170a 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker-expected.txt
@@ -1,5 +1,4 @@ Tests that setTimeout callback will not fire while script execution is paused.Bug 377926. - Started worker Worker created SUCCESS: Worker paused
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html deleted file mode 100644 index 7853e5d..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html +++ /dev/null
@@ -1,82 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> -var worker; - -function startWorker() -{ - worker = new Worker("resources/dedicated-worker-suspend-setTimeout.js"); - worker.onmessage = function(event) { }; - worker.postMessage(1); - log("Started worker"); -} - - -function test() -{ - - var workerId; - var workerRequestId = 1; - function sendCommandToWorker(method, params) - { - var requestId = workerRequestId++; - InspectorTest.sendCommand("Target.sendMessageToTarget", - { - "targetId": workerId, - "message": JSON.stringify({ "method": method, - "params": params, - "id": requestId }) - }); - return requestId; - } - - function didEnableWorkerDebugging(messageObject) - { - if ("error" in messageObject) { - InspectorTest.log("FAIL: Couldn't enable worker debugger: " + messageObject.error.message); - InspectorTest.completeTest(); - } - } - InspectorTest.sendCommand("Target.setAutoAttach", {autoAttach: true, waitForDebuggerOnStart: true}, didEnableWorkerDebugging); - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "startWorker()" }); - - InspectorTest.eventHandler["Target.attachedToTarget"] = function(messageObject) - { - workerId = messageObject["params"]["targetInfo"]["targetId"]; - InspectorTest.log("Worker created"); - sendCommandToWorker("Debugger.enable", {}); - sendCommandToWorker("Runtime.runIfWaitingForDebugger", {}); - } - - var pauseCount = 0; - var evalRequestId; - InspectorTest.eventHandler["Target.receivedMessageFromTarget"] = function(messageObject) - { - var message = JSON.parse(messageObject["params"]["message"]); - if (message["method"] === "Debugger.paused") { - InspectorTest.log("SUCCESS: Worker paused"); - if (++pauseCount === 1) { - evalRequestId = sendCommandToWorker("Runtime.evaluate", { "expression": "global_value" }); - } else { - InspectorTest.log("FAIL: debugger paused second time"); - InspectorTest.completeTest(); - } - } else if (evalRequestId && message["id"] === evalRequestId) { - var value = message["result"]["result"]["value"]; - if (value === 1) - InspectorTest.log("SUCCESS: global_value is 1"); - else - InspectorTest.log("FAIL: setTimeout callback fired while script execution was paused"); - sendCommandToWorker("Debugger.disable", {}); - InspectorTest.completeTest(); - } - } -} -</script> -</head> -<body onLoad="runTest();"> -<p>Tests that setTimeout callback will not fire while script execution is paused.<a href="https://code.google.com/p/chromium/issues/detail?id=377926">Bug 377926.</a> -</p> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.js new file mode 100644 index 0000000..f5ffb967 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.js
@@ -0,0 +1,49 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank('Tests that setTimeout callback will not fire while script execution is paused.Bug 377926.'); + + var workerId; + var workerRequestId = 1; + function sendCommandToWorker(method, params) { + var message = {method, params, id: workerRequestId}; + dp.Target.sendMessageToTarget({targetId: workerId, message: JSON.stringify(message)}); + return workerRequestId++; + } + + dp.Target.setAutoAttach({autoAttach: true, waitForDebuggerOnStart: true}); + await session.evaluate(` + window.worker = new Worker('${testRunner.url('resources/dedicated-worker-suspend-setTimeout.js')}'); + window.worker.onmessage = function(event) { }; + window.worker.postMessage(1); + `); + testRunner.log('Started worker'); + + var messageObject = await dp.Target.onceAttachedToTarget(); + workerId = messageObject.params.targetInfo.targetId; + testRunner.log('Worker created'); + + sendCommandToWorker('Debugger.enable', {}); + sendCommandToWorker('Runtime.runIfWaitingForDebugger', {}); + + var pauseCount = 0; + var evalRequestId; + dp.Target.onReceivedMessageFromTarget(async messageObject => { + var message = JSON.parse(messageObject.params.message); + if (message.method === 'Debugger.paused') { + testRunner.log('SUCCESS: Worker paused'); + if (++pauseCount === 1) { + evalRequestId = sendCommandToWorker('Runtime.evaluate', {expression: 'global_value'}); + } else { + testRunner.log('FAIL: debugger paused second time'); + testRunner.completeTest(); + } + } else if (evalRequestId && message.id === evalRequestId) { + var value = message.result.result.value; + if (value === 1) + testRunner.log('SUCCESS: global_value is 1'); + else + testRunner.log('FAIL: setTimeout callback fired while script execution was paused'); + sendCommandToWorker('Debugger.disable', {}); + testRunner.completeTest(); + } + }); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes-expected.txt b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes-expected.txt index ed52d23..55d32b9 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes-expected.txt
@@ -1,3 +1,4 @@ + Paused on 'debugger;' Variable value changed Stacktrace re-read again
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.html deleted file mode 100644 index 20004b4..0000000 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.html +++ /dev/null
@@ -1,72 +0,0 @@ -<html> -<head> -<script type="text/javascript" src="../../http/tests/inspector-protocol/resources/inspector-protocol-test.js"></script> -<script> - -function TestFunction() -{ - var a = 2; - debugger; - debugger; -} - -function test() -{ - var newVariableValue = 55; - - InspectorTest.sendCommand("Debugger.enable", {}); - - InspectorTest.eventHandler["Debugger.paused"] = handleDebuggerPaused; - - InspectorTest.sendCommand("Runtime.evaluate", { "expression": "setTimeout(TestFunction, 0)" }); - - function handleDebuggerPaused(messageObject) - { - InspectorTest.log("Paused on 'debugger;'"); - InspectorTest.eventHandler["Debugger.paused"] = undefined; - - var topFrame = messageObject.params.callFrames[0]; - var topFrameId = topFrame.callFrameId; - InspectorTest.sendCommand("Debugger.evaluateOnCallFrame", { "callFrameId": topFrameId, "expression": "a = " + newVariableValue }, callbackChangeValue); - } - - function callbackChangeValue(response) - { - InspectorTest.log("Variable value changed"); - InspectorTest.eventHandler["Debugger.paused"] = callbackGetBacktrace; - InspectorTest.sendCommand("Debugger.resume", { }); - } - - function callbackGetBacktrace(response) - { - InspectorTest.log("Stacktrace re-read again"); - var localScope = response.params.callFrames[0].scopeChain[0]; - InspectorTest.sendCommand("Runtime.getProperties", { "objectId": localScope.object.objectId }, callbackGetProperties); - } - - function callbackGetProperties(response) - { - InspectorTest.log("Scope variables downloaded anew"); - var varNamedA; - var propertyList = response.result.result; - for (var i = 0; i < propertyList.length; i++) { - if (propertyList[i].name === "a") { - varNamedA = propertyList[i]; - break; - } - } - if (varNamedA) { - var actualValue = varNamedA.value.value; - InspectorTest.log("New variable is " + actualValue + ", expected is " + newVariableValue + ", old was: 2"); - InspectorTest.log(actualValue == newVariableValue ? "SUCCESS" : "FAIL"); - } else { - InspectorTest.log("Failed to find variable in scope"); - } - InspectorTest.completeTest(); - } -} -</script> -</head> -<body onLoad="runTest();"> -</body> -</html>
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.js b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.js new file mode 100644 index 0000000..09e007d --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/updateCallFrameScopes.js
@@ -0,0 +1,41 @@ +(async function(testRunner) { + let {page, session, dp} = await testRunner.startBlank(''); + + var newVariableValue = 55; + + dp.Debugger.enable(); + dp.Runtime.evaluate({expression: ` + function TestFunction() { + var a = 2; + debugger; + debugger; + } + setTimeout(TestFunction, 0); + `}); + + var messageObject = await dp.Debugger.oncePaused(); + testRunner.log(`Paused on 'debugger;'`); + var topFrame = messageObject.params.callFrames[0]; + var topFrameId = topFrame.callFrameId; + + dp.Debugger.evaluateOnCallFrame({callFrameId: topFrameId, expression: 'a = ' + newVariableValue }); + testRunner.log('Variable value changed'); + dp.Debugger.resume(); + + var response = await dp.Debugger.oncePaused(); + testRunner.log('Stacktrace re-read again'); + var localScope = response.params.callFrames[0].scopeChain[0]; + + response = await dp.Runtime.getProperties({objectId: localScope.object.objectId }); + testRunner.log('Scope variables downloaded anew'); + var propertyList = response.result.result; + var varNamedA = propertyList.find(x => x.name === 'a'); + if (varNamedA) { + var actualValue = varNamedA.value.value; + testRunner.log('New variable is ' + actualValue + ', expected is ' + newVariableValue + ', old was: 2'); + testRunner.log(actualValue == newVariableValue ? 'SUCCESS' : 'FAIL'); + } else { + testRunner.log('Failed to find variable in scope'); + } + testRunner.completeTest(); +})
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/resources/inspector-protocol-test.js b/third_party/WebKit/LayoutTests/inspector-protocol/resources/inspector-protocol-test.js index ca43106..f2c60bad 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/resources/inspector-protocol-test.js +++ b/third_party/WebKit/LayoutTests/inspector-protocol/resources/inspector-protocol-test.js
@@ -312,7 +312,7 @@ var eventName = match[3]; eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1); if (match[1] === 'once') - return () => this._waitForEvent(`${agentName}.${eventName}`); + return eventMatcher => this._waitForEvent(`${agentName}.${eventName}`, eventMatcher); if (match[1] === 'off') return listener => this._removeEventHandler(`${agentName}.${eventName}`, listener); return listener => this._addEventHandler(`${agentName}.${eventName}`, listener); @@ -335,9 +335,11 @@ this._eventHandlers.set(eventName, handlers); } - _waitForEvent(eventName) { + _waitForEvent(eventName, eventMatcher) { return new Promise(callback => { var handler = result => { + if (eventMatcher && !eventMatcher(result)) + return; this._removeEventHandler(eventName, handler); callback(result); };
diff --git a/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling-expected.txt b/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling-expected.txt new file mode 100644 index 0000000..b6a2ccb3 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling-expected.txt
@@ -0,0 +1,135 @@ +Tests that mobile, network, and CPU throttling interact with each other logically. + +Initial throttling state +=== THROTTLING STATE === +Network throttling - download: -1 upload: -1 latency: 0 +CPU throttling rate: 1 +Device mode throttling: Online +Network panel offline checkbox: false +Network panel throttling: Online +Network conditions drawer throttling: Online +Performance panel network throttling: Online +Performance panel CPU throttling: No throttling +======================== + +Change to offline in device mode +=== THROTTLING STATE === +Network throttling - download: 0 upload: 0 latency: 0 +CPU throttling rate: 1 +Device mode throttling: Offline +Network panel offline checkbox: true +Network panel throttling: Offline +Network conditions drawer throttling: Offline +Performance panel network throttling: Offline +Performance panel CPU throttling: No throttling +======================== + +Toggle network offline checkbox +=== THROTTLING STATE === +Network throttling - download: -1 upload: -1 latency: 0 +CPU throttling rate: 1 +Device mode throttling: Online +Network panel offline checkbox: false +Network panel throttling: Online +Network conditions drawer throttling: Online +Performance panel network throttling: Online +Performance panel CPU throttling: No throttling +======================== + +Change to low-end mobile in device mode +=== THROTTLING STATE === +Network throttling - download: 51200 upload: 51200 latency: 2000 +CPU throttling rate: 6 +Device mode throttling: Low-end mobile +Network panel offline checkbox: false +Network panel throttling: Slow 3G +Network conditions drawer throttling: Slow 3G +Performance panel network throttling: Slow 3G +Performance panel CPU throttling: 6× slowdown +======================== + +Change network to Fast 3G +=== THROTTLING STATE === +Network throttling - download: 188743.68000000002 upload: 86400 latency: 562.5 +CPU throttling rate: 6 +Device mode throttling: Custom +Network panel offline checkbox: false +Network panel throttling: Fast 3G +Network conditions drawer throttling: Fast 3G +Performance panel network throttling: Fast 3G +Performance panel CPU throttling: 6× slowdown +======================== + +Toggle network offline checkbox (enable offline) +=== THROTTLING STATE === +Network throttling - download: 0 upload: 0 latency: 0 +CPU throttling rate: 6 +Device mode throttling: Custom +Network panel offline checkbox: true +Network panel throttling: Offline +Network conditions drawer throttling: Offline +Performance panel network throttling: Offline +Performance panel CPU throttling: 6× slowdown +======================== + +Toggle network offline checkbox (disable offline) +=== THROTTLING STATE === +Network throttling - download: 188743.68000000002 upload: 86400 latency: 562.5 +CPU throttling rate: 6 +Device mode throttling: Custom +Network panel offline checkbox: false +Network panel throttling: Fast 3G +Network conditions drawer throttling: Fast 3G +Performance panel network throttling: Fast 3G +Performance panel CPU throttling: 6× slowdown +======================== + +Change to mid-tier mobile in device mode +=== THROTTLING STATE === +Network throttling - download: 188743.68000000002 upload: 86400 latency: 562.5 +CPU throttling rate: 4 +Device mode throttling: Mid-tier mobile +Network panel offline checkbox: false +Network panel throttling: Fast 3G +Network conditions drawer throttling: Fast 3G +Performance panel network throttling: Fast 3G +Performance panel CPU throttling: 4× slowdown +======================== + +Change CPU throttling to low-end mobile +=== THROTTLING STATE === +Network throttling - download: 188743.68000000002 upload: 86400 latency: 562.5 +CPU throttling rate: 6 +Device mode throttling: Custom +Network panel offline checkbox: false +Network panel throttling: Fast 3G +Network conditions drawer throttling: Fast 3G +Performance panel network throttling: Fast 3G +Performance panel CPU throttling: 6× slowdown +======================== + +Change CPU throttling to mid-tier mobile +=== THROTTLING STATE === +Network throttling - download: 188743.68000000002 upload: 86400 latency: 562.5 +CPU throttling rate: 4 +Device mode throttling: Mid-tier mobile +Network panel offline checkbox: false +Network panel throttling: Fast 3G +Network conditions drawer throttling: Fast 3G +Performance panel network throttling: Fast 3G +Performance panel CPU throttling: 4× slowdown +======================== + +Change to no throttling in device mode +=== THROTTLING STATE === +Network throttling - download: -1 upload: -1 latency: 0 +CPU throttling rate: 1 +Device mode throttling: Online +Network panel offline checkbox: false +Network panel throttling: Online +Network conditions drawer throttling: Online +Performance panel network throttling: Online +Performance panel CPU throttling: No throttling +======================== + +
diff --git a/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling.html b/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling.html new file mode 100644 index 0000000..ce09f425 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/throttling/mobile-throttling.html
@@ -0,0 +1,106 @@ +<html> +<head> +<title> Change mobile throttling setting.</title> +<script src = "../../http/tests/inspector/inspector-test.js"></script> +<script> + +function initialize_ThrottlingTest() { + InspectorTest.preloadPanel("network"); + InspectorTest.preloadPanel("timeline"); + UI.viewManager.showView("network.config"); +} + +function test() { + var deviceModeView = new Emulation.DeviceModeView(); + + var deviceModeThrottling = deviceModeView._toolbar._throttlingConditionsItem; + var networkPanelThrottling = UI.panels.network._throttlingSelect; + var networkPanelOfflineCheckbox = UI.panels.network._offlineCheckbox.inputElement; + var networkConditionsDrawerThrottlingSelector = + self.runtime.sharedInstance(Network.NetworkConfigView)._networkThrottlingSelect; + var performancePanelNetworkThrottling = UI.panels.timeline._networkThrottlingSelect; + var performancePanelCPUThrottling = UI.panels.timeline._cpuThrottlingSelect; + + function dumpThrottlingState() { + InspectorTest.addResult('=== THROTTLING STATE ==='); + var {download, upload, latency} = SDK.multitargetNetworkManager.networkConditions(); + InspectorTest.addResult(`Network throttling - download: ${download} upload: ${upload} latency: ${latency}`); + InspectorTest.addResult('CPU throttling rate: ' + + MobileThrottling.throttlingManager().cpuThrottlingRate()); + InspectorTest.addResult('Device mode throttling: ' + deviceModeThrottling._text); + InspectorTest.addResult('Network panel offline checkbox: ' + + networkPanelOfflineCheckbox.checked); + InspectorTest.addResult('Network panel throttling: ' + + networkPanelThrottling.selectedOption().text); + InspectorTest.addResult('Network conditions drawer throttling: ' + + networkConditionsDrawerThrottlingSelector.value); + InspectorTest.addResult('Performance panel network throttling: ' + + performancePanelNetworkThrottling.selectedOption().text); + InspectorTest.addResult('Performance panel CPU throttling: ' + + performancePanelCPUThrottling.selectedOption().text); + InspectorTest.addResult('========================\n'); + } + + InspectorTest.addResult('Initial throttling state'); + dumpThrottlingState(); + + InspectorTest.addResult('Change to offline in device mode'); + SDK.multitargetNetworkManager.setNetworkConditions(MobileThrottling.OfflineConditions.network); + MobileThrottling.throttlingManager().setCPUThrottlingRate( + MobileThrottling.OfflineConditions.cpuThrottlingRate); + dumpThrottlingState(); + + InspectorTest.addResult('Toggle network offline checkbox'); + networkPanelOfflineCheckbox.click(); + dumpThrottlingState(); + + InspectorTest.addResult('Change to low-end mobile in device mode'); + SDK.multitargetNetworkManager.setNetworkConditions(MobileThrottling.LowEndMobileConditions.network); + MobileThrottling.throttlingManager().setCPUThrottlingRate( + MobileThrottling.LowEndMobileConditions.cpuThrottlingRate); + dumpThrottlingState(); + + InspectorTest.addResult('Change network to Fast 3G'); + SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.Fast3GConditions); + dumpThrottlingState(); + + InspectorTest.addResult('Toggle network offline checkbox (enable offline)'); + networkPanelOfflineCheckbox.click(); + dumpThrottlingState(); + + InspectorTest.addResult('Toggle network offline checkbox (disable offline)'); + networkPanelOfflineCheckbox.click(); + dumpThrottlingState(); + + InspectorTest.addResult('Change to mid-tier mobile in device mode'); + SDK.multitargetNetworkManager.setNetworkConditions(MobileThrottling.MidTierMobileConditions.network); + MobileThrottling.throttlingManager().setCPUThrottlingRate( + MobileThrottling.MidTierMobileConditions.cpuThrottlingRate); + dumpThrottlingState(); + + InspectorTest.addResult('Change CPU throttling to low-end mobile'); + MobileThrottling.throttlingManager().setCPUThrottlingRate(MobileThrottling.CPUThrottlingRates.LowEndMobile); + dumpThrottlingState(); + + InspectorTest.addResult('Change CPU throttling to mid-tier mobile'); + MobileThrottling.throttlingManager().setCPUThrottlingRate( + MobileThrottling.CPUThrottlingRates.MidTierMobile); + dumpThrottlingState(); + + InspectorTest.addResult('Change to no throttling in device mode'); + SDK.multitargetNetworkManager.setNetworkConditions(MobileThrottling.NoThrottlingConditions.network); + MobileThrottling.throttlingManager().setCPUThrottlingRate( + MobileThrottling.NoThrottlingConditions.cpuThrottlingRate); + dumpThrottlingState(); + + InspectorTest.completeTest(); +} + +</script> +</head> +<body onload="runTest()"> + <p> + Tests that mobile, network, and CPU throttling interact with each other logically. + </p> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/mojo/bind-intercepted-interface-in-worker.html b/third_party/WebKit/LayoutTests/mojo/bind-intercepted-interface-in-worker.html new file mode 100644 index 0000000..50d4293 --- /dev/null +++ b/third_party/WebKit/LayoutTests/mojo/bind-intercepted-interface-in-worker.html
@@ -0,0 +1,15 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> +'use strict'; + +async_test(t => { + let worker = new Worker('resources/bind-intercepted-interface-in-worker.js'); + worker.postMessage({}); + worker.onmessage = e => { + if (e.data == 'PASS') + t.done(); + }; +}, 'Can implement a Mojo service and intercept it from a worker'); +</script>
diff --git a/third_party/WebKit/LayoutTests/mojo/detached-frame.html b/third_party/WebKit/LayoutTests/mojo/detached-frame.html new file mode 100644 index 0000000..0bea05d --- /dev/null +++ b/third_party/WebKit/LayoutTests/mojo/detached-frame.html
@@ -0,0 +1,102 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js"></script> +<script src="file:///gen/content/test/data/mojo_layouttest_test.mojom.js"></script> +<body> +<script> + +function frameLoaded(frame) { + return new Promise(resolve => { + let eventHandler = e => { + frame.removeEventListener('load', eventHandler); + resolve(); + }; + frame.addEventListener('load', eventHandler); + }); +} + +promise_test(async () => { + let frame = document.createElement("iframe"); + let promise = frameLoaded(frame); + document.body.appendChild(frame); + await promise; + + // Save a reference to the Mojo object from the child frame so that we can + // make calls to it after the context has been destroyed. + let frameMojo = frame.contentWindow.Mojo; + document.body.removeChild(frame); + + let helper = new content.mojom.MojoLayoutTestHelperPtr; + frameMojo.bindInterface(content.mojom.MojoLayoutTestHelper.name, + mojo.makeRequest(helper).handle); + + try { + let reply = await helper.reverse("hello world."); + assert_unreached(); + } catch (e) { + // Connection failure expected. + } +}, "Mojo object is safe to use after its frame has been detached"); + +promise_test(async () => { + let frame = document.createElement("iframe"); + let promise = frameLoaded(frame); + document.body.appendChild(frame); + await promise; + + // Save a reference to the MojoInterfaceInterceptor constructor from the child + // frame so that we can be used after the context has been destroyed. + let frameMojoInterfaceInterceptor = + frame.contentWindow.MojoInterfaceInterceptor; + document.body.removeChild(frame); + + let interceptor = new frameMojoInterfaceInterceptor( + content.mojom.MojoLayoutTestHelper.name); + try { + interceptor.start(); + assert_unreached(); + } catch (e) { + // Failure expected. + } +}, "MojoInterfaceInterceptor constructor is safe to use after its frame has been detached"); + +promise_test(async () => { + let frame = document.createElement("iframe"); + let promise = frameLoaded(frame); + document.body.appendChild(frame); + await promise; + + // Create the interceptor while the frame is attached so that it is associated + // with the frame's execution context. + let interceptor = new frame.contentWindow.MojoInterfaceInterceptor( + content.mojom.MojoLayoutTestHelper.name); + document.body.removeChild(frame); + + try { + interceptor.start(); + assert_unreached(); + } catch (e) { + // Failure expected. + } +}, "MojoInterfaceInterceptor can't be started after its frame has been detached"); + +promise_test(async () => { + let frame = document.createElement("iframe"); + let promise = frameLoaded(frame); + document.body.appendChild(frame); + await promise; + + // Create the interceptor and start it while the frame is attached. + let interceptor = new frame.contentWindow.MojoInterfaceInterceptor( + content.mojom.MojoLayoutTestHelper.name); + interceptor.start(); + document.body.removeChild(frame); + + // stop() will succeed because it is implicitly called when the execution + // context is destroyed. + interceptor.stop(); +}, "MojoInterfaceInterceptor is stopped on frame destruction"); + +</script> +</body>
diff --git a/third_party/WebKit/LayoutTests/mojo/resources/bind-intercepted-interface-in-worker.js b/third_party/WebKit/LayoutTests/mojo/resources/bind-intercepted-interface-in-worker.js new file mode 100644 index 0000000..5b15920 --- /dev/null +++ b/third_party/WebKit/LayoutTests/mojo/resources/bind-intercepted-interface-in-worker.js
@@ -0,0 +1,37 @@ +importScripts('../../resources/testharness.js'); +importScripts('file:///gen/layout_test_data/mojo/public/js/mojo_bindings.js'); +importScripts('file:///gen/content/test/data/mojo_layouttest_test.mojom.js'); + +class MojoLayoutTestHelper { + constructor() { + this.bindingSet_ = new mojo.BindingSet( + content.mojom.MojoLayoutTestHelper); + this.interceptor_ = new MojoInterfaceInterceptor( + content.mojom.MojoLayoutTestHelper.name); + this.interceptor_.oninterfacerequest = + e => this.bindingSet_.addBinding(this, e.handle); + this.interceptor_.start(); + } + + getLastString() { + return this.lastString_; + } + + reverse(message) { + this.lastString_ = message; + return Promise.resolve({ reversed: message.split('').reverse().join('') }); + } +} + +let mojoLayoutTestHelperImpl = new MojoLayoutTestHelper; + +onmessage = async () => { + let helper = new content.mojom.MojoLayoutTestHelperPtr; + Mojo.bindInterface(content.mojom.MojoLayoutTestHelper.name, + mojo.makeRequest(helper).handle); + + let response = await helper.reverse('the string'); + assert_equals(response.reversed, 'gnirts eht'); + assert_equals(mojoLayoutTestHelperImpl.getLastString(), 'the string'); + postMessage('PASS'); +};
diff --git a/third_party/WebKit/LayoutTests/platform/linux/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/linux/animations/keyframe-multiple-timing-functions-transform-expected.png index f74c696..56ac52f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-expected.txt index d869eaf..7040849 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 323 PASS, 179 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_equals: failure should set href to input expected "test-a-colon.html" but got "" +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_equals: failure should set href to input expected "test-a-colon-b.html" but got "" +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "a://b" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-xhtml-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-xhtml-expected.txt index d869eaf..7040849 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-xhtml-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/a-element-xhtml-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 323 PASS, 179 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_equals: failure should set href to input expected "test-a-colon.html" but got "" +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_equals: failure should set href to input expected "test-a-colon-b.html" but got "" +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "a://b" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/url-constructor-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/url-constructor-expected.txt index 73e29f4..f3a7da3 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/url-constructor-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/linux/external/wpt/url/url-constructor-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 497 tests; 386 PASS, 111 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 506 tests; 393 PASS, 113 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS URL.searchParams getter PASS URL.searchParams updating, clearing PASS URL.searchParams setter, invalid values @@ -548,6 +548,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +PASS Parsing: <test-a.html> against <a> +PASS Parsing: <test-a-slash.html> against <a/> +PASS Parsing: <test-a-slash-slash.html> against <a//> +PASS Parsing: <test-a-colon.html> against <a:> +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> Failed to construct 'URL': Invalid URL +PASS Parsing: <test-a-colon-b.html> against <a:b> +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> Failed to construct 'URL': Invalid URL PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png index f74c696..56ac52f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/mac/animations/keyframe-multiple-timing-functions-transform-expected.png index 1f20eba5..4537469 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-expected.txt index d869eaf..7040849 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 323 PASS, 179 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_equals: failure should set href to input expected "test-a-colon.html" but got "" +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_equals: failure should set href to input expected "test-a-colon-b.html" but got "" +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "a://b" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-xhtml-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-xhtml-expected.txt index d869eaf..7040849 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-xhtml-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/a-element-xhtml-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 323 PASS, 179 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_equals: failure should set href to input expected "test-a-colon.html" but got "" +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_equals: failure should set href to input expected "test-a-colon-b.html" but got "" +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "a://b" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/url-constructor-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/url-constructor-expected.txt index 73e29f4..f3a7da3 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/url-constructor-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/external/wpt/url/url-constructor-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 497 tests; 386 PASS, 111 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 506 tests; 393 PASS, 113 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS URL.searchParams getter PASS URL.searchParams updating, clearing PASS URL.searchParams setter, invalid values @@ -548,6 +548,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +PASS Parsing: <test-a.html> against <a> +PASS Parsing: <test-a-slash.html> against <a/> +PASS Parsing: <test-a-slash-slash.html> against <a//> +PASS Parsing: <test-a-colon.html> against <a:> +PASS Parsing: <test-a-colon-slash.html> against <a:/> +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> Failed to construct 'URL': Invalid URL +PASS Parsing: <test-a-colon-b.html> against <a:b> +PASS Parsing: <test-a-colon-slash-b.html> against <a:/b> +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> Failed to construct 'URL': Invalid URL PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png index 1f20eba5..4537469 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/win/animations/keyframe-multiple-timing-functions-transform-expected.png index 1dfb93cb..f9f9768 100644 --- a/third_party/WebKit/LayoutTests/platform/win/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-expected.txt b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-expected.txt index 9facaa7a..bbb3bac4 100644 --- a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 321 PASS, 181 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon-slash.html> against <a:/> assert_equals: href expected "a:/test-a-colon-slash.html" but got "file:///A:/test-a-colon-slash.html" +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "file:///A://test-a-colon-slash-slash.html" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon-slash-b.html> against <a:/b> assert_equals: href expected "a:/test-a-colon-slash-b.html" but got "file:///A:/test-a-colon-slash-b.html" +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "file:///A://test-a-colon-slash-slash-b.html" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-xhtml-expected.txt b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-xhtml-expected.txt index 9facaa7a..bbb3bac4 100644 --- a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-xhtml-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/a-element-xhtml-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 493 tests; 321 PASS, 172 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 502 tests; 321 PASS, 181 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS Loading data… PASS Parsing: <http://example . org> against <http://example.org/foo/bar> @@ -502,6 +502,15 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +FAIL Parsing: <test-a.html> against <a> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash.html> against <a/> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-slash-slash.html> against <a//> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon.html> against <a:> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon-slash.html> against <a:/> assert_equals: href expected "a:/test-a-colon-slash.html" but got "file:///A:/test-a-colon-slash.html" +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "file:///A://test-a-colon-slash-slash.html" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_unreached: Expected URL to fail parsing Reached unreachable code +FAIL Parsing: <test-a-colon-slash-b.html> against <a:/b> assert_equals: href expected "a:/test-a-colon-slash-b.html" but got "file:///A:/test-a-colon-slash-b.html" +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "file:///A://test-a-colon-slash-slash-b.html" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/url-constructor-expected.txt b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/url-constructor-expected.txt index 566dee6e..a536283e 100644 --- a/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/url-constructor-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/external/wpt/url/url-constructor-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 497 tests; 386 PASS, 111 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 506 tests; 389 PASS, 117 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS URL.searchParams getter PASS URL.searchParams updating, clearing PASS URL.searchParams setter, invalid values @@ -548,6 +548,19 @@ PASS Parsing: <http://example.org/test?%GH> against <about:blank> PASS Parsing: <http://example.org/test?a#%EF> against <about:blank> PASS Parsing: <http://example.org/test?a#%GH> against <about:blank> +PASS Parsing: <test-a.html> against <a> +PASS Parsing: <test-a-slash.html> against <a/> +PASS Parsing: <test-a-slash-slash.html> against <a//> +FAIL Parsing: <test-a-colon.html> against <a:> assert_throws: function "function () { + bURL(expected.input, expected.base) + }" did not throw +FAIL Parsing: <test-a-colon-slash.html> against <a:/> assert_equals: href expected "a:/test-a-colon-slash.html" but got "file:///A:/test-a-colon-slash.html" +FAIL Parsing: <test-a-colon-slash-slash.html> against <a://> assert_equals: href expected "a:///test-a-colon-slash-slash.html" but got "file:///A://test-a-colon-slash-slash.html" +FAIL Parsing: <test-a-colon-b.html> against <a:b> assert_throws: function "function () { + bURL(expected.input, expected.base) + }" did not throw +FAIL Parsing: <test-a-colon-slash-b.html> against <a:/b> assert_equals: href expected "a:/test-a-colon-slash-b.html" but got "file:///A:/test-a-colon-slash-b.html" +FAIL Parsing: <test-a-colon-slash-slash-b.html> against <a://b> assert_equals: href expected "a://b/test-a-colon-slash-slash-b.html" but got "file:///A://test-a-colon-slash-slash-b.html" PASS Parsing: <http://example.org/test?a#b\0c> against <about:blank> Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png index 1dfb93cb..f9f9768 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/threaded/animations/keyframe-multiple-timing-functions-transform-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/sensor/accelerometer.html b/third_party/WebKit/LayoutTests/sensor/accelerometer.html index a8b5526..0c89932 100644 --- a/third_party/WebKit/LayoutTests/sensor/accelerometer.html +++ b/third_party/WebKit/LayoutTests/sensor/accelerometer.html
@@ -34,6 +34,12 @@ sensor.timestamp != null; } -runGenericSensorTests(Accelerometer, update_sensor_reading, verify_sensor_reading); +runGenericSensorTests(Accelerometer, + update_sensor_reading, + verify_sensor_reading); + +runGenericSensorTests(LinearAccelerationSensor, + update_sensor_reading, + verify_sensor_reading); </script>
diff --git a/third_party/WebKit/LayoutTests/sensor/idl-LinearAccelerationSensor.html b/third_party/WebKit/LayoutTests/sensor/idl-LinearAccelerationSensor.html new file mode 100644 index 0000000..55fe0a79 --- /dev/null +++ b/third_party/WebKit/LayoutTests/sensor/idl-LinearAccelerationSensor.html
@@ -0,0 +1,9 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script> +test(function() { + // Test that LinearAccelerationSensor interface exists + assert_true('LinearAccelerationSensor' in window); +}, 'Test that the LinearAccelerationSensor interface is present'); +</script>
diff --git a/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js b/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js index c749a64..502316d 100644 --- a/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js +++ b/third_party/WebKit/LayoutTests/sensor/resources/generic-sensor-tests.js
@@ -385,7 +385,10 @@ // next time, the fast sensor (30 Hz) has been notified // for int(30/9) = 3 times. let elapsedUpdates = mockSensor.reading_updates_count() - readingUpdatesCounter; - assert_equals(fastSensorNotifiedCounter, elapsedUpdates); + // Approximation because 'slowSensor.onreading' is sometimes + // called before 'fastSensor.onreading', in this case + // 'fastSensorNotifiedCounter == elapsedUpdates - 1'. + assert_approx_equals(fastSensorNotifiedCounter, elapsedUpdates, 1); fastSensor.stop(); slowSensor.stop(); resolve(mockSensor);
diff --git a/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js b/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js index 98648a0..0aca665d 100644 --- a/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js +++ b/third_party/WebKit/LayoutTests/sensor/resources/sensor-helpers.js
@@ -21,8 +21,8 @@ return define('Generic Sensor API mocks', [ 'mojo/public/js/core', 'mojo/public/js/bindings', - 'device/generic_sensor/public/interfaces/sensor_provider.mojom', - 'device/generic_sensor/public/interfaces/sensor.mojom', + 'services/device/public/interfaces/sensor_provider.mojom', + 'services/device/public/interfaces/sensor.mojom', 'services/device/public/interfaces/constants.mojom', ], (core, bindings, sensor_provider, sensor, deviceConstants) => {
diff --git a/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash-expected.html b/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash-expected.html deleted file mode 100644 index 0a07779b..0000000 --- a/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash-expected.html +++ /dev/null
@@ -1 +0,0 @@ -<body onload="document.execCommand('selectAll')">PASS</body>
diff --git a/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash.html b/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash.html index fc2297d64..4a61f67 100644 --- a/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash.html +++ b/third_party/WebKit/LayoutTests/svg/foreignObject/viewport-foreignobject-crash.html
@@ -1,6 +1,9 @@ <html> <body> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> +var t = async_test(); var script = document.getElementsByTagName("script")[0]; script.parentNode.removeChild(script); @@ -13,7 +16,7 @@ document.execCommand('InsertHTML', false, document.body.innerHTML); if (count == 1) { document.removeEventListener("DOMNodeInserted", crash, false); - document.body.innerHTML = "PASS"; + t.done(); return; } count += 1;
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 612e998..9fd330b 100644 --- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -691,6 +691,59 @@ method start setter onmessage setter onmessageerror +interface Mojo + static method bindInterface + static method createDataPipe + static method createMessagePipe + static method createSharedBuffer + attribute @@toStringTag + attribute RESULT_ABORTED + attribute RESULT_ALREADY_EXISTS + attribute RESULT_BUSY + attribute RESULT_CANCELLED + attribute RESULT_DATA_LOSS + attribute RESULT_DEADLINE_EXCEEDED + attribute RESULT_FAILED_PRECONDITION + attribute RESULT_INTERNAL + attribute RESULT_INVALID_ARGUMENT + attribute RESULT_NOT_FOUND + attribute RESULT_OK + attribute RESULT_OUT_OF_RANGE + attribute RESULT_PERMISSION_DENIED + attribute RESULT_RESOURCE_EXHAUSTED + attribute RESULT_SHOULD_WAIT + attribute RESULT_UNAVAILABLE + attribute RESULT_UNIMPLEMENTED + attribute RESULT_UNKNOWN + method constructor +interface MojoHandle + attribute @@toStringTag + method close + method constructor + method discardData + method duplicateBufferHandle + method mapBuffer + method queryData + method readData + method readMessage + method watch + method writeData + method writeMessage +interface MojoInterfaceInterceptor : EventTarget + attribute @@toStringTag + getter oninterfacerequest + method constructor + method start + method stop + setter oninterfacerequest +interface MojoInterfaceRequestEvent : Event + attribute @@toStringTag + getter handle + method constructor +interface MojoWatcher + attribute @@toStringTag + method cancel + method constructor interface NetworkInformation : EventTarget attribute @@toStringTag getter downlink
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-dedicated-worker-expected.txt index f5c0488..4232580 100644 --- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -644,6 +644,59 @@ [Worker] method start [Worker] setter onmessage [Worker] setter onmessageerror +[Worker] interface Mojo +[Worker] static method bindInterface +[Worker] static method createDataPipe +[Worker] static method createMessagePipe +[Worker] static method createSharedBuffer +[Worker] attribute @@toStringTag +[Worker] attribute RESULT_ABORTED +[Worker] attribute RESULT_ALREADY_EXISTS +[Worker] attribute RESULT_BUSY +[Worker] attribute RESULT_CANCELLED +[Worker] attribute RESULT_DATA_LOSS +[Worker] attribute RESULT_DEADLINE_EXCEEDED +[Worker] attribute RESULT_FAILED_PRECONDITION +[Worker] attribute RESULT_INTERNAL +[Worker] attribute RESULT_INVALID_ARGUMENT +[Worker] attribute RESULT_NOT_FOUND +[Worker] attribute RESULT_OK +[Worker] attribute RESULT_OUT_OF_RANGE +[Worker] attribute RESULT_PERMISSION_DENIED +[Worker] attribute RESULT_RESOURCE_EXHAUSTED +[Worker] attribute RESULT_SHOULD_WAIT +[Worker] attribute RESULT_UNAVAILABLE +[Worker] attribute RESULT_UNIMPLEMENTED +[Worker] attribute RESULT_UNKNOWN +[Worker] method constructor +[Worker] interface MojoHandle +[Worker] attribute @@toStringTag +[Worker] method close +[Worker] method constructor +[Worker] method discardData +[Worker] method duplicateBufferHandle +[Worker] method mapBuffer +[Worker] method queryData +[Worker] method readData +[Worker] method readMessage +[Worker] method watch +[Worker] method writeData +[Worker] method writeMessage +[Worker] interface MojoInterfaceInterceptor : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter oninterfacerequest +[Worker] method constructor +[Worker] method start +[Worker] method stop +[Worker] setter oninterfacerequest +[Worker] interface MojoInterfaceRequestEvent : Event +[Worker] attribute @@toStringTag +[Worker] getter handle +[Worker] method constructor +[Worker] interface MojoWatcher +[Worker] attribute @@toStringTag +[Worker] method cancel +[Worker] method constructor [Worker] interface NetworkInformation : EventTarget [Worker] attribute @@toStringTag [Worker] getter downlink
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt index 1eb4b88..b7d4343 100644 --- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt
@@ -3893,6 +3893,9 @@ interface KeyframeEffectReadOnly : AnimationEffectReadOnly attribute @@toStringTag method constructor +interface LinearAccelerationSensor : Accelerometer + attribute @@toStringTag + method constructor interface Location attribute @@toStringTag method constructor @@ -4872,13 +4875,15 @@ getter responseEnd getter responseStart getter secureConnectionStart + getter serverTiming getter transferSize getter workerStart method constructor -interface PerformanceServerTiming : PerformanceEntry +interface PerformanceServerTiming attribute @@toStringTag getter description getter metric + getter value method constructor interface PerformanceTiming attribute @@toStringTag
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-shared-worker-expected.txt index 20e1ef5..3f242fd 100644 --- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -639,6 +639,59 @@ [Worker] method start [Worker] setter onmessage [Worker] setter onmessageerror +[Worker] interface Mojo +[Worker] static method bindInterface +[Worker] static method createDataPipe +[Worker] static method createMessagePipe +[Worker] static method createSharedBuffer +[Worker] attribute @@toStringTag +[Worker] attribute RESULT_ABORTED +[Worker] attribute RESULT_ALREADY_EXISTS +[Worker] attribute RESULT_BUSY +[Worker] attribute RESULT_CANCELLED +[Worker] attribute RESULT_DATA_LOSS +[Worker] attribute RESULT_DEADLINE_EXCEEDED +[Worker] attribute RESULT_FAILED_PRECONDITION +[Worker] attribute RESULT_INTERNAL +[Worker] attribute RESULT_INVALID_ARGUMENT +[Worker] attribute RESULT_NOT_FOUND +[Worker] attribute RESULT_OK +[Worker] attribute RESULT_OUT_OF_RANGE +[Worker] attribute RESULT_PERMISSION_DENIED +[Worker] attribute RESULT_RESOURCE_EXHAUSTED +[Worker] attribute RESULT_SHOULD_WAIT +[Worker] attribute RESULT_UNAVAILABLE +[Worker] attribute RESULT_UNIMPLEMENTED +[Worker] attribute RESULT_UNKNOWN +[Worker] method constructor +[Worker] interface MojoHandle +[Worker] attribute @@toStringTag +[Worker] method close +[Worker] method constructor +[Worker] method discardData +[Worker] method duplicateBufferHandle +[Worker] method mapBuffer +[Worker] method queryData +[Worker] method readData +[Worker] method readMessage +[Worker] method watch +[Worker] method writeData +[Worker] method writeMessage +[Worker] interface MojoInterfaceInterceptor : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter oninterfacerequest +[Worker] method constructor +[Worker] method start +[Worker] method stop +[Worker] setter oninterfacerequest +[Worker] interface MojoInterfaceRequestEvent : Event +[Worker] attribute @@toStringTag +[Worker] getter handle +[Worker] method constructor +[Worker] interface MojoWatcher +[Worker] attribute @@toStringTag +[Worker] method cancel +[Worker] method constructor [Worker] interface NetworkInformation : EventTarget [Worker] attribute @@toStringTag [Worker] getter downlink
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/external/wpt/service-workers/README.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/external/wpt/service-workers/README.txt new file mode 100644 index 0000000..339e450 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/external/wpt/service-workers/README.txt
@@ -0,0 +1 @@ +This directory is for testing the script streaming (Tracking bug: https://crbug.com/683037).
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker-proxied/README.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker-proxied/README.txt new file mode 100644 index 0000000..339e450 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker-proxied/README.txt
@@ -0,0 +1 @@ +This directory is for testing the script streaming (Tracking bug: https://crbug.com/683037).
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker/README.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker/README.txt new file mode 100644 index 0000000..339e450 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/fetch/serviceworker/README.txt
@@ -0,0 +1 @@ +This directory is for testing the script streaming (Tracking bug: https://crbug.com/683037).
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/serviceworker/README.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/serviceworker/README.txt new file mode 100644 index 0000000..339e450 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-script-streaming/http/tests/serviceworker/README.txt
@@ -0,0 +1 @@ +This directory is for testing the script streaming (Tracking bug: https://crbug.com/683037).
diff --git a/third_party/WebKit/LayoutTests/vr/requestAnimationFrame_consistentTimestamps.html b/third_party/WebKit/LayoutTests/vr/requestAnimationFrame_consistentTimestamps.html new file mode 100644 index 0000000..71dc384 --- /dev/null +++ b/third_party/WebKit/LayoutTests/vr/requestAnimationFrame_consistentTimestamps.html
@@ -0,0 +1,68 @@ +<!DOCTYPE html> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="../resources/mojo-helpers.js"></script> +<script src="resources/fake-vr-displays.js"></script> +<script src="resources/mock-vr-service.js"></script> +<canvas id="webgl-canvas"></canvas> +<script src="resources/presentation-setup.js"></script> +<script> +let fakeDisplays = fakeVRDisplays(); + +// This test verifies that timestamps are consistent when switching between +// magic window and presentation mode. + +vr_test( (t) => { + return navigator.getVRDisplays().then( (displays) => { + + let display = displays[0]; + + let usingPresentingRAF = false; + let lastTime = -1; + let lastrAFTime = -1; + let tolerance_ms = 250; + + function onAnimationFrame(time) { + var currentTime = window.performance.now(); + if (lastTime != -1) { + var timeDiff = currentTime - lastTime; + var rAFDiff = time - lastrAFTime; + if (usingPresentingRAF) { + t.step( () => { + assert_approx_equals(rAFDiff, timeDiff, tolerance_ms); + }, "timestamps not continuous"); + } + } + lastTime = currentTime; + lastrAFTime = time; + + if (usingPresentingRAF) { + t.done(); + } + if (!display.isPresenting) { + runWithUserGesture( () => { + display.requestPresent([{ source : webglCanvas }]).then( () => { + t.step( () => { + assert_true(display.isPresenting); + }, "Display should be presenting"); + usingPresentingRAF = true; + display.requestAnimationFrame(onAnimationFrame); + }, (err) => { + t.step( () => { + assert_unreached(err); + }, "requestPresent rejected"); + }); + }); + } + } + display.requestAnimationFrame(onAnimationFrame); + }, (err) => { + t.step( () => { + assert_unreached("getVRDisplays rejected"); + }); + t.done(); + }); +}, [fakeDisplays["Pixel"]], +"requestAnimationFrame timestamp is consistent between magic window and presentation."); + +</script>
diff --git a/third_party/WebKit/LayoutTests/vr/resources/mock-vr-service.js b/third_party/WebKit/LayoutTests/vr/resources/mock-vr-service.js index 066ba62..040f98d4 100644 --- a/third_party/WebKit/LayoutTests/vr/resources/mock-vr-service.js +++ b/third_party/WebKit/LayoutTests/vr/resources/mock-vr-service.js
@@ -62,7 +62,6 @@ class MockVRPresentationProvider { constructor() { - this.timeDelta_ = 0; this.binding_ = new bindings.Binding(vr_service.VRPresentationProvider, this); this.pose_ = null; @@ -91,16 +90,22 @@ this.pose_.poseIndex++; } + // Convert current document time to monotonic time. + var now = window.performance.now() / 1000.0; + var diff = + now - window.internals.monotonicTimeToZeroBasedDocumentTime(now); + now += diff; + now *= 1000000; + let retval = Promise.resolve({ pose: this.pose_, time: { - microseconds: this.timeDelta_, + microseconds: now, }, frame_id: 0, status: vr_service.VRPresentationProvider.VSyncStatus.SUCCESS, }); - this.timeDelta_ += 1000.0 / 60.0; return retval; } initPose() {
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 84c6ce2d..7db7f71b 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -644,6 +644,59 @@ [Worker] method start [Worker] setter onmessage [Worker] setter onmessageerror +[Worker] interface Mojo +[Worker] static method bindInterface +[Worker] static method createDataPipe +[Worker] static method createMessagePipe +[Worker] static method createSharedBuffer +[Worker] attribute @@toStringTag +[Worker] attribute RESULT_ABORTED +[Worker] attribute RESULT_ALREADY_EXISTS +[Worker] attribute RESULT_BUSY +[Worker] attribute RESULT_CANCELLED +[Worker] attribute RESULT_DATA_LOSS +[Worker] attribute RESULT_DEADLINE_EXCEEDED +[Worker] attribute RESULT_FAILED_PRECONDITION +[Worker] attribute RESULT_INTERNAL +[Worker] attribute RESULT_INVALID_ARGUMENT +[Worker] attribute RESULT_NOT_FOUND +[Worker] attribute RESULT_OK +[Worker] attribute RESULT_OUT_OF_RANGE +[Worker] attribute RESULT_PERMISSION_DENIED +[Worker] attribute RESULT_RESOURCE_EXHAUSTED +[Worker] attribute RESULT_SHOULD_WAIT +[Worker] attribute RESULT_UNAVAILABLE +[Worker] attribute RESULT_UNIMPLEMENTED +[Worker] attribute RESULT_UNKNOWN +[Worker] method constructor +[Worker] interface MojoHandle +[Worker] attribute @@toStringTag +[Worker] method close +[Worker] method constructor +[Worker] method discardData +[Worker] method duplicateBufferHandle +[Worker] method mapBuffer +[Worker] method queryData +[Worker] method readData +[Worker] method readMessage +[Worker] method watch +[Worker] method writeData +[Worker] method writeMessage +[Worker] interface MojoInterfaceInterceptor : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter oninterfacerequest +[Worker] method constructor +[Worker] method start +[Worker] method stop +[Worker] setter oninterfacerequest +[Worker] interface MojoInterfaceRequestEvent : Event +[Worker] attribute @@toStringTag +[Worker] getter handle +[Worker] method constructor +[Worker] interface MojoWatcher +[Worker] attribute @@toStringTag +[Worker] method cancel +[Worker] method constructor [Worker] interface NavigationPreloadManager [Worker] attribute @@toStringTag [Worker] method constructor
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 3343c104..640a986 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -3893,6 +3893,9 @@ interface KeyframeEffectReadOnly : AnimationEffectReadOnly attribute @@toStringTag method constructor +interface LinearAccelerationSensor : Accelerometer + attribute @@toStringTag + method constructor interface Location attribute @@toStringTag method constructor @@ -4879,13 +4882,15 @@ getter responseEnd getter responseStart getter secureConnectionStart + getter serverTiming getter transferSize getter workerStart method constructor -interface PerformanceServerTiming : PerformanceEntry +interface PerformanceServerTiming attribute @@toStringTag getter description getter metric + getter value method constructor interface PerformanceTiming attribute @@toStringTag
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt index e1511a29..41bc19b 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -639,6 +639,59 @@ [Worker] method start [Worker] setter onmessage [Worker] setter onmessageerror +[Worker] interface Mojo +[Worker] static method bindInterface +[Worker] static method createDataPipe +[Worker] static method createMessagePipe +[Worker] static method createSharedBuffer +[Worker] attribute @@toStringTag +[Worker] attribute RESULT_ABORTED +[Worker] attribute RESULT_ALREADY_EXISTS +[Worker] attribute RESULT_BUSY +[Worker] attribute RESULT_CANCELLED +[Worker] attribute RESULT_DATA_LOSS +[Worker] attribute RESULT_DEADLINE_EXCEEDED +[Worker] attribute RESULT_FAILED_PRECONDITION +[Worker] attribute RESULT_INTERNAL +[Worker] attribute RESULT_INVALID_ARGUMENT +[Worker] attribute RESULT_NOT_FOUND +[Worker] attribute RESULT_OK +[Worker] attribute RESULT_OUT_OF_RANGE +[Worker] attribute RESULT_PERMISSION_DENIED +[Worker] attribute RESULT_RESOURCE_EXHAUSTED +[Worker] attribute RESULT_SHOULD_WAIT +[Worker] attribute RESULT_UNAVAILABLE +[Worker] attribute RESULT_UNIMPLEMENTED +[Worker] attribute RESULT_UNKNOWN +[Worker] method constructor +[Worker] interface MojoHandle +[Worker] attribute @@toStringTag +[Worker] method close +[Worker] method constructor +[Worker] method discardData +[Worker] method duplicateBufferHandle +[Worker] method mapBuffer +[Worker] method queryData +[Worker] method readData +[Worker] method readMessage +[Worker] method watch +[Worker] method writeData +[Worker] method writeMessage +[Worker] interface MojoInterfaceInterceptor : EventTarget +[Worker] attribute @@toStringTag +[Worker] getter oninterfacerequest +[Worker] method constructor +[Worker] method start +[Worker] method stop +[Worker] setter oninterfacerequest +[Worker] interface MojoInterfaceRequestEvent : Event +[Worker] attribute @@toStringTag +[Worker] getter handle +[Worker] method constructor +[Worker] interface MojoWatcher +[Worker] attribute @@toStringTag +[Worker] method cancel +[Worker] method constructor [Worker] interface NavigationPreloadManager [Worker] attribute @@toStringTag [Worker] method constructor
diff --git a/third_party/WebKit/Source/bindings/modules/BUILD.gn b/third_party/WebKit/Source/bindings/modules/BUILD.gn index ca6e9c1..3e176fa 100644 --- a/third_party/WebKit/Source/bindings/modules/BUILD.gn +++ b/third_party/WebKit/Source/bindings/modules/BUILD.gn
@@ -73,9 +73,9 @@ ] deps = make_core_generated_deps + [ "//third_party/WebKit/Source/bindings/modules:modules_bindings_generated_event_interfaces" ] deps += [ - "//device/generic_sensor/public/interfaces:interfaces_blink", "//device/vr:mojo_bindings_blink", "//media/midi:mojo_blink", + "//services/device/public/interfaces:generic_sensor_blink", ] }
diff --git a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py index 541093e..713ec3e 100755 --- a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py +++ b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py
@@ -27,7 +27,7 @@ # Aligns like a pointer (can be 32 or 64 bits) 'NamedGridLinesMap', 'OrderedNamedGridLines', 'NamedGridAreaMap', 'TransformOperations', 'Vector<CSSPropertyID>', 'Vector<GridTrackSize>', 'GridPosition', 'AtomicString', - 'RefPtr', 'DataPersistent', 'Persistent', 'std::unique_ptr', + 'RefPtr', 'Persistent', 'std::unique_ptr', 'Vector<String>', 'Font', 'FillLayer', 'NinePieceImage', # Aligns like float 'StyleOffsetRotation', 'TransformOrigin', 'ScrollPadding', 'ScrollSnapMargin', 'LengthBox', @@ -162,7 +162,7 @@ def __init__(self, field_role, name_for_methods, property_name, type_name, wrapper_pointer_name, field_template, size, default_value, custom_copy, custom_compare, mutable, - getter_method_name, setter_method_name, initial_method_name, **kwargs): + getter_method_name, setter_method_name, initial_method_name, default_generated_functions, **kwargs): """Creates a new field.""" self.name = class_member_name(name_for_methods) self.property_name = property_name @@ -199,7 +199,7 @@ self.internal_setter_method_name = method_name(join_name(setter_method_name, 'Internal')) self.initial_method_name = initial_method_name self.resetter_method_name = method_name(join_name('Reset', name_for_methods)) - + self.default_generated_functions = default_generated_functions # If the size of the field is not None, it means it is a bit field self.is_bit_field = self.size is not None @@ -400,6 +400,7 @@ getter_method_name=property_['getter'], setter_method_name=property_['setter'], initial_method_name=property_['initial'], + default_generated_functions=property_['default_generated_functions'], ) @@ -424,6 +425,7 @@ getter_method_name=method_name(name_for_methods), setter_method_name=method_name(join_name('set', name_for_methods)), initial_method_name=method_name(join_name('initial', name_for_methods)), + default_generated_functions=property_["default_generated_functions"] )
diff --git a/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl index c7261c7..c5cf4494 100644 --- a/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/ComputedStyleBase.h.tmpl
@@ -11,7 +11,6 @@ #include "core/style/ComputedStyleConstants.h" #include "core/style/DataRef.h" #include "core/style/MemberCopy.h" -#include "core/style/DataPersistent.h" {% for path in include_paths %} #include "{{path}}" {% endfor %}
diff --git a/third_party/WebKit/Source/build/scripts/templates/fields/storage_only.tmpl b/third_party/WebKit/Source/build/scripts/templates/fields/storage_only.tmpl index c3c9346..6ce6baf9 100644 --- a/third_party/WebKit/Source/build/scripts/templates/fields/storage_only.tmpl +++ b/third_party/WebKit/Source/build/scripts/templates/fields/storage_only.tmpl
@@ -3,15 +3,29 @@ {% macro decl_public_methods(field) -%} {{base.decl_initial_method(field)}} -// Getters and setters not generated +// Only specified functions are generated +{% if 'getter' in field.default_generated_functions %} +{{base.decl_getter_method(field)}} +{% endif %} +{% if 'setter' in field.default_generated_functions %} +{{base.decl_setter_method(field)}} +{% endif %} +{% if 'reset' in field.default_generated_functions %} +{{base.decl_resetter_method(field)}} +{% endif %} +{% if 'mutable' in field.default_generated_functions %} +{{base.decl_mutable_method(field)}} +{% endif %} {%- endmacro %} {% macro decl_protected_methods(field) -%} +{% if 'getter' not in field.default_generated_functions %} {{base.decl_internal_getter_method(field)}} -{% if not field.wrapper_pointer_name %} +{% endif %} +{% if not field.wrapper_pointer_name and 'setter' not in field.default_generated_functions %} {{base.decl_internal_setter_method(field)}} {% endif %} -{% if not field.is_bit_field -%} +{% if not field.is_bit_field and 'setter' not in field.default_generated_functions -%} void {{field.internal_setter_method_name}}({{field.type_name}}&& v) { {% if field.group.parent %} if (!({{getter_expression(field)}} == v)) @@ -20,7 +34,9 @@ {{field.name}} = std::move(v); {% endif %} } +{% if 'mutable' not in field.default_generated_functions %} {{base.decl_mutable_method(field)}} +{% endif %} {%- endif %} {%- endmacro %}
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index bd7fb58..f803a5e 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -334,7 +334,7 @@ "events/UIEvent.idl", "events/WheelEvent.idl", "html/track/TrackEvent.idl", - "mojo/testing/MojoInterfaceRequestEvent.idl", + "mojo/test/MojoInterfaceRequestEvent.idl", ] output_file = "core/EventInterfaces.json5" } @@ -586,7 +586,6 @@ "$blink_core_output_dir/css/properties/CSSPropertyAPIZoom.h", "$blink_core_output_dir/css/properties/CSSPropertyDescriptor.cpp", "$blink_core_output_dir/css/properties/CSSPropertyDescriptor.h", - "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIAnimation.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIBorderRadius.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIBorderSpacing.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIColumns.h", @@ -596,7 +595,6 @@ "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIOverflow.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIOffset.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPITextDecoration.h", - "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPITransition.h", "$blink_core_output_dir/css/properties/CSSShorthandPropertyAPIWebkitMarginCollapse.h", ] }
diff --git a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp index 6f39102..807bb6b 100644 --- a/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp +++ b/third_party/WebKit/Source/core/animation/ListInterpolationFunctions.cpp
@@ -13,6 +13,8 @@ DEFINE_NON_INTERPOLABLE_VALUE_TYPE(NonInterpolableList); +const size_t kRepeatableListMaxLength = 1000; + bool ListInterpolationFunctions::EqualValues( const InterpolationValue& a, const InterpolationValue& b, @@ -55,7 +57,14 @@ if (length_matching_strategy == ListInterpolationFunctions::LengthMatchingStrategy:: kLowestCommonMultiple) { - return lowestCommonMultiple(start_length, end_length); + // Combining the length expansion of lowestCommonMultiple with CSS + // transitions has the potential to create pathological cases where this + // algorithm compounds upon itself as the user starts transitions on already + // animating values multiple times. This maximum limit is to avoid locking + // up users' systems with memory consumption in the event that this occurs. + // See crbug.com/739197 for more context. + return std::min(kRepeatableListMaxLength, + lowestCommonMultiple(start_length, end_length)); } DCHECK_EQ(length_matching_strategy, ListInterpolationFunctions::LengthMatchingStrategy::kPadToLargest);
diff --git a/third_party/WebKit/Source/core/core_idl_files.gni b/third_party/WebKit/Source/core/core_idl_files.gni index cbc6cad..ecf084c 100644 --- a/third_party/WebKit/Source/core/core_idl_files.gni +++ b/third_party/WebKit/Source/core/core_idl_files.gni
@@ -284,8 +284,8 @@ "mojo/Mojo.idl", "mojo/MojoHandle.idl", "mojo/MojoWatcher.idl", - "mojo/testing/MojoInterfaceInterceptor.idl", - "mojo/testing/MojoInterfaceRequestEvent.idl", + "mojo/test/MojoInterfaceInterceptor.idl", + "mojo/test/MojoInterfaceRequestEvent.idl", "page/PagePopupController.idl", "page/scrolling/ScrollState.idl", "page/scrolling/ScrollStateCallback.idl", @@ -584,7 +584,7 @@ "mojo/MojoReadMessageResult.idl", "mojo/MojoWriteDataOptions.idl", "mojo/MojoWriteDataResult.idl", - "mojo/testing/MojoInterfaceRequestEventInit.idl", + "mojo/test/MojoInterfaceRequestEventInit.idl", "offscreencanvas/ImageEncodeOptions.idl", "page/scrolling/ScrollStateInit.idl", "timing/PerformanceObserverInit.idl",
diff --git a/third_party/WebKit/Source/core/css/BUILD.gn b/third_party/WebKit/Source/core/css/BUILD.gn index 88e8273..61763c6 100644 --- a/third_party/WebKit/Source/core/css/BUILD.gn +++ b/third_party/WebKit/Source/core/css/BUILD.gn
@@ -506,9 +506,6 @@ "properties/CSSPropertyAnimationIterationCountUtils.h", "properties/CSSPropertyAnimationNameUtils.cpp", "properties/CSSPropertyAnimationNameUtils.h", - "properties/CSSPropertyAnimationTimingFunctionUtils.cpp", - "properties/CSSPropertyAnimationTimingFunctionUtils.h", - "properties/CSSPropertyAnimationUtils.h", "properties/CSSPropertyBorderImageUtils.cpp", "properties/CSSPropertyBorderImageUtils.h", "properties/CSSPropertyBoxShadowUtils.cpp", @@ -536,7 +533,6 @@ "properties/CSSPropertyTransitionPropertyUtils.h", "properties/CSSPropertyWebkitBorderWidthUtils.cpp", "properties/CSSPropertyWebkitBorderWidthUtils.h", - "properties/CSSShorthandPropertyAPIAnimation.cpp", "properties/CSSShorthandPropertyAPIBorderRadius.cpp", "properties/CSSShorthandPropertyAPIBorderSpacing.cpp", "properties/CSSShorthandPropertyAPIColumns.cpp", @@ -546,7 +542,6 @@ "properties/CSSShorthandPropertyAPIOffset.cpp", "properties/CSSShorthandPropertyAPIOverflow.cpp", "properties/CSSShorthandPropertyAPITextDecoration.cpp", - "properties/CSSShorthandPropertyAPITransition.cpp", "properties/CSSShorthandPropertyAPIWebkitMarginCollapse.cpp", "resolver/AnimatedStyleBuilder.cpp", "resolver/AnimatedStyleBuilder.h",
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index 5fe54adc..b23c83c 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -117,7 +117,7 @@ // Can only be set if the field template is storage_only. wrapper_pointer_name: { valid_type: "str", - valid_values: ["RefPtr", "Persistent", "std::unique_ptr", "DataPersistent"], + valid_values: ["RefPtr", "Persistent", "std::unique_ptr"], }, // - keywords: ["keyword1", "keyword2"] @@ -237,7 +237,16 @@ }, type_name: { }, - + // The default_generated_functions property will allow us to set + // the functions we would like to auto generate so that we wont have + // to implement all of the public function of storage-only in case + // some of them are trivial. + // initial function will always be generated by default + default_generated_functions: { + default: [], + valid_type: "list", + valid_values: ["getter", "setter", "reset", "mutable"], + }, // - converter: "ConvertRadius" // The StyleBuilder will call the specified function on StyleBuilderConverter // to convert a CSSValue to an appropriate platform value @@ -602,6 +611,7 @@ type_name: "float", default_value: "1.0", field_group: "visual", + default_generated_functions: ["getter"], }, { @@ -649,9 +659,9 @@ runtime_flag: "CSSBackdropFilter", field_template: "storage_only", type_name: "StyleFilterData", - field_group: "rare-non-inherited", - default_value: "DataPersistent<StyleFilterData>()", - wrapper_pointer_name: "DataPersistent", + field_group: "rare-non-inherited->backdrop-filter-ops", + default_value: "StyleFilterData::Create()", + wrapper_pointer_name: "Persistent", include_paths: ["core/style/StyleFilterData.h"], }, { @@ -684,6 +694,7 @@ type_name: "StyleColor", default_value: "StyleColor(Color::kTransparent)", field_group: "background", + default_generated_functions: ["setter"], }, { name: "background-image", @@ -1051,6 +1062,7 @@ type_name: "LengthBox", default_value: "LengthBox()", field_group: "visual", + default_generated_functions: ["getter"], }, { name: "clip-path", @@ -1107,6 +1119,7 @@ field_group: "rare-non-inherited", field_size: 4, default_value: "kContainsNone", + default_generated_functions: ["getter","setter"], }, { name: "content", @@ -1226,10 +1239,10 @@ converter: "ConvertFilterOperations", interpolable: true, field_template: "storage_only", - type_name: "StyleFilterData", - field_group: "rare-non-inherited", - default_value: "DataPersistent<StyleFilterData>()", - wrapper_pointer_name: "DataPersistent", + type_name : "StyleFilterData", + field_group: "rare-non-inherited->filter-ops", + default_value: "StyleFilterData::Create()", + wrapper_pointer_name: "Persistent", include_paths: ["core/style/StyleFilterData.h"], }, { @@ -1324,6 +1337,7 @@ default_value: "kAutoFlowRow", field_size: 4, // TODO(shend): Make this use "kGridAutoFlowBits". field_group: "rare-non-inherited->grid", + default_generated_functions: ["setter"], }, { name: "grid-auto-rows", @@ -1655,6 +1669,7 @@ { name: "marker-end", api_class: "CSSPropertyAPIMarker", + api_methods: ["parseSingleValue"], converter: "ConvertFragmentIdentifier", inherited: true, name_for_methods: "MarkerEndResource", @@ -1663,6 +1678,7 @@ { name: "marker-mid", api_class: "CSSPropertyAPIMarker", + api_methods: ["parseSingleValue"], converter: "ConvertFragmentIdentifier", inherited: true, name_for_methods: "MarkerMidResource", @@ -1671,6 +1687,7 @@ { name: "marker-start", api_class: "CSSPropertyAPIMarker", + api_methods: ["parseSingleValue"], converter: "ConvertFragmentIdentifier", inherited: true, name_for_methods: "MarkerStartResource", @@ -1679,6 +1696,7 @@ { name: "mask", api_class: "CSSPropertyAPIMarker", + api_methods: ["parseSingleValue"], converter: "ConvertFragmentIdentifier", name_for_methods: "MaskerResource", svg: true, @@ -1840,6 +1858,7 @@ type_name: "float", field_group: "rare-non-inherited", default_value: "1.0", + default_generated_functions: ["getter"], }, { name: "order", @@ -1850,6 +1869,7 @@ type_name: "int", field_group: "rare-non-inherited", default_value: "0", + default_generated_functions: ["getter"], }, { name: "orphans", @@ -1884,6 +1904,7 @@ type_name: "int", field_group: "rare-non-inherited", default_value: "0", + default_generated_functions: ["setter"], }, { name: "outline-style", @@ -2106,6 +2127,7 @@ field_group: "rare-non-inherited", field_size: 2, default_value: "kScrollBehaviorAuto", + default_generated_functions: ["getter", "setter"], }, { name: "scroll-snap-type", @@ -2341,6 +2363,7 @@ type_name: "float", field_group: "rare-non-inherited", default_value: "0.0", + default_generated_functions: ["getter"], }, { name: "shape-margin", @@ -2367,6 +2390,7 @@ default_value: "nullptr", wrapper_pointer_name: "Persistent", include_paths: ["core/style/ShapeValue.h"], + default_generated_functions: ["setter"], }, { name: "shape-rendering", @@ -2479,7 +2503,7 @@ field_template: "keyword", keywords: [ "auto", "fixed" - ] + ], }, { name: "tab-size", @@ -2571,6 +2595,7 @@ default_value: "TextDecorationSkip::kObjects", field_size: 3, field_group: "rare-inherited", + default_generated_functions: ["getter", "setter"], }, { name: "text-decoration-style", @@ -2685,6 +2710,7 @@ field_size: 6, // TODO(shend): Make this use "kTouchActionBits". default_value: "TouchAction::kTouchActionAuto", include_paths: ["platform/graphics/TouchAction.h"], + default_generated_functions: ["getter", "setter"], }, { name: "transform", @@ -2698,7 +2724,8 @@ type_name: "TransformOperations", field_group: "rare-non-inherited->transform", default_value: "EmptyTransformOperations()", - include_paths: ["platform/transforms/TransformOperations.h"] + include_paths: ["platform/transforms/TransformOperations.h"], + default_generated_functions: ["getter", "setter"], }, { name: "transform-box", @@ -2822,6 +2849,7 @@ field_group: "rare-non-inherited", default_value: "kNoControlPart", field_size: 6, + default_generated_functions: ["getter", "setter"], }, { name: "-webkit-app-region", @@ -2928,6 +2956,7 @@ field_template: "storage_only", default_value: "1", field_group: "rare-non-inherited->deprecated-flexible-box", + default_generated_functions: ["getter"], }, { name: "-webkit-box-orient", @@ -2965,6 +2994,7 @@ field_template: "storage_only", default_value: "1", field_group: "rare-non-inherited->multi-col", + default_generated_functions: ["getter"], }, { name: "column-gap", @@ -2977,6 +3007,7 @@ field_template: "storage_only", default_value: "0.0f", field_group: "rare-non-inherited->multi-col", + default_generated_functions: ["getter"], }, { name: "column-rule-color", @@ -3031,6 +3062,7 @@ type_name: "float", default_value: "0.0f", field_group: "rare-non-inherited->multi-col", + default_generated_functions: ["getter"], }, { name: "-webkit-highlight", @@ -3416,7 +3448,8 @@ type_name: "int", field_template: "storage_only", field_group: "box", - default_value: "0" + default_value: "0", + default_generated_functions: ["getter"], }, // CSS logical props @@ -3666,8 +3699,6 @@ { name: "animation", longhands: ["animation-name", "animation-duration", "animation-timing-function", "animation-delay", "animation-iteration-count", "animation-direction", "animation-fill-mode", "animation-play-state"], - api_class: true, - api_methods: ["parseShorthand"], }, { name: "background", @@ -3876,8 +3907,6 @@ { name: "transition", longhands: ["transition-property", "transition-duration", "transition-timing-function", "transition-delay"], - api_class: true, - api_methods: ["parseShorthand"], }, { name: "-webkit-border-after",
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 b/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 index 3be5ad7..6b04d51 100644 --- a/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5 +++ b/third_party/WebKit/Source/core/css/ComputedStyleDiffFunctions.json5
@@ -352,12 +352,15 @@ }, { name: "UpdatePropertySpecificDifferencesFilter", - fields_to_diff: ["filter"], predicates_to_test: [ { predicate: "a.ReflectionDataEquivalent(b)", field_dependencies: ["-webkit-box-reflect"] }, + { + predicate: "a.FilterDataEquivalent(b)", + field_dependencies: ["filter"] + }, ] }, { @@ -379,7 +382,12 @@ }, { name: "UpdatePropertySpecificDifferencesBackdropFilter", - fields_to_diff: ["backdrop-filter"], + predicates_to_test: [ + { + predicate: "a.BackdropFilterDataEquivalent(b)", + field_dependencies: ["backdrop-filter"] + }, + ] }, { name: "UpdatePropertySpecificDifferencesTextDecorationOrColor",
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp index 8e314d1..d69df9f 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.cpp
@@ -22,6 +22,7 @@ #include "core/css/CSSReflectValue.h" #include "core/css/CSSShadowValue.h" #include "core/css/CSSStringValue.h" +#include "core/css/CSSTimingFunctionValue.h" #include "core/css/CSSURIValue.h" #include "core/css/CSSUnicodeRangeValue.h" #include "core/css/CSSUnsetValue.h" @@ -34,7 +35,8 @@ #include "core/css/parser/CSSPropertyParserHelpers.h" #include "core/css/parser/CSSVariableParser.h" #include "core/css/properties/CSSPropertyAlignmentUtils.h" -#include "core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h" +#include "core/css/properties/CSSPropertyAnimationIterationCountUtils.h" +#include "core/css/properties/CSSPropertyAnimationNameUtils.h" #include "core/css/properties/CSSPropertyBorderImageUtils.h" #include "core/css/properties/CSSPropertyBoxShadowUtils.h" #include "core/css/properties/CSSPropertyDescriptor.h" @@ -43,6 +45,7 @@ #include "core/css/properties/CSSPropertyMarginUtils.h" #include "core/css/properties/CSSPropertyOffsetRotateUtils.h" #include "core/css/properties/CSSPropertyPositionUtils.h" +#include "core/css/properties/CSSPropertyTransitionPropertyUtils.h" #include "core/css/properties/CSSPropertyWebkitBorderWidthUtils.h" #include "core/frame/UseCounter.h" #include "core/layout/LayoutTheme.h" @@ -308,6 +311,192 @@ return ConsumeString(range); } +static CSSValue* ConsumeSteps(CSSParserTokenRange& range) { + DCHECK_EQ(range.Peek().FunctionId(), CSSValueSteps); + CSSParserTokenRange range_copy = range; + CSSParserTokenRange args = ConsumeFunction(range_copy); + + CSSPrimitiveValue* steps = ConsumePositiveInteger(args); + if (!steps) + return nullptr; + + StepsTimingFunction::StepPosition position = + StepsTimingFunction::StepPosition::END; + if (ConsumeCommaIncludingWhitespace(args)) { + switch (args.ConsumeIncludingWhitespace().Id()) { + case CSSValueMiddle: + if (!RuntimeEnabledFeatures::WebAnimationsAPIEnabled()) + return nullptr; + position = StepsTimingFunction::StepPosition::MIDDLE; + break; + case CSSValueStart: + position = StepsTimingFunction::StepPosition::START; + break; + case CSSValueEnd: + position = StepsTimingFunction::StepPosition::END; + break; + default: + return nullptr; + } + } + + if (!args.AtEnd()) + return nullptr; + + range = range_copy; + return CSSStepsTimingFunctionValue::Create(steps->GetIntValue(), position); +} + +static CSSValue* ConsumeFrames(CSSParserTokenRange& range) { + DCHECK_EQ(range.Peek().FunctionId(), CSSValueFrames); + CSSParserTokenRange range_copy = range; + CSSParserTokenRange args = ConsumeFunction(range_copy); + + CSSPrimitiveValue* frames = ConsumePositiveInteger(args); + if (!frames) + return nullptr; + + int frames_int = frames->GetIntValue(); + if (frames_int <= 1) + return nullptr; + + if (!args.AtEnd()) + return nullptr; + + range = range_copy; + return CSSFramesTimingFunctionValue::Create(frames_int); +} + +static CSSValue* ConsumeCubicBezier(CSSParserTokenRange& range) { + DCHECK_EQ(range.Peek().FunctionId(), CSSValueCubicBezier); + CSSParserTokenRange range_copy = range; + CSSParserTokenRange args = ConsumeFunction(range_copy); + + double x1, y1, x2, y2; + if (ConsumeNumberRaw(args, x1) && x1 >= 0 && x1 <= 1 && + ConsumeCommaIncludingWhitespace(args) && ConsumeNumberRaw(args, y1) && + ConsumeCommaIncludingWhitespace(args) && ConsumeNumberRaw(args, x2) && + x2 >= 0 && x2 <= 1 && ConsumeCommaIncludingWhitespace(args) && + ConsumeNumberRaw(args, y2) && args.AtEnd()) { + range = range_copy; + return CSSCubicBezierTimingFunctionValue::Create(x1, y1, x2, y2); + } + + return nullptr; +} + +static CSSValue* ConsumeAnimationTimingFunction(CSSParserTokenRange& range) { + CSSValueID id = range.Peek().Id(); + if (id == CSSValueEase || id == CSSValueLinear || id == CSSValueEaseIn || + id == CSSValueEaseOut || id == CSSValueEaseInOut || + id == CSSValueStepStart || id == CSSValueStepEnd || + id == CSSValueStepMiddle) + return ConsumeIdent(range); + + CSSValueID function = range.Peek().FunctionId(); + if (function == CSSValueSteps) + return ConsumeSteps(range); + if (RuntimeEnabledFeatures::FramesTimingFunctionEnabled() && + function == CSSValueFrames) { + return ConsumeFrames(range); + } + if (function == CSSValueCubicBezier) + return ConsumeCubicBezier(range); + return nullptr; +} + +static CSSValue* ConsumeAnimationValue(CSSPropertyID property, + CSSParserTokenRange& range, + const CSSParserContext* context, + bool use_legacy_parsing) { + switch (property) { + case CSSPropertyAnimationDelay: + case CSSPropertyTransitionDelay: + return ConsumeTime(range, kValueRangeAll); + case CSSPropertyAnimationDirection: + return ConsumeIdent<CSSValueNormal, CSSValueAlternate, CSSValueReverse, + CSSValueAlternateReverse>(range); + case CSSPropertyAnimationDuration: + case CSSPropertyTransitionDuration: + return ConsumeTime(range, kValueRangeNonNegative); + case CSSPropertyAnimationFillMode: + return ConsumeIdent<CSSValueNone, CSSValueForwards, CSSValueBackwards, + CSSValueBoth>(range); + case CSSPropertyAnimationIterationCount: + return CSSPropertyAnimationIterationCountUtils:: + ConsumeAnimationIterationCount(range); + case CSSPropertyAnimationName: + return CSSPropertyAnimationNameUtils::ConsumeAnimationName( + range, context, use_legacy_parsing); + case CSSPropertyAnimationPlayState: + return ConsumeIdent<CSSValueRunning, CSSValuePaused>(range); + case CSSPropertyTransitionProperty: + return CSSPropertyTransitionPropertyUtils::ConsumeTransitionProperty( + range); + case CSSPropertyAnimationTimingFunction: + case CSSPropertyTransitionTimingFunction: + return ConsumeAnimationTimingFunction(range); + default: + NOTREACHED(); + return nullptr; + } +} + +bool CSSPropertyParser::ConsumeAnimationShorthand( + const StylePropertyShorthand& shorthand, + bool use_legacy_parsing, + bool important) { + const unsigned longhand_count = shorthand.length(); + CSSValueList* longhands[8]; + DCHECK_LE(longhand_count, 8u); + for (size_t i = 0; i < longhand_count; ++i) + longhands[i] = CSSValueList::CreateCommaSeparated(); + + do { + bool parsed_longhand[8] = {false}; + do { + bool found_property = false; + for (size_t i = 0; i < longhand_count; ++i) { + if (parsed_longhand[i]) + continue; + + if (CSSValue* value = + ConsumeAnimationValue(shorthand.properties()[i], range_, + context_, use_legacy_parsing)) { + parsed_longhand[i] = true; + found_property = true; + longhands[i]->Append(*value); + break; + } + } + if (!found_property) + return false; + } while (!range_.AtEnd() && range_.Peek().GetType() != kCommaToken); + + // TODO(timloh): This will make invalid longhands, see crbug.com/386459 + for (size_t i = 0; i < longhand_count; ++i) { + if (!parsed_longhand[i]) + longhands[i]->Append(*CSSInitialValue::Create()); + parsed_longhand[i] = false; + } + } while (ConsumeCommaIncludingWhitespace(range_)); + + for (size_t i = 0; i < longhand_count; ++i) { + // TODO(bugsnash): Refactor out the need to check for + // CSSPropertyTransitionProperty here when this is method implemented in the + // property APIs + if (shorthand.properties()[i] == CSSPropertyTransitionProperty && + !CSSPropertyTransitionPropertyUtils::IsValidPropertyList(*longhands[i])) + return false; + } + + for (size_t i = 0; i < longhand_count; ++i) { + AddParsedProperty(shorthand.properties()[i], shorthand.id(), *longhands[i], + important); + } + return range_.AtEnd(); +} + static CSSFunctionValue* ConsumeFilterFunction( CSSParserTokenRange& range, const CSSParserContext* context) { @@ -401,13 +590,6 @@ return list; } -static CSSValue* ConsumeNoneOrURI(CSSParserTokenRange& range, - const CSSParserContext* context) { - if (range.Peek().Id() == CSSValueNone) - return ConsumeIdent(range); - return ConsumeUrl(range, context); -} - static CSSValue* ConsumePerspective(CSSParserTokenRange& range, const CSSParserContext* context, bool use_legacy_parsing) { @@ -1121,9 +1303,7 @@ kValueRangeNonNegative); case CSSPropertyAnimationTimingFunction: case CSSPropertyTransitionTimingFunction: - return ConsumeCommaSeparatedList(CSSPropertyAnimationTimingFunctionUtils:: - ConsumeAnimationTimingFunction, - range_); + return ConsumeCommaSeparatedList(ConsumeAnimationTimingFunction, range_); case CSSPropertyGridColumnGap: case CSSPropertyGridRowGap: return ConsumeLengthOrPercent(range_, context_->Mode(), @@ -1174,11 +1354,6 @@ return CSSPropertyPositionUtils::ConsumePositionLonghand<CSSValueTop, CSSValueBottom>( range_, context_->Mode()); - case CSSPropertyMarkerStart: - case CSSPropertyMarkerMid: - case CSSPropertyMarkerEnd: - case CSSPropertyMask: - return ConsumeNoneOrURI(range_, context_); case CSSPropertyWebkitBoxFlex: return ConsumeNumber(range_, kValueRangeAll); case CSSPropertyStrokeWidth: @@ -2314,6 +2489,13 @@ } switch (property) { + case CSSPropertyAnimation: + return ConsumeAnimationShorthand( + animationShorthandForParsing(), + unresolved_property == CSSPropertyAliasWebkitAnimation, important); + case CSSPropertyTransition: + return ConsumeAnimationShorthand(transitionShorthandForParsing(), false, + important); case CSSPropertyTextDecoration: DCHECK(RuntimeEnabledFeatures::CSS3TextDecorationsEnabled()); return ConsumeShorthandGreedily(textDecorationShorthand(), important);
diff --git a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h index 4fc7e94..57ced9e 100644 --- a/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h +++ b/third_party/WebKit/Source/core/css/parser/CSSPropertyParser.h
@@ -88,6 +88,10 @@ bool Consume2Values(const StylePropertyShorthand&, bool important); bool Consume4Values(const StylePropertyShorthand&, bool important); + // Legacy parsing allows <string>s for animation-name + bool ConsumeAnimationShorthand(const StylePropertyShorthand&, + bool use_legacy_parsing, + bool important); bool ConsumeBackgroundShorthand(const StylePropertyShorthand&, bool important);
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIMarker.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIMarker.cpp index c89ec90..97eea70 100644 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIMarker.cpp +++ b/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIMarker.cpp
@@ -4,4 +4,21 @@ #include "core/css/properties/CSSPropertyAPIMarker.h" -namespace blink {} // namespace blink +#include "core/css/CSSURIValue.h" +#include "core/css/parser/CSSParserTokenRange.h" +#include "core/css/parser/CSSPropertyParserHelpers.h" + +namespace blink { + +class CSSParserLocalContext; + +const CSSValue* CSSPropertyAPIMarker::parseSingleValue( + CSSParserTokenRange& range, + const CSSParserContext& context, + const CSSParserLocalContext&) { + if (range.Peek().Id() == CSSValueNone) + return CSSPropertyParserHelpers::ConsumeIdent(range); + return CSSPropertyParserHelpers::ConsumeUrl(range, &context); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.cpp b/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.cpp deleted file mode 100644 index 57961c2..0000000 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.cpp +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h" - -#include "core/css/CSSTimingFunctionValue.h" -#include "core/css/parser/CSSPropertyParserHelpers.h" -#include "platform/RuntimeEnabledFeatures.h" - -namespace blink { - -namespace { - -CSSValue* ConsumeSteps(CSSParserTokenRange& range) { - DCHECK_EQ(range.Peek().FunctionId(), CSSValueSteps); - CSSParserTokenRange range_copy = range; - CSSParserTokenRange args = - CSSPropertyParserHelpers::ConsumeFunction(range_copy); - - CSSPrimitiveValue* steps = - CSSPropertyParserHelpers::ConsumePositiveInteger(args); - if (!steps) - return nullptr; - - StepsTimingFunction::StepPosition position = - StepsTimingFunction::StepPosition::END; - if (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args)) { - switch (args.ConsumeIncludingWhitespace().Id()) { - case CSSValueMiddle: - if (!RuntimeEnabledFeatures::WebAnimationsAPIEnabled()) - return nullptr; - position = StepsTimingFunction::StepPosition::MIDDLE; - break; - case CSSValueStart: - position = StepsTimingFunction::StepPosition::START; - break; - case CSSValueEnd: - position = StepsTimingFunction::StepPosition::END; - break; - default: - return nullptr; - } - } - - if (!args.AtEnd()) - return nullptr; - - range = range_copy; - return CSSStepsTimingFunctionValue::Create(steps->GetIntValue(), position); -} - -CSSValue* ConsumeFrames(CSSParserTokenRange& range) { - DCHECK_EQ(range.Peek().FunctionId(), CSSValueFrames); - CSSParserTokenRange range_copy = range; - CSSParserTokenRange args = - CSSPropertyParserHelpers::ConsumeFunction(range_copy); - - CSSPrimitiveValue* frames = - CSSPropertyParserHelpers::ConsumePositiveInteger(args); - if (!frames) - return nullptr; - - int frames_int = frames->GetIntValue(); - if (frames_int <= 1) - return nullptr; - - if (!args.AtEnd()) - return nullptr; - - range = range_copy; - return CSSFramesTimingFunctionValue::Create(frames_int); -} - -CSSValue* ConsumeCubicBezier(CSSParserTokenRange& range) { - DCHECK_EQ(range.Peek().FunctionId(), CSSValueCubicBezier); - CSSParserTokenRange range_copy = range; - CSSParserTokenRange args = - CSSPropertyParserHelpers::ConsumeFunction(range_copy); - - double x1, y1, x2, y2; - if (CSSPropertyParserHelpers::ConsumeNumberRaw(args, x1) && x1 >= 0 && - x1 <= 1 && - CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) && - CSSPropertyParserHelpers::ConsumeNumberRaw(args, y1) && - CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) && - CSSPropertyParserHelpers::ConsumeNumberRaw(args, x2) && x2 >= 0 && - x2 <= 1 && - CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(args) && - CSSPropertyParserHelpers::ConsumeNumberRaw(args, y2) && args.AtEnd()) { - range = range_copy; - return CSSCubicBezierTimingFunctionValue::Create(x1, y1, x2, y2); - } - - return nullptr; -} - -} // namespace - -CSSValue* -CSSPropertyAnimationTimingFunctionUtils::ConsumeAnimationTimingFunction( - CSSParserTokenRange& range) { - CSSValueID id = range.Peek().Id(); - if (id == CSSValueEase || id == CSSValueLinear || id == CSSValueEaseIn || - id == CSSValueEaseOut || id == CSSValueEaseInOut || - id == CSSValueStepStart || id == CSSValueStepEnd || - id == CSSValueStepMiddle) - return CSSPropertyParserHelpers::ConsumeIdent(range); - - CSSValueID function = range.Peek().FunctionId(); - if (function == CSSValueSteps) - return ConsumeSteps(range); - if (RuntimeEnabledFeatures::FramesTimingFunctionEnabled() && - function == CSSValueFrames) { - return ConsumeFrames(range); - } - if (function == CSSValueCubicBezier) - return ConsumeCubicBezier(range); - return nullptr; -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h deleted file mode 100644 index d067fd98..0000000 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CSSPropertyAnimationTimingFunctionUtils_h -#define CSSPropertyAnimationTimingFunctionUtils_h - -#include "platform/wtf/Allocator.h" - -namespace blink { - -class CSSParserTokenRange; -class CSSValue; - -class CSSPropertyAnimationTimingFunctionUtils { - STATIC_ONLY(CSSPropertyAnimationTimingFunctionUtils); - - public: - static CSSValue* ConsumeAnimationTimingFunction(CSSParserTokenRange&); -}; - -} // namespace blink - -#endif // CSSPropertyAnimationTimingFunctionUtils_h
diff --git a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationUtils.h b/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationUtils.h deleted file mode 100644 index f6158cc..0000000 --- a/third_party/WebKit/Source/core/css/properties/CSSPropertyAnimationUtils.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CSSPropertyAnimationUtils_h -#define CSSPropertyAnimationUtils_h - -#include "core/StylePropertyShorthand.h" -#include "core/css/CSSInitialValue.h" -#include "core/css/parser/CSSPropertyParserHelpers.h" -#include "platform/heap/HeapAllocator.h" -#include "platform/wtf/Allocator.h" - -namespace blink { - -constexpr size_t kMaxNumAnimationLonghands = 8; - -class CSSPropertyAnimationUtils { - STATIC_ONLY(CSSPropertyAnimationUtils); - - public: - template <typename Callback, typename... Args> - static bool ConsumeAnimationShorthand( - const StylePropertyShorthand& shorthand, - HeapVector<CSSValueList*, kMaxNumAnimationLonghands>& longhands, - Callback consumeLonghandItem, - CSSParserTokenRange& range, - const Args&... args) { - const unsigned longhand_count = shorthand.length(); - DCHECK_LE(longhand_count, kMaxNumAnimationLonghands); - - for (size_t i = 0; i < longhand_count; ++i) - longhands[i] = CSSValueList::CreateCommaSeparated(); - - do { - bool parsed_longhand[kMaxNumAnimationLonghands] = {false}; - do { - bool found_property = false; - for (size_t i = 0; i < longhand_count; ++i) { - if (parsed_longhand[i]) - continue; - - CSSValue* value = - consumeLonghandItem(shorthand.properties()[i], range, args...); - if (value) { - parsed_longhand[i] = true; - found_property = true; - longhands[i]->Append(*value); - break; - } - } - if (!found_property) - return false; - } while (!range.AtEnd() && range.Peek().GetType() != kCommaToken); - - // TODO(timloh): This will make invalid longhands, see crbug.com/386459 - for (size_t i = 0; i < longhand_count; ++i) { - if (!parsed_longhand[i]) - longhands[i]->Append(*CSSInitialValue::Create()); - parsed_longhand[i] = false; - } - } while (CSSPropertyParserHelpers::ConsumeCommaIncludingWhitespace(range)); - - return true; - } -}; - -} // namespace blink - -#endif // CSSPropertyAnimationUtils_h
diff --git a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIAnimation.cpp b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIAnimation.cpp deleted file mode 100644 index 195fa81..0000000 --- a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPIAnimation.cpp +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "core/css/properties/CSSShorthandPropertyAPIAnimation.h" - -#include "core/StylePropertyShorthand.h" -#include "core/css/CSSIdentifierValue.h" -#include "core/css/parser/CSSParserContext.h" -#include "core/css/parser/CSSParserLocalContext.h" -#include "core/css/parser/CSSPropertyParserHelpers.h" -#include "core/css/properties/CSSPropertyAnimationIterationCountUtils.h" -#include "core/css/properties/CSSPropertyAnimationNameUtils.h" -#include "core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h" -#include "core/css/properties/CSSPropertyAnimationUtils.h" - -namespace blink { - -namespace { - -// Legacy parsing allows <string>s for animation-name. -CSSValue* ConsumeAnimationValue(CSSPropertyID property, - CSSParserTokenRange& range, - const CSSParserContext& context, - bool use_legacy_parsing) { - switch (property) { - case CSSPropertyAnimationDelay: - return CSSPropertyParserHelpers::ConsumeTime(range, kValueRangeAll); - case CSSPropertyAnimationDirection: - return CSSPropertyParserHelpers::ConsumeIdent< - CSSValueNormal, CSSValueAlternate, CSSValueReverse, - CSSValueAlternateReverse>(range); - case CSSPropertyAnimationDuration: - return CSSPropertyParserHelpers::ConsumeTime(range, - kValueRangeNonNegative); - case CSSPropertyAnimationFillMode: - return CSSPropertyParserHelpers::ConsumeIdent< - CSSValueNone, CSSValueForwards, CSSValueBackwards, CSSValueBoth>( - range); - case CSSPropertyAnimationIterationCount: - return CSSPropertyAnimationIterationCountUtils:: - ConsumeAnimationIterationCount(range); - case CSSPropertyAnimationName: - return CSSPropertyAnimationNameUtils::ConsumeAnimationName( - range, &context, use_legacy_parsing); - case CSSPropertyAnimationPlayState: - return CSSPropertyParserHelpers::ConsumeIdent<CSSValueRunning, - CSSValuePaused>(range); - case CSSPropertyAnimationTimingFunction: - return CSSPropertyAnimationTimingFunctionUtils:: - ConsumeAnimationTimingFunction(range); - default: - NOTREACHED(); - return nullptr; - } -} - -} // namespace - -bool CSSShorthandPropertyAPIAnimation::parseShorthand( - bool important, - CSSParserTokenRange& range, - const CSSParserContext& context, - const CSSParserLocalContext& local_context, - HeapVector<CSSProperty, 256>& properties) { - const StylePropertyShorthand shorthand = animationShorthandForParsing(); - const unsigned longhand_count = shorthand.length(); - - HeapVector<CSSValueList*, kMaxNumAnimationLonghands> longhands( - longhand_count); - if (!CSSPropertyAnimationUtils::ConsumeAnimationShorthand( - shorthand, longhands, ConsumeAnimationValue, range, context, - local_context.UseAliasParsing())) { - return false; - } - - for (size_t i = 0; i < longhand_count; ++i) { - CSSPropertyParserHelpers::AddProperty( - shorthand.properties()[i], shorthand.id(), *longhands[i], important, - CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties); - } - return range.AtEnd(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPITransition.cpp b/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPITransition.cpp deleted file mode 100644 index 43db3ed4..0000000 --- a/third_party/WebKit/Source/core/css/properties/CSSShorthandPropertyAPITransition.cpp +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "core/css/properties/CSSShorthandPropertyAPITransition.h" - -#include "core/StylePropertyShorthand.h" -#include "core/css/CSSIdentifierValue.h" -#include "core/css/parser/CSSParserContext.h" -#include "core/css/parser/CSSParserLocalContext.h" -#include "core/css/parser/CSSPropertyParserHelpers.h" -#include "core/css/properties/CSSPropertyAnimationTimingFunctionUtils.h" -#include "core/css/properties/CSSPropertyAnimationUtils.h" -#include "core/css/properties/CSSPropertyTransitionPropertyUtils.h" - -namespace blink { - -namespace { - -CSSValue* ConsumeTransitionValue(CSSPropertyID property, - CSSParserTokenRange& range) { - switch (property) { - case CSSPropertyTransitionDelay: - return CSSPropertyParserHelpers::ConsumeTime(range, kValueRangeAll); - case CSSPropertyTransitionDuration: - return CSSPropertyParserHelpers::ConsumeTime(range, - kValueRangeNonNegative); - case CSSPropertyTransitionProperty: - return CSSPropertyTransitionPropertyUtils::ConsumeTransitionProperty( - range); - case CSSPropertyTransitionTimingFunction: - return CSSPropertyAnimationTimingFunctionUtils:: - ConsumeAnimationTimingFunction(range); - default: - NOTREACHED(); - return nullptr; - } -} - -} // namespace - -bool CSSShorthandPropertyAPITransition::parseShorthand( - bool important, - CSSParserTokenRange& range, - const CSSParserContext& context, - const CSSParserLocalContext&, - HeapVector<CSSProperty, 256>& properties) { - const StylePropertyShorthand shorthand = transitionShorthandForParsing(); - const unsigned longhand_count = shorthand.length(); - - HeapVector<CSSValueList*, kMaxNumAnimationLonghands> longhands( - longhand_count); - if (!CSSPropertyAnimationUtils::ConsumeAnimationShorthand( - shorthand, longhands, ConsumeTransitionValue, range)) { - return false; - } - - for (size_t i = 0; i < longhand_count; ++i) { - if (shorthand.properties()[i] == CSSPropertyTransitionProperty && - !CSSPropertyTransitionPropertyUtils::IsValidPropertyList(*longhands[i])) - return false; - } - - for (size_t i = 0; i < longhand_count; ++i) { - CSSPropertyParserHelpers::AddProperty( - shorthand.properties()[i], shorthand.id(), *longhands[i], important, - CSSPropertyParserHelpers::IsImplicitProperty::kNotImplicit, properties); - } - - return range.AtEnd(); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/OWNERS b/third_party/WebKit/Source/core/dom/OWNERS index 422f9ab..efcf301 100644 --- a/third_party/WebKit/Source/core/dom/OWNERS +++ b/third_party/WebKit/Source/core/dom/OWNERS
@@ -1,2 +1,5 @@ +hayato@chromium.org +tkent@chromium.org + # TEAM: dom-dev@chromium.org # COMPONENT: Blink>DOM
diff --git a/third_party/WebKit/Source/core/dom/README.md b/third_party/WebKit/Source/core/dom/README.md index 4a2cd52..a9b8175 100644 --- a/third_party/WebKit/Source/core/dom/README.md +++ b/third_party/WebKit/Source/core/dom/README.md
@@ -1,2 +1,192 @@ -# DOCUMENT OBJECT MODEL (DOM): -[The WHATWG DOM spec](https://dom.spec.whatwg.org/) describes the structure of documents and the way a document is accessed and manipulated. It is an API used by HTML and XML documents. It also allowers programmers to build documents, navigate their structure, and add, modify, or delete elements and content. +# DOM + +[Rendered](https://chromium.googlesource.com/chromium/src/+/master/third_party/WebKit/Source/core/dom/README.md) + +This directory contains the implementation of [DOM]. + +[DOM]: https://dom.spec.whatwg.org/ +[DOM Standard]: https://dom.spec.whatwg.org/ + +Basically, this directory should contain only a file which is related to [DOM Standard]. +However, for historical reasons, `core/dom` directory has been used +as if it were *misc* directory. As a result, unfortunately, this directory +contains a lot of files which are not directly related to DOM. + +Please don't add unrelated files to this directory any more. We are trying to +organize the files so that developers wouldn't get confused at seeing this +directory. + +See [crbug.com/738794](http://crbug.com/738794) for tracking our efforts. + +As of now, the following files might be candidates which can be put in other +appropriate directory, including, but not limited to: + +## WebIDL (-> core/???) + +- CommonDefinitions + +## Frame (core/frame) + +- ChildFrameDisconnector +- CompositorWorkerProxyClient +- ContextFeatures +- ContextFeaturesClientImpl +- ContextLifecycleNotifier +- FrameRequestCallback +- FrameRequestCallbackCollection +- ViewportDescription + +## Animation (-> core/animation) + +- AnimationWorkletProxyClient +- ScriptedAnimationController + +## CSSOM (-> core/css/cssom) + +- ClientRect +- ClientRectList + +## CSS (-> core/css) + +- CSSSelectorWatch +- SelectRuleFeatureSet +- SelectorQuery + +## Events (-> core/events) + +- SimulatedClickOptions +- Touch +- TouchInit +- TouchList + +## Style (-> core/styles) + +- DocumentStyleSheetCollection +- ShadowTreeStyleSheetCollection +- StyleChangeReason +- StyleElement (-> core/html?) +- StyleEngine +- StyleEngineContext +- StyleSheetCandidate +- StyleSheetCollection +- TreeScopeStyleSheetCollection +- stylerecalc.md + +## accessibility (-> modules/accessibility?) + +- AXObjectCache +- AXObjectCacheBase +- AccessibleNode + +## typedarray (-> new directory, core/typedarray?) + +- ArrayBuffer +- ArrayBufferView +- ArrayBufferViewHelpers +- DOMArrayBuffer +- DOMArrayBufferView +- DOMArrayPiece +- DOMDataView +- DOMSharedArrayBuffer +- DOMTypedArray +- DataView +- FlexibleArrayBufferView +- Float32Array +- Float64Array +- Int16Array +- Int32Array +- Int8Array +- SharedArrayBuffer +- TypedFlexibleArrayBufferView +- Uint16Array +- Uint32Array +- Uint8Array +- Uint8ClampedArray + +# URL (-> core/url?) + +- URL +- URLSearchParams +- URLUtilsReadOnly + +## Parser (-> core/html/parser) + +- DecodedDataDocumentParser +- DocumentParser +- DocumentParserClient +- DocumentParserTiming +- RawDataDocumentParser +- ScriptableDocumentParser + +## Script (-> core/html) + +- FunctionStringCallback +- Script +- ScriptElementBase +- ScriptLoader +- ScriptModuleResolver +- ScriptModuleResolverImpl +- ScriptRunner +- ScriptedIdleTaskController + +## HTML Element (-> core/html) + +- FirstLetterPseudoElement +- PseudoElement +- PseudoElementData +- VisitedLinkState (HTMLLinkElement) + +## fullscreen (-> core/fullscreen or core/html) + +- DocumentFullscreen +- ElementFullscreen +- Fullscreen + +## [Message Channels](https://html.spec.whatwg.org/#message-channels) (-> core/html) + +- AncestorList +- ClassicPendingScript, ClassicScript +- MessageChannel +- MessagePort + +## ES6 Modules (-> ???) + +- Modulator +- ModulatorImpl +- ModuleMap + +## [Intersection Observer](https://wicg.github.io/IntersectionObserver/) (-> core/intersection-observer) + +- IntersectionObservation +- IntersectionObserver +- IntersectionObserverCallback +- IntersectionObserverController +- IntersectionObserverEntry +- IntersectionObserverInit + +## Security (-> core/frame/csp or core/frame) + +- RemoteSecurityContext +- SecurityContext + +## Layout (-> core/layout) + +- ResizeObservation +- ResizeObserver +- ResizeObserverController +- ResizeObserverEntry +- WhitespaceAttacher +- WhitespaceLayoutObjects.md + +## iframe (-> core/html?) + +- SandboxFlags + +## Focus (-> core/page) + +- ScopedWindowFocusAllowedIndicator +- SlotScopedTraversal + + +Note: The above classification might be wrong. Please fix this README.md, and move +files if you can, if you know more appropriate places for each file.
diff --git a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp index 26211c17..983f91ba 100644 --- a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp +++ b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
@@ -911,15 +911,11 @@ DCHECK(pending_script_->IsExternal()); bool error_occurred = false; Script* script = pending_script_->GetSource(NullURL(), error_occurred); - const bool was_canceled = pending_script_->WasCanceled(); + const bool wasCanceled = pending_script_->WasCanceled(); DetachPendingScript(); if (error_occurred) { DispatchErrorEvent(); - } else { - // TODO(hiroshige): Remove |was_canceled| once it is confirmed that this - // CHECK never fails. - CHECK(!was_canceled); - + } else if (!wasCanceled) { switch (ExecuteScript(script)) { case ExecuteScriptResult::kShouldFireLoadEvent: DispatchLoadEvent();
diff --git a/third_party/WebKit/Source/core/editing/FrameSelection.cpp b/third_party/WebKit/Source/core/editing/FrameSelection.cpp index a804533d..c70683b 100644 --- a/third_party/WebKit/Source/core/editing/FrameSelection.cpp +++ b/third_party/WebKit/Source/core/editing/FrameSelection.cpp
@@ -1128,14 +1128,28 @@ .SetBaseAndExtentDeprecated(base_position.DeepEquivalent(), extent_position.DeepEquivalent()) .SetAffinity(base_position.Affinity()) - .SetGranularity(granularity) .SetIsHandleVisible(IsHandleVisible()) .Build(); if (new_selection.IsNone()) return; - SetSelection(new_selection, kCloseTyping | kClearTypingStyle, + const VisibleSelection& visible_selection = + CreateVisibleSelectionWithGranularity(new_selection, granularity); + if (visible_selection.IsNone()) + return; + + SelectionInDOMTree::Builder builder; + if (visible_selection.IsBaseFirst()) { + builder.SetBaseAndExtent(visible_selection.Start(), + visible_selection.End()); + } else { + builder.SetBaseAndExtent(visible_selection.End(), + visible_selection.Start()); + } + builder.SetAffinity(visible_selection.Affinity()); + builder.SetIsHandleVisible(IsHandleVisible()); + SetSelection(builder.Build(), kCloseTyping | kClearTypingStyle, CursorAlignOnScroll::kIfNeeded, granularity); }
diff --git a/third_party/WebKit/Source/core/editing/FrameSelectionTest.cpp b/third_party/WebKit/Source/core/editing/FrameSelectionTest.cpp index 9fc95a6..247820ff 100644 --- a/third_party/WebKit/Source/core/editing/FrameSelectionTest.cpp +++ b/third_party/WebKit/Source/core/editing/FrameSelectionTest.cpp
@@ -238,6 +238,27 @@ EXPECT_EQ_SELECTED_TEXT("Foo Bar"); } +TEST_F(FrameSelectionTest, MoveRangeSelectionNoLiveness) { + SetBodyContent("<span id=sample>xyz</span>"); + Element* const sample = GetDocument().getElementById("sample"); + // Select as: <span id=sample>^xyz|</span> + Selection().MoveRangeSelection( + CreateVisiblePosition(Position(sample->firstChild(), 1)), + CreateVisiblePosition(Position(sample->firstChild(), 1)), + kWordGranularity); + EXPECT_EQ("xyz", Selection().SelectedText()); + sample->insertBefore(Text::Create(GetDocument(), "abc"), + sample->firstChild()); + GetDocument().UpdateStyleAndLayout(); + const VisibleSelection& selection = + Selection().ComputeVisibleSelectionInDOMTree(); + // Inserting "abc" before "xyz" should not affect to selection. + EXPECT_EQ(Position(sample->lastChild(), 0), selection.Start()); + EXPECT_EQ(Position(sample->lastChild(), 3), selection.End()); + EXPECT_EQ("xyz", Selection().SelectedText()); + EXPECT_EQ("abcxyz", sample->innerText()); +} + // For http://crbug.com/695317 TEST_F(FrameSelectionTest, SelectAllWithInputElement) { SetBodyContent("<input>123");
diff --git a/third_party/WebKit/Source/core/editing/SelectionController.cpp b/third_party/WebKit/Source/core/editing/SelectionController.cpp index 84d0b6a2..71cac42 100644 --- a/third_party/WebKit/Source/core/editing/SelectionController.cpp +++ b/third_party/WebKit/Source/core/editing/SelectionController.cpp
@@ -535,12 +535,12 @@ const VisiblePositionInFlatTree& pos = VisiblePositionOfHitTestResult(adjusted_hit_test_result); const VisibleSelectionInFlatTree& new_selection = - pos.IsNotNull() - ? CreateVisibleSelection(SelectionInFlatTree::Builder() - .Collapse(pos.ToPositionWithAffinity()) - .SetGranularity(kWordGranularity) - .Build()) - : VisibleSelectionInFlatTree(); + pos.IsNotNull() ? CreateVisibleSelectionWithGranularity( + SelectionInFlatTree::Builder() + .Collapse(pos.ToPositionWithAffinity()) + .Build(), + kWordGranularity) + : VisibleSelectionInFlatTree(); HandleVisibility visibility = HandleVisibility::kNotVisible; if (select_input_event_type == SelectInputEventType::kTouch) { @@ -903,12 +903,12 @@ const VisiblePositionInFlatTree& pos = VisiblePositionOfHitTestResult(event.GetHitTestResult()); const VisibleSelectionInFlatTree new_selection = - pos.IsNotNull() - ? CreateVisibleSelection(SelectionInFlatTree::Builder() - .Collapse(pos.ToPositionWithAffinity()) - .SetGranularity(kParagraphGranularity) - .Build()) - : VisibleSelectionInFlatTree(); + pos.IsNotNull() ? CreateVisibleSelectionWithGranularity( + SelectionInFlatTree::Builder() + .Collapse(pos.ToPositionWithAffinity()) + .Build(), + kParagraphGranularity) + : VisibleSelectionInFlatTree(); const bool is_handle_visible = event.Event().FromTouch() && new_selection.IsRange();
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp index 9714d1a5..1c71047e9 100644 --- a/third_party/WebKit/Source/core/editing/VisibleSelection.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
@@ -50,20 +50,21 @@ template <typename Strategy> VisibleSelectionTemplate<Strategy>::VisibleSelectionTemplate( - const SelectionTemplate<Strategy>& selection) + const SelectionTemplate<Strategy>& selection, + TextGranularity granularity) : base_(selection.Base()), extent_(selection.Extent()), affinity_(selection.Affinity()), selection_type_(kNoSelection), is_directional_(selection.IsDirectional()), - granularity_(selection.Granularity()) { + granularity_(granularity) { Validate(granularity_); } template <typename Strategy> VisibleSelectionTemplate<Strategy> VisibleSelectionTemplate<Strategy>::Create( const SelectionTemplate<Strategy>& selection) { - return VisibleSelectionTemplate(selection); + return VisibleSelectionTemplate(selection, selection.Granularity()); } VisibleSelection CreateVisibleSelection(const SelectionInDOMTree& selection) { @@ -76,6 +77,27 @@ } template <typename Strategy> +VisibleSelectionTemplate<Strategy> +VisibleSelectionTemplate<Strategy>::CreateWithGranularity( + const SelectionTemplate<Strategy>& selection, + TextGranularity granularity) { + return VisibleSelectionTemplate(selection, granularity); +} + +VisibleSelection CreateVisibleSelectionWithGranularity( + const SelectionInDOMTree& selection, + TextGranularity granularity) { + return VisibleSelection::CreateWithGranularity(selection, granularity); +} + +VisibleSelectionInFlatTree CreateVisibleSelectionWithGranularity( + const SelectionInFlatTree& selection, + TextGranularity granularity) { + return VisibleSelectionInFlatTree::CreateWithGranularity(selection, + granularity); +} + +template <typename Strategy> static SelectionType ComputeSelectionType( const PositionTemplate<Strategy>& start, const PositionTemplate<Strategy>& end) {
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelection.h b/third_party/WebKit/Source/core/editing/VisibleSelection.h index d3c694b..665889c 100644 --- a/third_party/WebKit/Source/core/editing/VisibleSelection.h +++ b/third_party/WebKit/Source/core/editing/VisibleSelection.h
@@ -61,6 +61,12 @@ // Note: |create()| should be used only by |createVisibleSelection|. static VisibleSelectionTemplate Create(const SelectionTemplate<Strategy>&); + // Note: |CreateWithGranularity()| should be used only by + // |CreateVisibleSelectionWithGranularity()|. + static VisibleSelectionTemplate CreateWithGranularity( + const SelectionTemplate<Strategy>&, + TextGranularity); + SelectionType GetSelectionType() const { return selection_type_; } TextAffinity Affinity() const { return affinity_; } @@ -144,7 +150,7 @@ private: friend class SelectionAdjuster; - VisibleSelectionTemplate(const SelectionTemplate<Strategy>&); + VisibleSelectionTemplate(const SelectionTemplate<Strategy>&, TextGranularity); void Validate(TextGranularity = kCharacterGranularity); @@ -193,6 +199,14 @@ CORE_EXPORT VisibleSelectionInFlatTree CreateVisibleSelection(const SelectionInFlatTree&); +CORE_EXPORT VisibleSelection +CreateVisibleSelectionWithGranularity(const SelectionInDOMTree&, + TextGranularity); + +CORE_EXPORT VisibleSelectionInFlatTree +CreateVisibleSelectionWithGranularity(const SelectionInFlatTree&, + TextGranularity); + // We don't yet support multi-range selections, so we only ever have one range // to return. CORE_EXPORT EphemeralRange FirstEphemeralRangeOf(const VisibleSelection&);
diff --git a/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp b/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp index 4077327d..c9e5b882 100644 --- a/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp +++ b/third_party/WebKit/Source/core/editing/VisibleSelectionTest.cpp
@@ -64,11 +64,11 @@ VisibleSelectionTemplate<Strategy> ExpandUsingGranularity( const VisibleSelectionTemplate<Strategy>& selection, TextGranularity granularity) { - return CreateVisibleSelection( + return CreateVisibleSelectionWithGranularity( typename SelectionTemplate<Strategy>::Builder() .SetBaseAndExtent(selection.Base(), selection.Extent()) - .SetGranularity(granularity) - .Build()); + .Build(), + granularity); } // For http://crbug.com/700368 @@ -82,12 +82,12 @@ // TODO(editing-dev): We should remove above comment once we fix [1]. // [1] http://crbug.com/701657 double-click on user-select:none should not // compute selection. - const VisibleSelection selection = - CreateVisibleSelection(SelectionInDOMTree::Builder() - .Collapse(Position::BeforeNode(*input)) - .Extend(Position::AfterNode(*input)) - .SetGranularity(kWordGranularity) - .Build()); + const VisibleSelection selection = CreateVisibleSelectionWithGranularity( + SelectionInDOMTree::Builder() + .Collapse(Position::BeforeNode(*input)) + .Extend(Position::AfterNode(*input)) + .Build(), + kWordGranularity); const VisibleSelection result = selection.AppendTrailingWhitespace(); EXPECT_EQ(Position::BeforeNode(*input), result.Start());
diff --git a/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm b/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm index 7584a65..f60a06c 100644 --- a/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm +++ b/third_party/WebKit/Source/core/editing/WebSubstringUtil.mm
@@ -169,11 +169,9 @@ return nil; // Expand to word under point. - const VisibleSelection& selection = - CreateVisibleSelection(SelectionInDOMTree::Builder() - .SetBaseAndExtent(range) - .SetGranularity(kWordGranularity) - .Build()); + const VisibleSelection& selection = CreateVisibleSelectionWithGranularity( + SelectionInDOMTree::Builder().SetBaseAndExtent(range).Build(), + kWordGranularity); const EphemeralRange word_range = selection.ToNormalizedEphemeralRange(); // Convert to NSAttributedString.
diff --git a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp index 029e5f7..2400a5f 100644 --- a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp
@@ -393,7 +393,7 @@ static bool ExpandSelectionToGranularity(LocalFrame& frame, TextGranularity granularity) { - const VisibleSelection& selection = CreateVisibleSelection( + const VisibleSelection& selection = CreateVisibleSelectionWithGranularity( SelectionInDOMTree::Builder() .SetBaseAndExtent(frame.Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() @@ -401,8 +401,8 @@ frame.Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .Extent()) - .SetGranularity(granularity) - .Build()); + .Build(), + granularity); const EphemeralRange new_range = selection.ToNormalizedEphemeralRange(); if (new_range.IsNull()) return false;
diff --git a/third_party/WebKit/Source/core/events/EventTargetFactory.json5 b/third_party/WebKit/Source/core/events/EventTargetFactory.json5 index 875c970..b9dcfb58 100644 --- a/third_party/WebKit/Source/core/events/EventTargetFactory.json5 +++ b/third_party/WebKit/Source/core/events/EventTargetFactory.json5
@@ -19,7 +19,7 @@ "core/html/track/TextTrackList", "core/html/track/VideoTrackList", "core/loader/appcache/ApplicationCache", - "core/mojo/testing/MojoInterfaceInterceptor", + "core/mojo/test/MojoInterfaceInterceptor", "core/offscreencanvas/OffscreenCanvas", "core/page/EventSource", "core/timing/Performance",
diff --git a/third_party/WebKit/Source/core/exported/WebViewBase.h b/third_party/WebKit/Source/core/exported/WebViewBase.h index e2a93a9..c177dcb 100644 --- a/third_party/WebKit/Source/core/exported/WebViewBase.h +++ b/third_party/WebKit/Source/core/exported/WebViewBase.h
@@ -16,11 +16,10 @@ namespace blink { -class AnimationWorkletProxyClient; class BrowserControls; class ChromeClient; class CompositorAnimationHost; -class CompositorWorkerProxyClient; +class CompositorMutatorImpl; class CompositorAnimationTimeline; class ContextMenuProvider; class DevToolsEmulator; @@ -180,8 +179,7 @@ virtual WebInputMethodController* GetActiveWebInputMethodController() const = 0; virtual void ScheduleAnimationForWidget() = 0; - virtual CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient() = 0; - virtual AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient() = 0; + virtual CompositorMutatorImpl* CompositorMutator() = 0; virtual void SetRootGraphicsLayer(GraphicsLayer*) = 0; virtual void SetRootLayer(WebLayer*) = 0; virtual CompositorAnimationHost* AnimationHost() const = 0;
diff --git a/third_party/WebKit/Source/core/frame/ContentSettingsClient.cpp b/third_party/WebKit/Source/core/frame/ContentSettingsClient.cpp index e919a74b..729a453e9 100644 --- a/third_party/WebKit/Source/core/frame/ContentSettingsClient.cpp +++ b/third_party/WebKit/Source/core/frame/ContentSettingsClient.cpp
@@ -58,12 +58,6 @@ return enabled_per_settings; } -bool ContentSettingsClient::AllowPlugins(bool enabled_per_settings) { - if (client_) - return client_->AllowPlugins(enabled_per_settings); - return enabled_per_settings; -} - bool ContentSettingsClient::AllowImage(bool enabled_per_settings, const KURL& image_url) { if (client_)
diff --git a/third_party/WebKit/Source/core/frame/ContentSettingsClient.h b/third_party/WebKit/Source/core/frame/ContentSettingsClient.h index 52ef140..4018343f 100644 --- a/third_party/WebKit/Source/core/frame/ContentSettingsClient.h +++ b/third_party/WebKit/Source/core/frame/ContentSettingsClient.h
@@ -48,9 +48,6 @@ // Controls whether scripts loaded from the given URL are allowed to execute. bool AllowScriptFromSource(bool enabled_per_settings, const KURL&); - // Controls whether plugins are allowed. - bool AllowPlugins(bool enabled_per_settings); - // Controls whether images are allowed. bool AllowImage(bool enabled_per_settings, const KURL&);
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp index 2f0221a..fb9f2b08 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.cpp
@@ -1493,7 +1493,6 @@ DocumentLoadTiming& timing = document_loader->GetTiming(); timing.MarkLoadEventStart(); DispatchEvent(load_event, document()); - SetHasLoadEventFired(); timing.MarkLoadEventEnd(); DCHECK(document_loader->Fetcher()); // If fetcher->countPreloads() is not empty here, it's full of link
diff --git a/third_party/WebKit/Source/core/frame/LocalDOMWindow.h b/third_party/WebKit/Source/core/frame/LocalDOMWindow.h index 777a7c71..1045dbd 100644 --- a/third_party/WebKit/Source/core/frame/LocalDOMWindow.h +++ b/third_party/WebKit/Source/core/frame/LocalDOMWindow.h
@@ -316,9 +316,6 @@ FloatSize GetViewportSize(IncludeScrollbarsInRect) const; - void SetHasLoadEventFired() { has_load_event_fired_ = true; } - bool HasLoadEventFired() { return has_load_event_fired_; } - protected: // EventTarget overrides. void AddedEventListener(const AtomicString& event_type,
diff --git a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h index dd5494c..37077d8 100644 --- a/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h +++ b/third_party/WebKit/Source/core/frame/WebFrameWidgetBase.h
@@ -17,9 +17,8 @@ namespace blink { -class AnimationWorkletProxyClient; class CompositorAnimationHost; -class CompositorWorkerProxyClient; +class CompositorMutatorImpl; class GraphicsLayer; class WebImage; class WebLayer; @@ -36,8 +35,8 @@ virtual bool ForSubframe() const = 0; virtual void ScheduleAnimation() = 0; - virtual CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient() = 0; - virtual AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient() = 0; + virtual CompositorMutatorImpl* CompositorMutator() = 0; + virtual WebWidgetClient* Client() const = 0; // Sets the root graphics layer. |GraphicsLayer| can be null when detaching
diff --git a/third_party/WebKit/Source/core/frame/WebLocalFrameBase.h b/third_party/WebKit/Source/core/frame/WebLocalFrameBase.h index 152e082..2ce9a52 100644 --- a/third_party/WebKit/Source/core/frame/WebLocalFrameBase.h +++ b/third_party/WebKit/Source/core/frame/WebLocalFrameBase.h
@@ -76,6 +76,8 @@ virtual TextFinder* GetTextFinder() const = 0; virtual void SetInputEventsTransformForEmulation(const IntSize&, float) = 0; + virtual WebFrameWidgetBase* LocalRootFrameWidget() = 0; + DEFINE_INLINE_VIRTUAL_TRACE() {} protected:
diff --git a/third_party/WebKit/Source/core/frame/WebViewFrameWidget.cpp b/third_party/WebKit/Source/core/frame/WebViewFrameWidget.cpp index 4e574b6..9a46395 100644 --- a/third_party/WebKit/Source/core/frame/WebViewFrameWidget.cpp +++ b/third_party/WebKit/Source/core/frame/WebViewFrameWidget.cpp
@@ -221,14 +221,8 @@ web_view_->ScheduleAnimationForWidget(); } -CompositorWorkerProxyClient* -WebViewFrameWidget::CreateCompositorWorkerProxyClient() { - return web_view_->CreateCompositorWorkerProxyClient(); -} - -AnimationWorkletProxyClient* -WebViewFrameWidget::CreateAnimationWorkletProxyClient() { - return web_view_->CreateAnimationWorkletProxyClient(); +CompositorMutatorImpl* WebViewFrameWidget::CompositorMutator() { + return web_view_->CompositorMutator(); } void WebViewFrameWidget::SetRootGraphicsLayer(GraphicsLayer* layer) {
diff --git a/third_party/WebKit/Source/core/frame/WebViewFrameWidget.h b/third_party/WebKit/Source/core/frame/WebViewFrameWidget.h index 1538173..5c0486d 100644 --- a/third_party/WebKit/Source/core/frame/WebViewFrameWidget.h +++ b/third_party/WebKit/Source/core/frame/WebViewFrameWidget.h
@@ -98,8 +98,7 @@ // WebFrameWidgetBase overrides: bool ForSubframe() const override { return false; } void ScheduleAnimation() override; - CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient() override; - AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient() override; + CompositorMutatorImpl* CompositorMutator() override; void SetRootGraphicsLayer(GraphicsLayer*) override; GraphicsLayer* RootGraphicsLayer() const override; void SetRootLayer(WebLayer*) override;
diff --git a/third_party/WebKit/Source/core/html/custom/V0CustomElementRegistry.cpp b/third_party/WebKit/Source/core/html/custom/V0CustomElementRegistry.cpp index 5b10f83b..f3648be 100644 --- a/third_party/WebKit/Source/core/html/custom/V0CustomElementRegistry.cpp +++ b/third_party/WebKit/Source/core/html/custom/V0CustomElementRegistry.cpp
@@ -48,7 +48,7 @@ const AtomicString& user_supplied_name, V0CustomElement::NameSet valid_names, ExceptionState& exception_state) { - AtomicString type = user_supplied_name.DeprecatedLower(); + AtomicString type = user_supplied_name.LowerASCII(); if (!constructor_builder->IsFeatureAllowed()) { V0CustomElementException::ThrowException(
diff --git a/third_party/WebKit/Source/core/html/forms/resources/input_alert.svg b/third_party/WebKit/Source/core/html/forms/resources/input_alert.svg new file mode 100644 index 0000000..b107f94 --- /dev/null +++ b/third_party/WebKit/Source/core/html/forms/resources/input_alert.svg
@@ -0,0 +1,10 @@ +<!-- No XML declaration intentionally --> +<!-- 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. --> +<svg xmlns="http://www.w3.org/2000/svg" width="23" height="23" viewBox="0 0 47 47" id="icon"> +<rect x="0" y="0" width="47" height="47" rx="4" ry="4" fill="#ffa300"/> +<rect x="20" y="10" width="7" height="15" fill="#ffffff" /> +<circle cx="23.5" cy="33" r="3.5" fill="#ffffff"/> +<!-- TODO(tkent): Add some shadow. --> +</svg>
diff --git a/third_party/WebKit/Source/core/html/forms/resources/validation_bubble.css b/third_party/WebKit/Source/core/html/forms/resources/validation_bubble.css new file mode 100644 index 0000000..0749f6f --- /dev/null +++ b/third_party/WebKit/Source/core/html/forms/resources/validation_bubble.css
@@ -0,0 +1,108 @@ +/* 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. + */ + +:root { + --bubble-background: white; + --bubble-border-color: gray; + --arrow-size: 8px; +} + +#container { + box-sizing: border-box; + display: inline-block; + font-family: system-ui; + font-size: 16px; + max-width: 50%; + opacity: 0; + position: absolute; + transition: opacity 0.3s; +} + +#bubble-body { + background: var(--bubble-background); + border-radius: 4px; + border: 1px solid var(--bubble-border-color); + box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.2); + display: grid; + padding: 8px; +} + +#outer-arrow-top { + border-color: transparent transparent var(--bubble-border-color) transparent; + border-style: solid; + border-width: 0px var(--arrow-size) var(--arrow-size) var(--arrow-size); + display: block; + left: 10px; + margin-top: -2px; + position: absolute; + width: 0px; +} + +#inner-arrow-top { + border-color: transparent transparent var(--bubble-background) transparent; + border-style: solid; + border-width: 0px var(--arrow-size) var(--arrow-size) var(--arrow-size); + display: block; + left: 10px; + margin-bottom: -2px; + position: relative; + width: 0px; +} + +.bottom-arrow #outer-arrow-top, .bottom-arrow #inner-arrow-top { + display: none; +} + +#outer-arrow-bottom, #inner-arrow-bottom { + display: none; +} + +.bottom-arrow #outer-arrow-bottom { + border-color: var(--bubble-border-color) transparent transparent transparent; + border-style: solid; + border-width: var(--arrow-size) var(--arrow-size) 0px var(--arrow-size); + display: block; + left: 10px; + margin-top: 1px; + position: absolute; + width: 0px; +} + +.bottom-arrow #inner-arrow-bottom { + border-color: var(--bubble-background) transparent transparent transparent; + border-style: solid; + border-width: var(--arrow-size) var(--arrow-size) 0px var(--arrow-size); + display: block; + left: 10px; + margin-top: -2px; + position: relative; + width: 0px; +} + +#icon { + grid-row: 1 / 3; + grid-column: 1; + margin-right: 8px; +} + +#main-message { + font-size: 16px; + grid-row: 1; + grid-column: 2; + margin-top: 3px; + margin-bottom: 4px; +} + +#sub-message { + color: #444; + font-size: 13px; + grid-row: 2; + grid-column: 2; +} + +body { + margin: 0; + overflow: hidden; +}
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportChild.h b/third_party/WebKit/Source/core/html/imports/HTMLImportChild.h index 9c98e15..6793e4c0 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportChild.h +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportChild.h
@@ -51,7 +51,7 @@ class HTMLImportChild final : public HTMLImport { public: HTMLImportChild(const KURL&, HTMLImportLoader*, SyncMode); - ~HTMLImportChild() override; + ~HTMLImportChild() final; void Dispose(); HTMLLinkElement* Link() const; @@ -62,15 +62,15 @@ void DidStartLoading(); // HTMLImport - Document* GetDocument() const override; - bool HasFinishedLoading() const override; - HTMLImportLoader* Loader() const override; - void StateWillChange() override; - void StateDidChange() override; + Document* GetDocument() const final; + bool HasFinishedLoading() const final; + HTMLImportLoader* Loader() const final; + void StateWillChange() final; + void StateDidChange() final; DECLARE_VIRTUAL_TRACE(); #if !defined(NDEBUG) - void ShowThis() override; + void ShowThis() final; #endif void SetClient(HTMLImportChildClient*);
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.h b/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.h index e794da6f..18ebb66a 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.h +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportLoader.h
@@ -68,7 +68,7 @@ return new HTMLImportLoader(controller); } - ~HTMLImportLoader() override; + ~HTMLImportLoader() final; void Dispose(); Document* GetDocument() const { return document_.Get(); } @@ -101,19 +101,19 @@ private: HTMLImportLoader(HTMLImportsController*); - // RawResourceClient + // RawResourceClient overrides: void ResponseReceived(Resource*, const ResourceResponse&, - std::unique_ptr<WebDataConsumerHandle>) override; - void DataReceived(Resource*, const char* data, size_t length) override; - void NotifyFinished(Resource*) override; - String DebugName() const override { return "HTMLImportLoader"; } + std::unique_ptr<WebDataConsumerHandle>) final; + void DataReceived(Resource*, const char* data, size_t length) final; + void NotifyFinished(Resource*) final; + String DebugName() const final { return "HTMLImportLoader"; } - // DocumentParserClient + // DocumentParserClient overrides: // Called after document parse is complete after DOMContentLoaded was // dispatched. - void NotifyParserStopped() override; + void NotifyParserStopped() final; State StartWritingAndParsing(const ResourceResponse&); State FinishWriting();
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportState.h b/third_party/WebKit/Source/core/html/imports/HTMLImportState.h index fe71c03..ec8e0706 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportState.h +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportState.h
@@ -36,7 +36,7 @@ namespace blink { -class HTMLImportState { +class HTMLImportState final { DISALLOW_NEW(); public:
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportStateResolver.h b/third_party/WebKit/Source/core/html/imports/HTMLImportStateResolver.h index 9592fda5..3cc09114 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportStateResolver.h +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportStateResolver.h
@@ -38,7 +38,7 @@ class HTMLImport; -class HTMLImportStateResolver { +class HTMLImportStateResolver final { STACK_ALLOCATED(); public:
diff --git a/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.h b/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.h index a2f1b27a..3a7a2eb6 100644 --- a/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.h +++ b/third_party/WebKit/Source/core/html/imports/HTMLImportTreeRoot.h
@@ -14,18 +14,18 @@ class HTMLImportChild; class KURL; -class HTMLImportTreeRoot : public HTMLImport { +class HTMLImportTreeRoot final : public HTMLImport { public: static HTMLImportTreeRoot* Create(Document*); - ~HTMLImportTreeRoot() override; + ~HTMLImportTreeRoot() final; void Dispose(); - // HTMLImport - Document* GetDocument() const override; - bool HasFinishedLoading() const override; - void StateWillChange() override; - void StateDidChange() override; + // HTMLImport overrides: + Document* GetDocument() const final; + bool HasFinishedLoading() const final; + void StateWillChange() final; + void StateDidChange() final; void ScheduleRecalcState();
diff --git a/third_party/WebKit/Source/core/html/imports/LinkImport.h b/third_party/WebKit/Source/core/html/imports/LinkImport.h index fa11439c..89d0a37 100644 --- a/third_party/WebKit/Source/core/html/imports/LinkImport.h +++ b/third_party/WebKit/Source/core/html/imports/LinkImport.h
@@ -51,21 +51,21 @@ static LinkImport* Create(HTMLLinkElement* owner); explicit LinkImport(HTMLLinkElement* owner); - ~LinkImport() override; + ~LinkImport() final; - // LinkResource - void Process() override; - LinkResourceType GetType() const override { return kImport; } - bool HasLoaded() const override; + // LinkResource overrides: + void Process() final; + LinkResourceType GetType() const final { return kImport; } + bool HasLoaded() const final; DECLARE_VIRTUAL_TRACE(); - void OwnerInserted() override; - void OwnerRemoved() override; + void OwnerInserted() final; + void OwnerRemoved() final; - // HTMLImportChildClient - void DidFinish() override; - void ImportChildWasDisposed(HTMLImportChild*) override; - bool IsSync() const override; - HTMLLinkElement* Link() override; + // HTMLImportChildClient overrides: + void DidFinish() final; + void ImportChildWasDisposed(HTMLImportChild*) final; + bool IsSync() const final; + HTMLLinkElement* Link() final; Document* ImportedDocument() const;
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp index ab7afbb..d78c84d 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -198,15 +198,4 @@ HTMLInputElement::Trace(visitor); } -// ---------------------------- - -MediaControlTimeDisplayElement::MediaControlTimeDisplayElement( - MediaControls& media_controls, - MediaControlElementType display_type) - : MediaControlDivElement(media_controls, display_type), current_value_(0) {} - -void MediaControlTimeDisplayElement::SetCurrentValue(double time) { - current_value_ = time; -} - } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h b/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h index 0fc0a49..798efbb 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h
@@ -191,21 +191,6 @@ } }; -// ---------------------------- - -class CORE_EXPORT MediaControlTimeDisplayElement - : public MediaControlDivElement { - public: - void SetCurrentValue(double); - double CurrentValue() const { return current_value_; } - - protected: - MediaControlTimeDisplayElement(MediaControls&, MediaControlElementType); - - private: - double current_value_; -}; - } // namespace blink #endif // MediaControlElementTypes_h
diff --git a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp index 25730704..9cb408b 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
@@ -2238,11 +2238,11 @@ if (!element_layout) return Response::OK(); - for (const LayoutObject* child = element_layout->SlowFirstChild(); child; - child = child->NextSibling()) { - if (!child->IsText()) + for (const Node* child = element->firstChild(); child; + child = child->nextSibling()) { + if (!child->IsTextNode()) continue; - text_bounds.Unite(LayoutRect(child->AbsoluteBoundingBoxRect())); + text_bounds.Unite(LayoutRect(child->BoundingBox())); } if (text_bounds.Size().IsEmpty()) return Response::OK();
diff --git a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp index cb21b97..9116d5a2 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp
@@ -216,16 +216,15 @@ String MixedContentTypeForContextType(WebMixedContentContextType context_type) { switch (context_type) { case WebMixedContentContextType::kNotMixedContent: - return protocol::Network::Request::MixedContentTypeEnum::None; + return protocol::Security::MixedContentTypeEnum::None; case WebMixedContentContextType::kBlockable: - return protocol::Network::Request::MixedContentTypeEnum::Blockable; + return protocol::Security::MixedContentTypeEnum::Blockable; case WebMixedContentContextType::kOptionallyBlockable: case WebMixedContentContextType::kShouldBeBlockable: - return protocol::Network::Request::MixedContentTypeEnum:: - OptionallyBlockable; + return protocol::Security::MixedContentTypeEnum::OptionallyBlockable; } - return protocol::Network::Request::MixedContentTypeEnum::None; + return protocol::Security::MixedContentTypeEnum::None; } String ResourcePriorityJSON(ResourceLoadPriority priority) {
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp index 3053528..6ead6e9 100644 --- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp +++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
@@ -76,7 +76,7 @@ new InspectorLogAgent(thread_->GetConsoleMessageStorage(), nullptr)); if (thread_->GlobalScope()->IsWorkerGlobalScope() && RuntimeEnabledFeatures::OffMainThreadFetchEnabled()) { - DCHECK(ToWorkerGlobalScope(thread_->GlobalScope())->GetFetchContext()); + DCHECK(ToWorkerGlobalScope(thread_->GlobalScope())->GetResourceFetcher()); session->Append(InspectorNetworkAgent::CreateForWorker( ToWorkerGlobalScope(thread_->GlobalScope()))); }
diff --git a/third_party/WebKit/Source/core/inspector/browser_protocol.json b/third_party/WebKit/Source/core/inspector/browser_protocol.json index c5ce1d31..a2970a5 100644 --- a/third_party/WebKit/Source/core/inspector/browser_protocol.json +++ b/third_party/WebKit/Source/core/inspector/browser_protocol.json
@@ -67,7 +67,7 @@ { "domain": "Page", "description": "Actions and events related to the inspected page belong to the page domain.", - "dependencies": ["Debugger", "DOM"], + "dependencies": ["Debugger", "DOM", "Network"], "types": [ { "id": "ResourceType", @@ -102,7 +102,7 @@ { "name": "url", "type": "string", "description": "Resource URL." }, { "name": "type", "$ref": "ResourceType", "description": "Type of this resource." }, { "name": "mimeType", "type": "string", "description": "Resource mimeType as determined by the browser." }, - { "name": "lastModified", "$ref": "Network.Timestamp", "description": "last-modified timestamp as reported by server.", "optional": true }, + { "name": "lastModified", "$ref": "Network.TimeSinceEpoch", "description": "last-modified timestamp as reported by server.", "optional": true }, { "name": "contentSize", "type": "number", "description": "Resource content size.", "optional": true }, { "name": "failed", "type": "boolean", "optional": true, "description": "True if the resource failed to load." }, { "name": "canceled", "type": "boolean", "optional": true, "description": "True if the resource was canceled during loading." } @@ -157,7 +157,7 @@ { "name": "deviceHeight", "type": "number", "experimental": true, "description": "Device screen height in DIP." }, { "name": "scrollOffsetX", "type": "number", "experimental": true, "description": "Position of horizontal scroll in CSS pixels." }, { "name": "scrollOffsetY", "type": "number", "experimental": true, "description": "Position of vertical scroll in CSS pixels." }, - { "name": "timestamp", "type": "number", "optional": true, "experimental": true, "description": "Frame swap timestamp." } + { "name": "timestamp", "$ref": "Network.TimeSinceEpoch", "optional": true, "experimental": true, "description": "Frame swap timestamp." } ], "experimental": true }, @@ -549,13 +549,13 @@ { "name": "domContentEventFired", "parameters": [ - { "name": "timestamp", "type": "number" } + { "name": "timestamp", "$ref": "Network.MonotonicTime" } ] }, { "name": "loadEventFired", "parameters": [ - { "name": "timestamp", "type": "number" } + { "name": "timestamp", "$ref": "Network.MonotonicTime" } ] }, { @@ -1020,6 +1020,12 @@ "description": "An internal certificate ID value." }, { + "id": "MixedContentType", + "type": "string", + "enum": ["blockable", "optionally-blockable", "none"], + "description": "A description of mixed content (HTTP resources on HTTPS pages), as defined by https://www.w3.org/TR/mixed-content/#categories" + }, + { "id": "SecurityState", "type": "string", "enum": ["unknown", "neutral", "insecure", "warning", "secure", "info"], @@ -1032,7 +1038,8 @@ { "name": "securityState", "$ref": "SecurityState", "description": "Security state representing the severity of the factor being explained." }, { "name": "summary", "type": "string", "description": "Short phrase describing the type of factor." }, { "name": "description", "type": "string", "description": "Full text explanation of the factor." }, - { "name": "hasCertificate", "type": "boolean", "description": "True if the page has a certificate." } + { "name": "hasCertificate", "type": "boolean", "description": "True if the page has a certificate." }, + { "name": "mixedContentType", "$ref": "MixedContentType", "description": "The type of mixed content described by the explanation." } ], "description": "An explanation of an factor contributing to the security state." }, @@ -1136,9 +1143,14 @@ "description": "Network level fetch failure reason." }, { - "id": "Timestamp", + "id": "TimeSinceEpoch", "type": "number", - "description": "Number of seconds since epoch." + "description": "UTC time in seconds, counted from January 1, 1970." + }, + { + "id": "MonotonicTime", + "type": "number", + "description": "Monotonically increasing time in seconds since an arbitrary point in the past." }, { "id": "Headers", @@ -1195,7 +1207,7 @@ { "name": "method", "type": "string", "description": "HTTP request method." }, { "name": "headers", "$ref": "Headers", "description": "HTTP request headers." }, { "name": "postData", "type": "string", "optional": true, "description": "HTTP POST request data." }, - { "name": "mixedContentType", "optional": true, "type": "string", "enum": ["blockable", "optionally-blockable", "none"], "description": "The mixed content status of the request, as defined in http://www.w3.org/TR/mixed-content/" }, + { "name": "mixedContentType", "$ref": "Security.MixedContentType", "optional": true, "description": "The mixed content type of the request." }, { "name": "initialPriority", "$ref": "ResourcePriority", "description": "Priority of the resource request at the time request is sent."}, { "name": "referrerPolicy", "type": "string", "enum": [ "unsafe-url", "no-referrer-when-downgrade", "no-referrer", "origin", "origin-when-cross-origin", "same-origin", "strict-origin", "strict-origin-when-cross-origin" ], "description": "The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/" }, { "name": "isLinkPreload", "type": "boolean", "optional": true, "description": "Whether is loaded via link preload." } @@ -1210,7 +1222,7 @@ { "name": "origin", "type": "string", "description": "Origin." }, { "name": "logDescription", "type": "string", "description": "Log name / description." }, { "name": "logId", "type": "string", "description": "Log ID." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Issuance date." }, + { "name": "timestamp", "$ref": "TimeSinceEpoch", "description": "Issuance date." }, { "name": "hashAlgorithm", "type": "string", "description": "Hash algorithm." }, { "name": "signatureAlgorithm", "type": "string", "description": "Signature algorithm." }, { "name": "signatureData", "type": "string", "description": "Signature data." } @@ -1230,8 +1242,8 @@ { "name": "subjectName", "type": "string", "description": "Certificate subject name." }, { "name": "sanList", "type": "array", "items": { "type": "string" }, "description": "Subject Alternative Name (SAN) DNS names and IP addresses." }, { "name": "issuer", "type": "string", "description": "Name of the issuing CA." }, - { "name": "validFrom", "$ref": "Timestamp", "description": "Certificate valid from date." }, - { "name": "validTo", "$ref": "Timestamp", "description": "Certificate valid to (expiration) date" }, + { "name": "validFrom", "$ref": "TimeSinceEpoch", "description": "Certificate valid from date." }, + { "name": "validTo", "$ref": "TimeSinceEpoch", "description": "Certificate valid to (expiration) date" }, { "name": "signedCertificateTimestampList", "type": "array", "items": { "$ref": "SignedCertificateTimestamp" }, "description": "List of signed certificate timestamps (SCTs)." } ] }, @@ -1481,7 +1493,7 @@ { "name": "secure", "type": "boolean", "optional": true, "description": "Defaults ot false." }, { "name": "httpOnly", "type": "boolean", "optional": true, "description": "Defaults to false." }, { "name": "sameSite", "$ref": "CookieSameSite", "optional": true, "description": "Defaults to browser default behavior." }, - { "name": "expirationDate", "$ref": "Timestamp", "optional": true, "description": "If omitted, the cookie becomes a session cookie." } + { "name": "expirationDate", "$ref": "TimeSinceEpoch", "optional": true, "description": "If omitted, the cookie becomes a session cookie." } ], "returns": [ { "name": "success", "type": "boolean", "description": "True if successfully set cookie." } @@ -1573,7 +1585,7 @@ "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, { "name": "newPriority", "$ref": "ResourcePriority", "description": "New priority" }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." } + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." } ], "experimental": true }, @@ -1585,8 +1597,8 @@ { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier. Empty string if the request is fetched form worker." }, { "name": "documentURL", "type": "string", "description": "URL of the document this request is loaded for." }, { "name": "request", "$ref": "Request", "description": "Request data." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, - { "name": "wallTime", "$ref": "Timestamp", "experimental": true, "description": "UTC Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, + { "name": "wallTime", "$ref": "TimeSinceEpoch", "experimental": true, "description": "Timestamp." }, { "name": "initiator", "$ref": "Initiator", "description": "Request initiator." }, { "name": "redirectResponse", "optional": true, "$ref": "Response", "description": "Redirect response data." }, { "name": "type", "$ref": "Page.ResourceType", "optional": true, "experimental": true, "description": "Type of this resource." }, @@ -1606,7 +1618,7 @@ "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, { "name": "loaderId", "$ref": "LoaderId", "description": "Loader identifier. Empty string if the request is fetched form worker." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "type", "$ref": "Page.ResourceType", "description": "Resource type." }, { "name": "response", "$ref": "Response", "description": "Response data." }, { "name": "frameId", "optional": true, "$ref": "Page.FrameId", "description": "Frame identifier.", "experimental": true } @@ -1617,7 +1629,7 @@ "description": "Fired when data chunk was received over the network.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "dataLength", "type": "integer", "description": "Data chunk length." }, { "name": "encodedDataLength", "type": "integer", "description": "Actual bytes received (might be less than dataLength for compressed encodings)." } ] @@ -1627,7 +1639,7 @@ "description": "Fired when HTTP request has finished loading.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "encodedDataLength", "type": "number", "description": "Total number of bytes received for this request." } ] }, @@ -1636,7 +1648,7 @@ "description": "Fired when HTTP request has failed to load.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "type", "$ref": "Page.ResourceType", "description": "Resource type." }, { "name": "errorText", "type": "string", "description": "User friendly error message." }, { "name": "canceled", "type": "boolean", "optional": true, "description": "True if loading was canceled." }, @@ -1648,8 +1660,8 @@ "description": "Fired when WebSocket is about to initiate handshake.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, - { "name": "wallTime", "$ref": "Timestamp", "experimental": true, "description": "UTC Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, + { "name": "wallTime", "$ref": "TimeSinceEpoch", "experimental": true, "description": "UTC Timestamp." }, { "name": "request", "$ref": "WebSocketRequest", "description": "WebSocket request data." } ], "experimental": true @@ -1659,7 +1671,7 @@ "description": "Fired when WebSocket handshake response becomes available.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "response", "$ref": "WebSocketResponse", "description": "WebSocket response data." } ], "experimental": true @@ -1679,7 +1691,7 @@ "description": "Fired when WebSocket is closed.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." } + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." } ], "experimental": true }, @@ -1688,7 +1700,7 @@ "description": "Fired when WebSocket frame is received.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } ], "experimental": true @@ -1698,7 +1710,7 @@ "description": "Fired when WebSocket frame error occurs.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "errorMessage", "type": "string", "description": "WebSocket frame error message." } ], "experimental": true @@ -1708,7 +1720,7 @@ "description": "Fired when WebSocket frame is sent.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "response", "$ref": "WebSocketFrame", "description": "WebSocket response data." } ], "experimental": true @@ -1718,7 +1730,7 @@ "description": "Fired when EventSource message is received.", "parameters": [ { "name": "requestId", "$ref": "RequestId", "description": "Request identifier." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp." }, + { "name": "timestamp", "$ref": "MonotonicTime", "description": "Timestamp." }, { "name": "eventName", "type": "string", "description": "Message type." }, { "name": "eventId", "type": "string", "description": "Message identifier." }, { "name": "data", "type": "string", "description": "Message content." } @@ -3908,6 +3920,11 @@ "type": "string", "experimental": true, "enum": ["default", "touch", "mouse"] + }, + { + "id": "TimeSinceEpoch", + "type": "number", + "description": "UTC time in seconds, counted from January 1, 1970." } ], "commands": [ @@ -3923,7 +3940,7 @@ "parameters": [ { "name": "type", "type": "string", "enum": ["keyDown", "keyUp", "rawKeyDown", "char"], "description": "Type of the key event." }, { "name": "modifiers", "type": "integer", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0)." }, - { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred. Measured in UTC time in seconds since January 1, 1970 (default: current time)." }, + { "name": "timestamp", "$ref": "TimeSinceEpoch", "optional": true, "description": "Time at which the event occurred." }, { "name": "text", "type": "string", "optional": true, "description": "Text as generated by processing a virtual key code with a keyboard layout. Not needed for for <code>keyUp</code> and <code>rawKeyDown</code> events (default: \"\")" }, { "name": "unmodifiedText", "type": "string", "optional": true, "description": "Text that would have been generated by the keyboard if no modifiers were pressed (except for shift). Useful for shortcut (accelerator) key handling (default: \"\")." }, { "name": "keyIdentifier", "type": "string", "optional": true, "description": "Unique key identifier (e.g., 'U+0041') (default: \"\")." }, @@ -3944,7 +3961,7 @@ { "name": "x", "type": "integer", "description": "X coordinate of the event relative to the main frame's viewport."}, { "name": "y", "type": "integer", "description": "Y coordinate of the event relative to the main frame's viewport. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport."}, { "name": "modifiers", "type": "integer", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0)." }, - { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred. Measured in UTC time in seconds since January 1, 1970 (default: current time)." }, + { "name": "timestamp", "$ref": "TimeSinceEpoch", "optional": true, "description": "Time at which the event occurred." }, { "name": "button", "type": "string", "enum": ["none", "left", "middle", "right"], "optional": true, "description": "Mouse button (default: \"none\")." }, { "name": "clickCount", "type": "integer", "optional": true, "description": "Number of times the mouse button was clicked (default: 0)." } ], @@ -3957,7 +3974,7 @@ { "name": "type", "type": "string", "enum": ["touchStart", "touchEnd", "touchMove"], "description": "Type of the touch event." }, { "name": "touchPoints", "type": "array", "items": { "$ref": "TouchPoint" }, "description": "Touch points." }, { "name": "modifiers", "type": "integer", "optional": true, "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0)." }, - { "name": "timestamp", "type": "number", "optional": true, "description": "Time at which the event occurred. Measured in UTC time in seconds since January 1, 1970 (default: current time)." } + { "name": "timestamp", "$ref": "TimeSinceEpoch", "optional": true, "description": "Time at which the event occurred." } ], "description": "Dispatches a touch event to the page." }, @@ -3968,7 +3985,7 @@ { "name": "type", "type": "string", "enum": ["mousePressed", "mouseReleased", "mouseMoved", "mouseWheel"], "description": "Type of the mouse event." }, { "name": "x", "type": "integer", "description": "X coordinate of the mouse pointer in DIP."}, { "name": "y", "type": "integer", "description": "Y coordinate of the mouse pointer in DIP."}, - { "name": "timestamp", "type": "number", "description": "Time at which the event occurred. Measured in UTC time in seconds since January 1, 1970." }, + { "name": "timestamp", "$ref": "TimeSinceEpoch", "description": "Time at which the event occurred." }, { "name": "button", "type": "string", "enum": ["none", "left", "middle", "right"], "description": "Mouse button." }, { "name": "deltaX", "type": "number", "optional": true, "description": "X delta in DIP for mouse wheel event (default: 0)."}, { "name": "deltaY", "type": "number", "optional": true, "description": "Y delta in DIP for mouse wheel event (default: 0)."},
diff --git a/third_party/WebKit/Source/core/layout/ng/geometry/ng_box_strut.h b/third_party/WebKit/Source/core/layout/ng/geometry/ng_box_strut.h index 5b70b24..6b91aca 100644 --- a/third_party/WebKit/Source/core/layout/ng/geometry/ng_box_strut.h +++ b/third_party/WebKit/Source/core/layout/ng/geometry/ng_box_strut.h
@@ -26,6 +26,13 @@ block_start(block_start), block_end(block_end) {} + LayoutUnit LineLeft(TextDirection direction) const { + return IsLtr(direction) ? inline_start : inline_end; + } + LayoutUnit LineRight(TextDirection direction) const { + return IsLtr(direction) ? inline_end : inline_start; + } + LayoutUnit InlineSum() const { return inline_start + inline_end; } LayoutUnit BlockSum() const { return block_start + block_end; }
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc index 4a35415f1..4f73b35 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.cc
@@ -51,7 +51,7 @@ // For the following lines, clear states that are not shared across lines. for (auto& box : stack_) { box.fragment_start = 0; - box.metrics = NGLineHeightMetrics(); + box.metrics = box.text_metrics; if (box.needs_box_fragment) { box.line_left_position = LayoutUnit(); // Existing box states are wrapped boxes, and hence no left edges. @@ -86,7 +86,8 @@ // Compute box properties regardless of needs_box_fragment since close tag may // also set needs_box_fragment. - box->line_left_position = position + item_result.margins.inline_start; + box->line_left_position = + position + item_result.margins.LineLeft(item.Style()->Direction()); box->borders_paddings_block_start = item_result.borders_paddings_block_start; box->borders_paddings_block_end = item_result.borders_paddings_block_end; return box; @@ -155,7 +156,8 @@ const NGInlineItemResult& item_result, LayoutUnit position) { DCHECK(needs_box_fragment); - line_right_position = position - item_result.margins.inline_end; + line_right_position = + position - item_result.margins.LineRight(item.Style()->Direction()); // We have right edge on close tag, and if the box does not have a // continuation. // TODO(kojii): Needs review when we change SplitInlines().
diff --git a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h index cbc48e7..20e6505 100644 --- a/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h +++ b/third_party/WebKit/Source/core/layout/ng/inline/ng_inline_box_state.h
@@ -36,8 +36,18 @@ unsigned fragment_start; const NGInlineItem* item; const ComputedStyle* style; + + // The united metrics for the current box. This includes all objects in this + // box, including descendants, and adjusted by placement properties such as + // 'vertical-align'. NGLineHeightMetrics metrics; + + // The metrics of the font for this box. This includes leadings as specified + // by the 'line-height' property. NGLineHeightMetrics text_metrics; + + // The distance between the text-top and the baseline for this box. The + // text-top does not include leadings. LayoutUnit text_top; // These values are to create a box fragment. Set only when needs_box_fragment
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 01b1c7f..d704839 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
@@ -282,6 +282,11 @@ NGTextFragmentBuilder* text_builder) { DCHECK(item_result->layout_result); + // The input |position| is the line-left edge of the margin box. + // Adjust it to the border box by adding the line-left margin. + const ComputedStyle& style = *item.Style(); + position += item_result->margins.LineLeft(style.Direction()); + NGInlineBoxState* box = box_states_.OnOpenTag(item, *item_result, line_box, position); @@ -312,7 +317,7 @@ // TODO(kojii): Try to eliminate the wrapping text fragment and use the // |fragment| directly. Currently |CopyFragmentDataToLayoutBlockFlow| // requires a text fragment. - text_builder->SetDirection(item.Style()->Direction()); + text_builder->SetDirection(style.Direction()); text_builder->SetSize({fragment.InlineSize(), block_size}); LayoutUnit line_top = item_result->margins.block_start - metrics.ascent; RefPtr<NGPhysicalTextFragment> text_fragment = text_builder->ToTextFragment(
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 9857544..771d4b4 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
@@ -255,6 +255,22 @@ intrinsic_logical_height -= border_scrollbar_padding.BlockSum(); box_->SetIntrinsicContentLogicalHeight(intrinsic_logical_height); + // LayoutBox::Margin*() should be used value, while we set computed value + // here. This is not entirely correct, but these values are not used for + // layout purpose. + // BaselinePosition() relies on margins set to the box, and computed value is + // good enough for it to work correctly. + // Set this only for atomic inlines, or we end up adding margins twice. + if (box_->IsAtomicInlineLevel()) { + NGBoxStrut margins = + ComputeMargins(constraint_space, Style(), + constraint_space.WritingMode(), Style().Direction()); + box_->SetMarginBefore(margins.block_start); + box_->SetMarginAfter(margins.block_end); + box_->SetMarginStart(margins.inline_start); + box_->SetMarginEnd(margins.inline_end); + } + // TODO(ikilpatrick) is this the right thing to do? if (box_->IsLayoutBlockFlow()) { ToLayoutBlockFlow(box_)->RemoveFloatingObjects();
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index 1561744d..315ac38 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -951,13 +951,6 @@ document->ParseAndSetReferrerPolicy(referrer_policy_header); } - if (RuntimeEnabledFeatures::ServerTimingEnabled() && - frame_->GetDocument()->domWindow()) { - DOMWindowPerformance::performance(*(frame_->GetDocument()->domWindow())) - ->AddServerTiming(response_, - PerformanceBase::ShouldAddToBuffer::Always); - } - GetLocalFrameClient().DidCreateNewDocument(); }
diff --git a/third_party/WebKit/Source/core/loader/EmptyClients.h b/third_party/WebKit/Source/core/loader/EmptyClients.h index 1fd1425e0..a2ae83f 100644 --- a/third_party/WebKit/Source/core/loader/EmptyClients.h +++ b/third_party/WebKit/Source/core/loader/EmptyClients.h
@@ -214,16 +214,6 @@ String AcceptLanguages() override; - CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient( - LocalFrame*) override { - return nullptr; - } - - AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient( - LocalFrame*) override { - return nullptr; - } - void RegisterPopupOpeningObserver(PopupOpeningObserver*) override {} void UnregisterPopupOpeningObserver(PopupOpeningObserver*) override {} void NotifyPopupOpeningObservers() const {}
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp index 37de975..3c745b8 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -468,18 +468,6 @@ // It is essential that inspector gets resource response BEFORE console. GetFrame()->Console().ReportResourceResponseReceived(document_loader, identifier, response); - - // MainResource responses were already added, skip them here. - if (RuntimeEnabledFeatures::ServerTimingEnabled() && - resource->GetType() != Resource::kMainResource && - GetFrame()->GetDocument() && GetFrame()->GetDocument()->domWindow()) { - LocalDOMWindow* localDOMWindow = GetFrame()->GetDocument()->domWindow(); - DOMWindowPerformance::performance(*localDOMWindow) - ->AddServerTiming(response, - localDOMWindow->HasLoadEventFired() - ? PerformanceBase::ShouldAddToBuffer::Never - : PerformanceBase::ShouldAddToBuffer::Always); - } } void FrameFetchContext::DispatchDidReceiveData(unsigned long identifier,
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index 0aca3ae0..dfcbd7e 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -503,8 +503,7 @@ if (!Client()) return false; Settings* settings = frame_->GetSettings(); - bool allowed = frame_->GetContentSettingsClient()->AllowPlugins( - settings && settings->GetPluginsEnabled()); + bool allowed = settings && settings->GetPluginsEnabled(); if (!allowed && reason == kAboutToInstantiatePlugin) frame_->GetContentSettingsClient()->DidNotAllowPlugins(); return allowed;
diff --git a/third_party/WebKit/Source/core/loader/LinkLoader.cpp b/third_party/WebKit/Source/core/loader/LinkLoader.cpp index 72bedc26..fce7864 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoader.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoader.cpp
@@ -477,21 +477,16 @@ cross_origin, network_hints_interface, kLinkCalledFromMarkup); - Resource* preloaded_resource = PreloadIfNeeded( + Resource* resource = PreloadIfNeeded( rel_attribute, href, document, as, type, media, cross_origin, kLinkCalledFromMarkup, nullptr, referrer_policy); - Resource* prefetched_resource = PrefetchIfNeeded( - document, href, rel_attribute, cross_origin, referrer_policy); - - DCHECK(!preloaded_resource || !prefetched_resource); - - if (preloaded_resource) { - finish_observer_ = new FinishObserver(this, preloaded_resource, - Resource::kDontMarkAsReferenced); + if (!resource) { + resource = PrefetchIfNeeded(document, href, rel_attribute, cross_origin, + referrer_policy); } - if (prefetched_resource) { - finish_observer_ = new FinishObserver(this, prefetched_resource, - Resource::kMarkAsReferenced); + if (resource) { + finish_observer_ = + new FinishObserver(this, resource, Resource::kDontMarkAsReferenced); } if (const unsigned prerender_rel_types =
diff --git a/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp b/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp index f1c61ad..12486195 100644 --- a/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp +++ b/third_party/WebKit/Source/core/loader/LinkLoaderTest.cpp
@@ -397,6 +397,27 @@ } } +TEST(LinkLoaderTest, PreloadAndPrefetch) { + std::unique_ptr<DummyPageHolder> dummy_page_holder = + DummyPageHolder::Create(IntSize(500, 500)); + ResourceFetcher* fetcher = dummy_page_holder->GetDocument().Fetcher(); + ASSERT_TRUE(fetcher); + dummy_page_holder->GetFrame().GetSettings()->SetScriptEnabled(true); + Persistent<MockLinkLoaderClient> loader_client = + MockLinkLoaderClient::Create(true); + LinkLoader* loader = LinkLoader::Create(loader_client.Get()); + KURL href_url = KURL(KURL(), "https://www.example.com/"); + URLTestHelpers::RegisterMockedErrorURLLoad(href_url); + loader->LoadLink(LinkRelAttribute("preload prefetch"), + kCrossOriginAttributeNotSet, "application/javascript", + "script", "", kReferrerPolicyDefault, href_url, + dummy_page_holder->GetDocument(), NetworkHintsMock()); + ASSERT_EQ(1, fetcher->CountPreloads()); + Resource* resource = loader->GetResourceForTesting(); + ASSERT_NE(resource, nullptr); + EXPECT_TRUE(resource->IsLinkPreload()); +} + } // namespace } // namespace blink
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp index 3a2af15..f1c6965b 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp
@@ -34,7 +34,6 @@ #include "core/dom/ExecutionContext.h" #include "core/loader/DocumentThreadableLoader.h" #include "core/loader/ThreadableLoadingContext.h" -#include "core/loader/WorkerFetchContext.h" #include "core/loader/WorkerThreadableLoader.h" #include "core/workers/WorkerGlobalScope.h" #include "platform/RuntimeEnabledFeatures.h" @@ -50,7 +49,7 @@ if (context.IsWorkerGlobalScope()) { if (RuntimeEnabledFeatures::OffMainThreadFetchEnabled()) { - DCHECK(ToWorkerGlobalScope(&context)->GetFetchContext()); + DCHECK(ToWorkerGlobalScope(&context)->GetResourceFetcher()); // TODO(horo): Rename DocumentThreadableLoader. We will use it on the // worker thread when off-main-thread-fetch is enabled. return DocumentThreadableLoader::Create(
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp index 09832e7a..3844961 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp +++ b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.cpp
@@ -23,11 +23,6 @@ return document_->Fetcher(); } - BaseFetchContext* GetFetchContext() override { - DCHECK(IsContextThread()); - return static_cast<BaseFetchContext*>(&document_->Fetcher()->Context()); - } - ExecutionContext* GetExecutionContext() override { DCHECK(IsContextThread()); return document_.Get(); @@ -48,40 +43,32 @@ public: explicit WorkerThreadableLoadingContext( WorkerGlobalScope& worker_global_scope) - : worker_global_scope_(&worker_global_scope), - fetch_context_(worker_global_scope.GetFetchContext()) {} + : worker_global_scope_(&worker_global_scope) {} ~WorkerThreadableLoadingContext() override = default; ResourceFetcher* GetResourceFetcher() override { DCHECK(IsContextThread()); - return fetch_context_->GetResourceFetcher(); - } - - BaseFetchContext* GetFetchContext() override { - DCHECK(IsContextThread()); - return fetch_context_.Get(); + return worker_global_scope_->GetResourceFetcher(); } ExecutionContext* GetExecutionContext() override { + DCHECK(IsContextThread()); return worker_global_scope_.Get(); } DEFINE_INLINE_VIRTUAL_TRACE() { - visitor->Trace(fetch_context_); visitor->Trace(worker_global_scope_); ThreadableLoadingContext::Trace(visitor); } private: bool IsContextThread() const { - DCHECK(fetch_context_); DCHECK(worker_global_scope_); return worker_global_scope_->IsContextThread(); } Member<WorkerGlobalScope> worker_global_scope_; - Member<WorkerFetchContext> fetch_context_; }; ThreadableLoadingContext* ThreadableLoadingContext::Create(Document& document) { @@ -93,4 +80,8 @@ return new WorkerThreadableLoadingContext(worker_global_scope); } +BaseFetchContext* ThreadableLoadingContext::GetFetchContext() { + return static_cast<BaseFetchContext*>(&GetResourceFetcher()->Context()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h index 761af14..1593886 100644 --- a/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h +++ b/third_party/WebKit/Source/core/loader/ThreadableLoadingContext.h
@@ -33,8 +33,8 @@ virtual ~ThreadableLoadingContext() = default; virtual ResourceFetcher* GetResourceFetcher() = 0; - virtual BaseFetchContext* GetFetchContext() = 0; virtual ExecutionContext* GetExecutionContext() = 0; + BaseFetchContext* GetFetchContext(); DEFINE_INLINE_VIRTUAL_TRACE() {} };
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp index 05e2bf2..8dd557a 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.cpp
@@ -89,13 +89,6 @@ loading_task_runner_->ToSingleThreadTaskRunner()); } -ResourceFetcher* WorkerFetchContext::GetResourceFetcher() { - if (resource_fetcher_) - return resource_fetcher_; - resource_fetcher_ = ResourceFetcher::Create(this, loading_task_runner_); - return resource_fetcher_; -} - KURL WorkerFetchContext::GetFirstPartyForCookies() const { return web_context_->FirstPartyForCookies(); } @@ -111,7 +104,7 @@ } SubresourceFilter* WorkerFetchContext::GetSubresourceFilter() const { - // TODO(horo): Implement this. + // TODO(horo): Implement this. (https://crbug.com/739597) return nullptr; }
diff --git a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h index b763ab9..4ef5bba4 100644 --- a/third_party/WebKit/Source/core/loader/WorkerFetchContext.h +++ b/third_party/WebKit/Source/core/loader/WorkerFetchContext.h
@@ -33,7 +33,6 @@ static WorkerFetchContext* Create(WorkerOrWorkletGlobalScope&); virtual ~WorkerFetchContext(); - ResourceFetcher* GetResourceFetcher(); RefPtr<WebTaskRunner> GetTaskRunner() { return loading_task_runner_; } // BaseFetchContext implementation:
diff --git a/third_party/WebKit/Source/core/mojo/BUILD.gn b/third_party/WebKit/Source/core/mojo/BUILD.gn index 202d78e..a445f29 100644 --- a/third_party/WebKit/Source/core/mojo/BUILD.gn +++ b/third_party/WebKit/Source/core/mojo/BUILD.gn
@@ -12,10 +12,10 @@ "MojoHandle.h", "MojoWatcher.cpp", "MojoWatcher.h", - "testing/MojoInterfaceInterceptor.cpp", - "testing/MojoInterfaceInterceptor.h", - "testing/MojoInterfaceRequestEvent.cpp", - "testing/MojoInterfaceRequestEvent.h", + "test/MojoInterfaceInterceptor.cpp", + "test/MojoInterfaceInterceptor.h", + "test/MojoInterfaceRequestEvent.cpp", + "test/MojoInterfaceRequestEvent.h", ] deps = [
diff --git a/third_party/WebKit/Source/core/mojo/Mojo.cpp b/third_party/WebKit/Source/core/mojo/Mojo.cpp index 47f53e41..5ab2d3cf 100644 --- a/third_party/WebKit/Source/core/mojo/Mojo.cpp +++ b/third_party/WebKit/Source/core/mojo/Mojo.cpp
@@ -6,7 +6,7 @@ #include <string> -#include "core/frame/LocalDOMWindow.h" +#include "core/dom/Document.h" #include "core/frame/LocalFrame.h" #include "core/frame/LocalFrameClient.h" #include "core/mojo/MojoCreateDataPipeOptions.h" @@ -14,8 +14,11 @@ #include "core/mojo/MojoCreateMessagePipeResult.h" #include "core/mojo/MojoCreateSharedBufferResult.h" #include "core/mojo/MojoHandle.h" +#include "core/workers/WorkerGlobalScope.h" +#include "core/workers/WorkerThread.h" #include "mojo/public/cpp/system/message_pipe.h" #include "platform/bindings/ScriptState.h" +#include "platform/wtf/text/StringUTF8Adaptor.h" #include "services/service_manager/public/cpp/interface_provider.h" namespace blink { @@ -77,13 +80,24 @@ void Mojo::bindInterface(ScriptState* script_state, const String& interface_name, MojoHandle* request_handle) { - LocalDOMWindow::From(script_state) - ->GetFrame() - ->Client() - ->GetInterfaceProvider() - ->GetInterface( - std::string(interface_name.Utf8().data()), - mojo::ScopedMessagePipeHandle::From(request_handle->TakeHandle())); + std::string name = + StringUTF8Adaptor(interface_name).AsStringPiece().as_string(); + auto handle = + mojo::ScopedMessagePipeHandle::From(request_handle->TakeHandle()); + + ExecutionContext* context = ExecutionContext::From(script_state); + if (context->IsWorkerGlobalScope()) { + WorkerThread* thread = ToWorkerGlobalScope(context)->GetThread(); + thread->GetInterfaceProvider().GetInterface(name, std::move(handle)); + return; + } + + LocalFrame* frame = ToDocument(context)->GetFrame(); + if (!frame) + return; // |handle| will be destroyed, closing the pipe. + + frame->Client()->GetInterfaceProvider()->GetInterface(name, + std::move(handle)); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/mojo/Mojo.idl b/third_party/WebKit/Source/core/mojo/Mojo.idl index f9e87944..df7e12e1 100644 --- a/third_party/WebKit/Source/core/mojo/Mojo.idl +++ b/third_party/WebKit/Source/core/mojo/Mojo.idl
@@ -8,6 +8,7 @@ [ ContextEnabled=MojoJS, + Exposed=(Window,Worker), RuntimeEnabled=MojoJS ] interface Mojo { const MojoResult RESULT_OK = 0;
diff --git a/third_party/WebKit/Source/core/mojo/MojoHandle.idl b/third_party/WebKit/Source/core/mojo/MojoHandle.idl index 029c7005e..4fe2ab2 100644 --- a/third_party/WebKit/Source/core/mojo/MojoHandle.idl +++ b/third_party/WebKit/Source/core/mojo/MojoHandle.idl
@@ -6,6 +6,7 @@ [ ContextEnabled=MojoJS, + Exposed=(Window,Worker), RuntimeEnabled=MojoJS ] interface MojoHandle { void close();
diff --git a/third_party/WebKit/Source/core/mojo/MojoWatcher.idl b/third_party/WebKit/Source/core/mojo/MojoWatcher.idl index b0e34971..1b370a8 100644 --- a/third_party/WebKit/Source/core/mojo/MojoWatcher.idl +++ b/third_party/WebKit/Source/core/mojo/MojoWatcher.idl
@@ -5,6 +5,7 @@ [ ActiveScriptWrappable, DependentLifetime, + Exposed=(Window,Worker), ContextEnabled=MojoJS, RuntimeEnabled=MojoJS ] interface MojoWatcher {
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.cpp b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp similarity index 70% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.cpp rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp index d46c2a88..3e930b7 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.cpp +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.cpp
@@ -2,15 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "core/mojo/testing/MojoInterfaceInterceptor.h" +#include "core/mojo/test/MojoInterfaceInterceptor.h" #include "bindings/core/v8/ExceptionState.h" +#include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h" #include "core/frame/LocalFrameClient.h" #include "core/mojo/MojoHandle.h" -#include "core/mojo/testing/MojoInterfaceRequestEvent.h" +#include "core/mojo/test/MojoInterfaceRequestEvent.h" +#include "core/workers/WorkerGlobalScope.h" +#include "core/workers/WorkerThread.h" #include "platform/bindings/ScriptState.h" #include "platform/wtf/text/StringUTF8Adaptor.h" #include "services/service_manager/public/cpp/interface_provider.h" @@ -30,10 +33,18 @@ if (started_) return; + service_manager::InterfaceProvider* interface_provider = + GetInterfaceProvider(); + if (!interface_provider) { + exception_state.ThrowDOMException(kInvalidStateError, + "The interface provider is unavailable."); + return; + } + std::string interface_name = StringUTF8Adaptor(interface_name_).AsStringPiece().as_string(); - service_manager::InterfaceProvider::TestApi test_api( - GetFrame()->Client()->GetInterfaceProvider()); + + service_manager::InterfaceProvider::TestApi test_api(interface_provider); if (test_api.HasBinderForName(interface_name)) { exception_state.ThrowDOMException( kInvalidModificationError, @@ -54,8 +65,9 @@ return; started_ = false; - service_manager::InterfaceProvider::TestApi test_api( - GetFrame()->Client()->GetInterfaceProvider()); + // GetInterfaceProvider() is guaranteed not to return nullptr because this + // method is called when the context is destroyed. + service_manager::InterfaceProvider::TestApi test_api(GetInterfaceProvider()); std::string interface_name = StringUTF8Adaptor(interface_name_).AsStringPiece().as_string(); DCHECK(test_api.HasBinderForName(interface_name)); @@ -88,6 +100,22 @@ : ContextLifecycleObserver(ExecutionContext::From(script_state)), interface_name_(interface_name) {} +service_manager::InterfaceProvider* +MojoInterfaceInterceptor::GetInterfaceProvider() const { + ExecutionContext* context = GetExecutionContext(); + if (!context) + return nullptr; + + if (context->IsWorkerGlobalScope()) + return &ToWorkerGlobalScope(context)->GetThread()->GetInterfaceProvider(); + + LocalFrame* frame = ToDocument(context)->GetFrame(); + if (!frame) + return nullptr; + + return frame->Client()->GetInterfaceProvider(); +} + void MojoInterfaceInterceptor::OnInterfaceRequest( mojo::ScopedMessagePipeHandle handle) { DispatchEvent(MojoInterfaceRequestEvent::Create(
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.h b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.h similarity index 94% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.h rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.h index 4c7ce0d..ff73826 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.h +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.h
@@ -13,6 +13,10 @@ #include "platform/bindings/ScriptWrappable.h" #include "platform/wtf/text/WTFString.h" +namespace service_manager { +class InterfaceProvider; +} + namespace blink { class ExceptionState; @@ -59,6 +63,7 @@ MojoInterfaceInterceptor(ScriptState*, const String& interface_name); + service_manager::InterfaceProvider* GetInterfaceProvider() const; void OnInterfaceRequest(mojo::ScopedMessagePipeHandle); const String interface_name_;
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.idl b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.idl similarity index 94% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.idl rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.idl index e295564..0edcc16 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceInterceptor.idl +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceInterceptor.idl
@@ -7,6 +7,7 @@ Constructor(DOMString interfaceName), ConstructorCallWith=ScriptState, DependentLifetime, + Exposed=(Window,Worker), RuntimeEnabled=MojoJSTest ] interface MojoInterfaceInterceptor : EventTarget { [RaisesException] void start();
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.cpp b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.cpp similarity index 86% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.cpp rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.cpp index a25cd08..6974e84 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.cpp +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.cpp
@@ -2,9 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "core/mojo/testing/MojoInterfaceRequestEvent.h" +#include "core/mojo/test/MojoInterfaceRequestEvent.h" #include "core/mojo/MojoHandle.h" +#include "core/mojo/test/MojoInterfaceRequestEventInit.h" namespace blink {
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.h b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.h similarity index 95% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.h rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.h index db63af9..d97804492 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.h +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.h
@@ -6,11 +6,11 @@ #define MojoInterfaceRequestEvent_h #include "core/events/Event.h" -#include "core/mojo/testing/MojoInterfaceRequestEventInit.h" namespace blink { class MojoHandle; +class MojoInterfaceRequestEventInit; // An event dispatched to a MojoInterfaceInterceptor when its frame sends an // outgoing request for the interface it was configured to intercept. The event
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.idl b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.idl similarity index 92% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.idl rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.idl index f01e4cf..9d96d25 100644 --- a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEvent.idl +++ b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEvent.idl
@@ -4,6 +4,7 @@ [ Constructor(DOMString type, optional MojoInterfaceRequestEventInit eventInitDict), + Exposed=(Window,Worker), RuntimeEnabled=MojoJSTest ] interface MojoInterfaceRequestEvent : Event { readonly attribute MojoHandle handle;
diff --git a/third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEventInit.idl b/third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEventInit.idl similarity index 100% rename from third_party/WebKit/Source/core/mojo/testing/MojoInterfaceRequestEventInit.idl rename to third_party/WebKit/Source/core/mojo/test/MojoInterfaceRequestEventInit.idl
diff --git a/third_party/WebKit/Source/core/page/ChromeClient.h b/third_party/WebKit/Source/core/page/ChromeClient.h index 04d2392..42b0028 100644 --- a/third_party/WebKit/Source/core/page/ChromeClient.h +++ b/third_party/WebKit/Source/core/page/ChromeClient.h
@@ -55,7 +55,6 @@ class ColorChooser; class ColorChooserClient; -class CompositorWorkerProxyClient; class CompositorAnimationTimeline; class DateTimeChooser; class DateTimeChooserClient; @@ -220,12 +219,12 @@ const Color&) = 0; // This function is used for: - // - Mandatory date/time choosers if !ENABLE(INPUT_MULTIPLE_FIELDS_UI) + // - Mandatory date/time choosers if InputMultipleFieldsUI flag is not set // - Date/time choosers for types for which - // LayoutTheme::supportsCalendarPicker returns true, if - // ENABLE(INPUT_MULTIPLE_FIELDS_UI) + // LayoutTheme::SupportsCalendarPicker returns true, if + // InputMultipleFieldsUI flag is set // - <datalist> UI for date/time input types regardless of - // ENABLE(INPUT_MULTIPLE_FIELDS_UI) + // InputMultipleFieldsUI flag virtual DateTimeChooser* OpenDateTimeChooser( DateTimeChooserClient*, const DateTimeChooserParameters&) = 0; @@ -332,11 +331,6 @@ virtual void UnregisterPopupOpeningObserver(PopupOpeningObserver*) = 0; virtual void NotifyPopupOpeningObservers() const = 0; - virtual CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient( - LocalFrame*) = 0; - virtual AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient( - LocalFrame*) = 0; - virtual FloatSize ElasticOverscroll() const { return FloatSize(); } // Called when observed XHR, fetch, and other fetch request with non-GET
diff --git a/third_party/WebKit/Source/core/page/ValidationMessageClientImpl.cpp b/third_party/WebKit/Source/core/page/ValidationMessageClientImpl.cpp index 173d58ae..8fb7218 100644 --- a/third_party/WebKit/Source/core/page/ValidationMessageClientImpl.cpp +++ b/third_party/WebKit/Source/core/page/ValidationMessageClientImpl.cpp
@@ -32,6 +32,7 @@ #include "core/frame/WebLocalFrameBase.h" #include "core/page/ChromeClient.h" #include "core/page/ValidationMessageOverlayDelegate.h" +#include "platform/LayoutTestSupport.h" #include "platform/PlatformChromeClient.h" #include "platform/wtf/CurrentTime.h" #include "public/platform/WebRect.h" @@ -141,7 +142,9 @@ void ValidationMessageClientImpl::CheckAnchorStatus(TimerBase*) { DCHECK(current_anchor_); - if (MonotonicallyIncreasingTime() >= finish_time_ || !CurrentView()) { + if ((!LayoutTestSupport::IsRunningLayoutTest() && + MonotonicallyIncreasingTime() >= finish_time_) || + !CurrentView()) { HideValidationMessage(*current_anchor_); return; }
diff --git a/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.cpp b/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.cpp index 00c27c8..3d2dadb 100644 --- a/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.cpp +++ b/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.cpp
@@ -4,10 +4,13 @@ #include "core/page/ValidationMessageOverlayDelegate.h" +#include "core/dom/Element.h" #include "core/frame/Settings.h" #include "core/frame/VisualViewport.h" #include "core/loader/EmptyClients.h" #include "core/page/Page.h" +#include "core/page/PagePopupClient.h" +#include "platform/LayoutTestSupport.h" #include "platform/graphics/paint/CullRect.h" namespace blink { @@ -42,7 +45,12 @@ TextDirection message_dir, const String& sub_message, TextDirection sub_message_dir) - : main_page_(page) {} + : main_page_(page), + anchor_(anchor), + message_(message), + sub_message_(sub_message), + message_dir_(message_dir), + sub_message_dir_(sub_message_dir) {} std::unique_ptr<ValidationMessageOverlayDelegate> ValidationMessageOverlayDelegate::Create(Page& page, @@ -84,6 +92,7 @@ FrameView().Resize(view_size); page_->GetVisualViewport().SetSize(view_size); } + AdjustBubblePosition(view_size); FrameView().UpdateAllLifecyclePhases(); } @@ -114,11 +123,92 @@ page_->GetVisualViewport().SetSize(view_size); RefPtr<SharedBuffer> data = SharedBuffer::Create(); - // TODO(tkent): Pour HTML into |data|. + WriteDocument(data.Get()); frame->Loader().Load( FrameLoadRequest(nullptr, ResourceRequest(BlankURL()), SubstituteData(data, "text/html", "UTF-8", KURL(), kForceSynchronousLoad))); + + Element& container = BubbleContainer(); + if (LayoutTestSupport::IsRunningLayoutTest()) + container.SetInlineStyleProperty(CSSPropertyTransition, "none"); + // Get the size to decide position later. + FrameView().UpdateAllLifecyclePhases(); + bubble_size_ = container.VisibleBoundsInVisualViewport().Size(); + // Add one because the content sometimes exceeds the exact width due to + // rounding errors. + container.SetInlineStyleProperty(CSSPropertyMinWidth, + bubble_size_.Width() + 1, + CSSPrimitiveValue::UnitType::kPixels); +} + +void ValidationMessageOverlayDelegate::WriteDocument(SharedBuffer* data) { + DCHECK(data); + PagePopupClient::AddString("<!DOCTYPE html><html><head><style>", data); + data->Append(Platform::Current()->GetDataResource("validation_bubble.css")); + PagePopupClient::AddString( + "</style></head><body>" + "<div id=container>" + "<div id=outer-arrow-top></div>" + "<div id=inner-arrow-top></div>" + "<main id=bubble-body>", + data); + data->Append(Platform::Current()->GetDataResource("input_alert.svg")); + PagePopupClient::AddString(message_dir_ == TextDirection::kLtr + ? "<div dir=ltr id=main-message>" + : "<div dir=rtl id=main-message>", + data); + PagePopupClient::AddString(message_, data); + PagePopupClient::AddString(sub_message_dir_ == TextDirection::kLtr + ? "</div><div dir=ltr id=sub-message>" + : "</div><div dir=rtl id=sub-message>", + data); + PagePopupClient::AddString(sub_message_, data); + PagePopupClient::AddString( + "</div></main>" + "<div id=outer-arrow-bottom></div>" + "<div id=inner-arrow-bottom></div>" + "</div></body></html>\n", + data); +} + +Element& ValidationMessageOverlayDelegate::BubbleContainer() const { + Element* container = ToLocalFrame(page_->MainFrame()) + ->GetDocument() + ->getElementById("container"); + DCHECK(container) << "Failed to load the document?"; + return *container; +} + +void ValidationMessageOverlayDelegate::AdjustBubblePosition( + const IntSize& view_size) { + IntRect anchor_rect = anchor_->VisibleBoundsInVisualViewport(); + bool show_bottom_arrow = false; + double bubble_y = anchor_rect.MaxY(); + if (view_size.Height() - anchor_rect.MaxY() < bubble_size_.Height()) { + bubble_y = anchor_rect.Y() - bubble_size_.Height(); + show_bottom_arrow = true; + } + double bubble_x = + anchor_rect.X() + anchor_rect.Width() / 2 - bubble_size_.Width() / 2; + if (bubble_x < 0) + bubble_x = 0; + else if (bubble_x + bubble_size_.Width() > view_size.Width()) + bubble_x = view_size.Width() - bubble_size_.Width(); + + Element& container = BubbleContainer(); + container.SetInlineStyleProperty(CSSPropertyLeft, bubble_x, + CSSPrimitiveValue::UnitType::kPixels); + container.SetInlineStyleProperty(CSSPropertyTop, bubble_y, + CSSPrimitiveValue::UnitType::kPixels); + container.SetInlineStyleProperty(CSSPropertyOpacity, 1.0, + CSSPrimitiveValue::UnitType::kNumber); + if (show_bottom_arrow) + container.setAttribute(HTMLNames::classAttr, "bottom-arrow"); + else + container.removeAttribute(HTMLNames::classAttr); + + // TODO(tkent): Adjust arrow position. } } // namespace blink
diff --git a/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.h b/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.h index 06baa59..cdf1334 100644 --- a/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.h +++ b/third_party/WebKit/Source/core/page/ValidationMessageOverlayDelegate.h
@@ -48,13 +48,24 @@ LocalFrameView& FrameView() const; void UpdateFrameViewState(const PageOverlay&, const IntSize& view_size); void EnsurePage(const PageOverlay&, const IntSize& view_size); + void WriteDocument(SharedBuffer*); + Element& BubbleContainer() const; + void AdjustBubblePosition(const IntSize& view_size); // An internal Page and a ChromeClient for it. Persistent<Page> page_; Persistent<ChromeClient> chrome_client_; + IntSize bubble_size_; + // A page which triggered this validation message. Persistent<Page> main_page_; + + Persistent<const Element> anchor_; + String message_; + String sub_message_; + TextDirection message_dir_; + TextDirection sub_message_dir_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp index e5b641f..9ee9c82 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilder.cpp
@@ -979,7 +979,11 @@ auto* scrollable_area = box.GetScrollableArea(); IntSize scroll_offset = box.ScrolledContentOffset(); - IntSize scroll_clip = scrollable_area->VisibleContentRect().Size(); + auto clip_rect = box.OverflowClipRect(context.current.paint_offset); + // The container bounds are snapped to integers to match the equivalent + // bounds on cc::ScrollNode. + IntSize container_bounds = PixelSnappedIntRect(clip_rect).Size(); + IntSize scroll_bounds = scrollable_area->ContentsSize(); bool user_scrollable_horizontal = scrollable_area->UserInputScrollable(kHorizontalScrollbar); @@ -1007,7 +1011,7 @@ CompositorElementIdFromLayoutObjectId( object.UniqueId(), CompositorElementIdNamespace::kScrollTranslation), - context.current.scroll, scroll_clip, scroll_bounds, + context.current.scroll, container_bounds, scroll_bounds, user_scrollable_horizontal, user_scrollable_vertical, reasons, scrollable_area); force_subtree_update |= result.NewNodeCreated();
diff --git a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp index b597984..77295e0 100644 --- a/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp +++ b/third_party/WebKit/Source/core/paint/PaintPropertyTreeBuilderTest.cpp
@@ -2669,6 +2669,7 @@ " overflow: hidden;" " width: 5px;" " height: 3px;" + " border: 1px solid black;" " }" " .forceScroll {" " height: 79px;" @@ -2693,7 +2694,8 @@ EXPECT_TRUE(overflow_hidden_scroll_node->Parent()->IsRoot()); EXPECT_EQ(TransformationMatrix().Translate(0, -37), scroll_translation->Matrix()); - // This should match the overflow's dimensions. + // This should match the overflow's dimensions and should not include the + // box's border. EXPECT_EQ(IntSize(5, 3), overflow_hidden_scroll_node->ContainerBounds()); // The scrolling content's bounds should include both the overflow's // dimensions (5x3) and the 0x79 "forceScroll" object.
diff --git a/third_party/WebKit/Source/core/style/BUILD.gn b/third_party/WebKit/Source/core/style/BUILD.gn index c5ad69c..8f147a0 100644 --- a/third_party/WebKit/Source/core/style/BUILD.gn +++ b/third_party/WebKit/Source/core/style/BUILD.gn
@@ -33,7 +33,6 @@ "CursorData.h", "CursorList.h", "DataEquivalency.h", - "DataPersistent.h", "DataRef.h", "FillLayer.cpp", "FillLayer.h",
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.cpp b/third_party/WebKit/Source/core/style/ComputedStyle.cpp index 4fa3b1d..15b31bd 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.cpp +++ b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
@@ -686,7 +686,7 @@ bool other_has_clip = other.HasOutOfFlowPosition() && !other.HasAutoClipInternal(); if (has_clip != other_has_clip || - (has_clip && ClipInternal() != other.ClipInternal())) + (has_clip && Clip() != other.Clip())) diff.SetCSSClipChanged(); }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.h b/third_party/WebKit/Source/core/style/ComputedStyle.h index 99186c69..e38b036 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.h +++ b/third_party/WebKit/Source/core/style/ComputedStyle.h
@@ -307,7 +307,7 @@ } FilterOperations& MutableBackdropFilter() { DCHECK(BackdropFilterInternal().Get()); - return MutableBackdropFilterInternal().Access()->operations_; + return MutableBackdropFilterInternal()->operations_; } bool HasBackdropFilter() const { DCHECK(BackdropFilterInternal().Get()); @@ -316,14 +316,17 @@ void SetBackdropFilter(const FilterOperations& ops) { DCHECK(BackdropFilterInternal().Get()); if (BackdropFilterInternal()->operations_ != ops) - MutableBackdropFilterInternal().Access()->operations_ = ops; + MutableBackdropFilterInternal()->operations_ = ops; + } + bool BackdropFilterDataEquivalent(const ComputedStyle& o) const { + return DataEquivalent(BackdropFilterInternal(), o.BackdropFilterInternal()); } // filter (aka -webkit-filter) static const FilterOperations& InitialFilter(); FilterOperations& MutableFilter() { DCHECK(FilterInternal().Get()); - return MutableFilterInternal().Access()->operations_; + return MutableFilterInternal()->operations_; } const FilterOperations& Filter() const { DCHECK(FilterInternal().Get()); @@ -336,15 +339,16 @@ void SetFilter(const FilterOperations& v) { DCHECK(FilterInternal().Get()); if (FilterInternal()->operations_ != v) - MutableFilterInternal().Access()->operations_ = v; + MutableFilterInternal()->operations_ = v; + } + bool FilterDataEquivalent(const ComputedStyle& o) const { + return DataEquivalent(FilterInternal(), o.FilterInternal()); } // Background properties. // background-color static Color InitialBackgroundColor() { return Color::kTransparent; } - void SetBackgroundColor(const StyleColor& v) { - SetBackgroundColorInternal(v); - } + // background-image bool HasBackgroundImage() const { return BackgroundInternal().HasImage(); } @@ -480,7 +484,6 @@ // clip static LengthBox InitialClip() { return LengthBox(); } - const LengthBox& Clip() const { return ClipInternal(); } void SetClip(const LengthBox& box) { SetHasAutoClipInternal(false); SetClipInternal(box); @@ -494,7 +497,6 @@ // Column properties. // column-count (aka -webkit-column-count) static unsigned short InitialColumnCount() { return 1; } - unsigned short ColumnCount() const { return ColumnCountInternal(); } void SetColumnCount(unsigned short c) { SetColumnAutoCountInternal(false); SetColumnCountInternal(c); @@ -506,7 +508,6 @@ } // column-gap (aka -webkit-column-gap) - float ColumnGap() const { return ColumnGapInternal(); } void SetColumnGap(float f) { SetColumnNormalGapInternal(false); SetColumnGapInternal(f); @@ -538,7 +539,6 @@ } // column-width (aka -webkit-column-width) - float ColumnWidth() const { return ColumnWidthInternal(); } void SetColumnWidth(float f) { SetColumnAutoWidthInternal(false); SetColumnWidthInternal(f); @@ -551,8 +551,6 @@ // contain static Containment InitialContain() { return kContainsNone; } - Containment Contain() const { return ContainInternal(); } - void SetContain(Containment contain) { SetContainInternal(contain); } // content ContentData* GetContentData() const { return ContentInternal().Get(); } @@ -560,7 +558,6 @@ // -webkit-box-ordinal-group static unsigned InitialBoxOrdinalGroup() { return 1; } - unsigned BoxOrdinalGroup() const { return BoxOrdinalGroupInternal(); } void SetBoxOrdinalGroup(unsigned og) { SetBoxOrdinalGroupInternal( std::min(std::numeric_limits<unsigned>::max() - 1, og)); @@ -574,11 +571,9 @@ // grid-auto-flow static GridAutoFlow InitialGridAutoFlow() { return kAutoFlowRow; } - void SetGridAutoFlow(GridAutoFlow flow) { SetGridAutoFlowInternal(flow); } // opacity (aka -webkit-opacity) static float InitialOpacity() { return 1.0f; } - float Opacity() const { return OpacityInternal(); } void SetOpacity(float f) { float v = clampTo<float>(f, 0, 1); SetOpacityInternal(v); @@ -604,7 +599,6 @@ // order (aka -webkit-order) static int InitialOrder() { return 0; } - int Order() const { return OrderInternal(); } // We restrict the smallest value to int min + 2 because we use int min and // int min + 1 as special values in a hash set. void SetOrder(int o) { @@ -652,7 +646,6 @@ return 0; return OutlineOffsetInternal(); } - void SetOutlineOffset(int v) { SetOutlineOffsetInternal(v); } // -webkit-perspective-origin-x static Length InitialPerspectiveOriginX() { return Length(50.0, kPercent); } @@ -673,10 +666,6 @@ static EmptyTransformOperations InitialTransform() { return EmptyTransformOperations(); } - const TransformOperations& Transform() const { return TransformInternal(); } - void SetTransform(const TransformOperations& ops) { - SetTransformInternal(ops); - } // -webkit-transform-origin-x static Length InitialTransformOriginX() { return Length(50.0, kPercent); } @@ -705,8 +694,6 @@ // Scroll properties. // scroll-behavior static ScrollBehavior InitialScrollBehavior() { return kScrollBehaviorAuto; } - ScrollBehavior GetScrollBehavior() const { return ScrollBehaviorInternal(); } - void SetScrollBehavior(ScrollBehavior b) { SetScrollBehaviorInternal(b); } // scroll-padding-block-start const Length& ScrollPaddingBlockStart() const { @@ -804,7 +791,6 @@ // shape-image-threshold (aka -webkit-shape-image-threshold) static float InitialShapeImageThreshold() { return 0; } - float ShapeImageThreshold() const { return ShapeImageThresholdInternal(); } void SetShapeImageThreshold(float shape_image_threshold) { float clamped_shape_image_threshold = clampTo<float>(shape_image_threshold, 0, 1); @@ -814,7 +800,6 @@ // shape-outside (aka -webkit-shape-outside) static ShapeValue* InitialShapeOutside() { return 0; } ShapeValue* ShapeOutside() const { return ShapeOutsideInternal().Get(); } - void SetShapeOutside(ShapeValue* value) { SetShapeOutsideInternal(value); } bool ShapeOutsideDataEquivalent(const ComputedStyle& other) const { return DataEquivalent(ShapeOutside(), other.ShapeOutside()); } @@ -824,19 +809,11 @@ static TextDecorationSkip InitialTextDecorationSkip() { return TextDecorationSkip::kObjects; } - TextDecorationSkip GetTextDecorationSkip() const { - return TextDecorationSkipInternal(); - } - void SetTextDecorationSkip(TextDecorationSkip v) { - SetTextDecorationSkipInternal(v); - } // touch-action static TouchAction InitialTouchAction() { return TouchAction::kTouchActionAuto; } - TouchAction GetTouchAction() const { return TouchActionInternal(); } - void SetTouchAction(TouchAction t) { return SetTouchActionInternal(t); } // vertical-align static EVerticalAlign InitialVerticalAlign() { @@ -853,7 +830,6 @@ } // z-index - int ZIndex() const { return ZIndexInternal(); } bool HasAutoZIndex() const { return HasAutoZIndexInternal(); } void SetZIndex(int v) { SetHasAutoZIndexInternal(false); @@ -865,16 +841,13 @@ } // zoom - static float InitialZoom() { return 1.0f; } - float Zoom() const { return ZoomInternal(); } float EffectiveZoom() const { return EffectiveZoomInternal(); } bool SetZoom(float); bool SetEffectiveZoom(float); // -webkit-appearance static ControlPart InitialAppearance() { return kNoControlPart; } - ControlPart Appearance() const { return AppearanceInternal(); } - void SetAppearance(ControlPart a) { SetAppearanceInternal(a); } + // -webkit-clip-path bool ClipPathDataEquivalent(const ComputedStyle& other) const { @@ -1232,12 +1205,12 @@ } bool ColumnRuleEquivalent(const ComputedStyle& other_style) const; void InheritColumnPropertiesFrom(const ComputedStyle& parent) { - SetColumnGapInternal(parent.ColumnGapInternal()); - SetColumnWidthInternal(parent.ColumnWidthInternal()); + SetColumnGapInternal(parent.ColumnGap()); + SetColumnWidthInternal(parent.ColumnWidth()); SetVisitedLinkColumnRuleColorInternal( parent.VisitedLinkColumnRuleColorInternal()); SetColumnRuleColorInternal(parent.ColumnRuleColorInternal()); - SetColumnCountInternal(parent.ColumnCountInternal()); + SetColumnCountInternal(parent.ColumnCount()); SetColumnRuleStyle(parent.ColumnRuleStyle()); SetColumnAutoCountInternal(parent.ColumnAutoCountInternal()); SetColumnAutoWidthInternal(parent.ColumnAutoWidthInternal()); @@ -1887,10 +1860,10 @@ } // Clip utility functions. - const Length& ClipLeft() const { return ClipInternal().Left(); } - const Length& ClipRight() const { return ClipInternal().Right(); } - const Length& ClipTop() const { return ClipInternal().Top(); } - const Length& ClipBottom() const { return ClipInternal().Bottom(); } + const Length& ClipLeft() const { return Clip().Left(); } + const Length& ClipRight() const { return Clip().Right(); } + const Length& ClipTop() const { return Clip().Top(); } + const Length& ClipBottom() const { return Clip().Bottom(); } // Offset utility functions. // Accessors for positioned object edges that take into account writing mode. @@ -2023,7 +1996,7 @@ // Filter/transform utility functions. bool Has3DTransform() const { - return TransformInternal().Has3DOperation() || + return Transform().Has3DOperation() || (Translate() && Translate()->Z() != 0) || (Rotate() && (Rotate()->X() != 0 || Rotate()->Y() != 0)) || (Scale() && Scale()->Z() != 1); @@ -2033,7 +2006,7 @@ HasCurrentTransformAnimation() || Translate() || Rotate() || Scale(); } bool HasTransformOperations() const { - return !TransformInternal().Operations().IsEmpty(); + return !Transform().Operations().IsEmpty(); } ETransformStyle3D UsedTransformStyle3D() const { return HasGroupingProperty() ? ETransformStyle3D::kFlat @@ -2599,7 +2572,7 @@ } inline bool ComputedStyle::SetZoom(float f) { - if (ZoomInternal() == f) + if (Zoom() == f) return false; SetZoomInternal(f); SetEffectiveZoom(EffectiveZoom() * Zoom());
diff --git a/third_party/WebKit/Source/core/style/DataEquivalency.h b/third_party/WebKit/Source/core/style/DataEquivalency.h index f233462..4951191 100644 --- a/third_party/WebKit/Source/core/style/DataEquivalency.h +++ b/third_party/WebKit/Source/core/style/DataEquivalency.h
@@ -14,8 +14,6 @@ class Persistent; template <typename T> class Member; -template <typename T> -class DataPersistent; template <typename T> bool DataEquivalent(const T* a, const T* b) { @@ -46,11 +44,6 @@ return DataEquivalent(a.get(), b.get()); } -template <typename T> -bool DataEquivalent(const DataPersistent<T>& a, const DataPersistent<T>& b) { - return DataEquivalent(a.Get(), b.Get()); -} - } // namespace blink #endif // DataEquivalency_h
diff --git a/third_party/WebKit/Source/core/style/DataPersistent.h b/third_party/WebKit/Source/core/style/DataPersistent.h deleted file mode 100644 index 5b5feae..0000000 --- a/third_party/WebKit/Source/core/style/DataPersistent.h +++ /dev/null
@@ -1,101 +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 DataPersistent_h -#define DataPersistent_h - -#include <memory> -#include "platform/heap/Handle.h" -#include "platform/wtf/Allocator.h" -#include "platform/wtf/PtrUtil.h" - -namespace blink { - -// DataPersistent<T> provides the copy-on-modify behavior of DataRef<>, -// but for Persistent<> heap references. -// -// That is, the DataPersistent<T> copy assignment, |a = b;|, makes |a| -// share a reference to the T object that |b| holds until |a| is mutated -// and access() on it is called. Or, dually, if |b| is mutated after the -// assignment that mutation isn't observable to |a| but will be performed -// on a copy of the underlying T object. -// -// DataPersistent<T> does assume that no one keeps non-DataPersistent<> shared -// references to the underlying T object that it manages, and is mutating the -// object via those. -template <typename T> -class DataPersistent { - USING_FAST_MALLOC(DataPersistent); - - public: - DataPersistent() - : data_(WTF::WrapUnique(new Persistent<T>(T::Create()))), - own_copy_(true) {} - - DataPersistent(std::nullptr_t) : data_(nullptr), own_copy_(false) {} - - DataPersistent(const DataPersistent& other) : own_copy_(false) { - if (other.data_) - data_ = WTF::WrapUnique(new Persistent<T>(other.data_->Get())); - - // Invalidated, subsequent mutations will happen on a new copy. - // - // (Clearing |m_ownCopy| will not be observable over T, hence - // the const_cast<> is considered acceptable here.) - const_cast<DataPersistent&>(other).own_copy_ = false; - } - - DataPersistent(DataPersistent&& other) - : data_(std::move(other.data_)), own_copy_(other.own_copy_) { - other.own_copy_ = false; - } - - const T* Get() const { return data_ ? data_->Get() : nullptr; } - - const T& operator*() const { return data_ ? *Get() : nullptr; } - const T* operator->() const { return Get(); } - - T* Access() { - if (data_ && !own_copy_) { - *data_ = (*data_)->Copy(); - own_copy_ = true; - } - return data_ ? data_->Get() : nullptr; - } - - void Init() { - DCHECK(!data_); - data_ = WTF::WrapUnique(new Persistent<T>(T::Create())); - own_copy_ = true; - } - - bool operator==(const DataPersistent<T>& o) const { - DCHECK(data_); - DCHECK(o.data_); - return data_->Get() == o.data_->Get() || *data_->Get() == *o.data_->Get(); - } - - bool operator!=(const DataPersistent<T>& o) const { - DCHECK(data_); - DCHECK(o.data_); - return data_->Get() != o.data_->Get() && *data_->Get() != *o.data_->Get(); - } - - void operator=(std::nullptr_t) { data_.clear(); } - DataPersistent& operator=(DataPersistent&& other) { - data_ = std::move(other.data_); - own_copy_ = other.own_copy_; - other.own_copy_ = false; - return *this; - } - - private: - // Reduce size of DataPersistent<> by delaying creation of Persistent<>. - std::unique_ptr<Persistent<T>> data_; - unsigned own_copy_ : 1; -}; - -} // namespace blink - -#endif // DataPersistent_h
diff --git a/third_party/WebKit/Source/core/style/MemberCopy.h b/third_party/WebKit/Source/core/style/MemberCopy.h index efe0c2a..2cb6ad2 100644 --- a/third_party/WebKit/Source/core/style/MemberCopy.h +++ b/third_party/WebKit/Source/core/style/MemberCopy.h
@@ -7,8 +7,8 @@ #include <memory> #include "core/style/ContentData.h" -#include "core/style/DataPersistent.h" #include "core/style/DataRef.h" +#include "core/style/StyleFilterData.h" #include "platform/heap/Persistent.h" #include "platform/wtf/RefPtr.h" @@ -29,15 +29,15 @@ return v ? v->Clone() : nullptr; } -template <typename T> -DataPersistent<T> MemberCopy(const DataPersistent<T>& v) { - return v; -} - inline Persistent<ContentData> MemberCopy(const Persistent<ContentData>& v) { return v ? v->Clone() : nullptr; } +inline Persistent<StyleFilterData> MemberCopy( + const Persistent<StyleFilterData>& v) { + return v->Copy(); +} + } // namespace blink #endif // MemberCopy_h
diff --git a/third_party/WebKit/Source/core/timing/Performance.cpp b/third_party/WebKit/Source/core/timing/Performance.cpp index a60c520b..e32c306 100644 --- a/third_party/WebKit/Source/core/timing/Performance.cpp +++ b/third_party/WebKit/Source/core/timing/Performance.cpp
@@ -146,7 +146,11 @@ ResourceTimingInfo* info = document_loader->GetNavigationTimingInfo(); if (!info) return nullptr; - return new PerformanceNavigationTiming(GetFrame(), info, TimeOrigin()); + PerformanceServerTimingVector serverTiming = + PerformanceServerTiming::ParseServerTiming( + *info, PerformanceServerTiming::ShouldAllowTimingDetails::Yes); + return new PerformanceNavigationTiming(GetFrame(), info, TimeOrigin(), + serverTiming); } void Performance::UpdateLongTaskInstrumentation() {
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp index 904e27f9..42bf93446 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.cpp
@@ -42,7 +42,6 @@ #include "core/timing/PerformanceLongTaskTiming.h" #include "core/timing/PerformanceObserver.h" #include "core/timing/PerformanceResourceTiming.h" -#include "core/timing/PerformanceServerTiming.h" #include "core/timing/PerformanceUserTiming.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/loader/fetch/ResourceResponse.h" @@ -66,7 +65,6 @@ static const size_t kDefaultResourceTimingBufferSize = 150; static const size_t kDefaultFrameTimingBufferSize = 150; -static const size_t kServerTimingBufferSize = 150; PerformanceBase::PerformanceBase(double time_origin, RefPtr<WebTaskRunner> task_runner) @@ -107,7 +105,6 @@ entries.AppendVector(user_timing_->GetMeasures()); } - entries.AppendVector(server_timing_buffer_); if (first_paint_timing_) entries.push_back(first_paint_timing_); if (first_contentful_paint_timing_) @@ -151,9 +148,6 @@ if (user_timing_) entries.AppendVector(user_timing_->GetMeasures()); break; - case PerformanceEntry::kServer: - entries.AppendVector(server_timing_buffer_); - break; case PerformanceEntry::kPaint: if (first_paint_timing_) entries.push_back(first_paint_timing_); @@ -216,15 +210,6 @@ entries.AppendVector(user_timing_->GetMeasures(name)); } - if (entry_type.IsNull() || type == PerformanceEntry::kServer) { - // This is inefficient, but this buffer has a max size of - // 150 entries (controlled by kServerTimingBufferSize). - for (const auto& entry : server_timing_buffer_) { - if (entry->name() == name) - entries.push_back(entry); - } - } - std::sort(entries.begin(), entries.end(), PerformanceEntry::StartTimeCompareLessThan); return entries; @@ -306,45 +291,6 @@ return true; } -void PerformanceBase::AddServerTiming(const ResourceResponse& response, - ShouldAddToBuffer shouldAddToBuffer) { - if (shouldAddToBuffer == ShouldAddToBuffer::Never && - !HasObserverFor(PerformanceEntry::kServer)) { - return; - } - - ExecutionContext* context = GetExecutionContext(); - SecurityOrigin* securityOrigin = GetSecurityOrigin(context); - if (!securityOrigin) { - return; - } - bool allowTimingDetails = PassesTimingAllowCheck( - response, *securityOrigin, - response.HttpHeaderField(HTTPNames::Timing_Allow_Origin), context); - - std::unique_ptr<ServerTimingHeaderVector> headers = ParseServerTimingHeader( - response.HttpHeaderField(HTTPNames::Server_Timing)); - if ((*headers).size() == 0) { - return; - } - - PerformanceEntryVector entries; - for (const auto& header : *headers) { - PerformanceEntry* entry = PerformanceServerTiming::create( - response.Url().GetString(), header->metric, - allowTimingDetails ? header->duration : 0.0, - allowTimingDetails ? header->description : ""); - entries.push_back(*entry); - } - - NotifyObserversOfEntries(entries); - if (shouldAddToBuffer == ShouldAddToBuffer::Always && - server_timing_buffer_.size() + entries.size() <= - kServerTimingBufferSize) { - server_timing_buffer_.AppendVector(entries); - } -} - void PerformanceBase::AddResourceTiming(const ResourceTimingInfo& info) { if (IsResourceTimingBufferFull() && !HasObserverFor(PerformanceEntry::kResource)) @@ -360,9 +306,15 @@ info.OriginalTimingAllowOrigin(), context); double start_time = info.InitialTime(); + PerformanceServerTimingVector serverTiming = + PerformanceServerTiming::ParseServerTiming( + info, allow_timing_details + ? PerformanceServerTiming::ShouldAllowTimingDetails::Yes + : PerformanceServerTiming::ShouldAllowTimingDetails::No); + if (info.RedirectChain().IsEmpty()) { PerformanceEntry* entry = PerformanceResourceTiming::Create( - info, TimeOrigin(), start_time, allow_timing_details); + info, TimeOrigin(), start_time, allow_timing_details, serverTiming); NotifyObserversOfEntry(*entry); if (!IsResourceTimingBufferFull()) AddResourceTimingBuffer(*entry); @@ -387,7 +339,7 @@ PerformanceEntry* entry = PerformanceResourceTiming::Create( info, TimeOrigin(), start_time, last_redirect_end_time, - allow_timing_details, allow_redirect_details); + allow_timing_details, allow_redirect_details, serverTiming); NotifyObserversOfEntry(*entry); if (!IsResourceTimingBufferFull()) AddResourceTimingBuffer(*entry); @@ -612,7 +564,6 @@ visitor->Trace(resource_timing_buffer_); visitor->Trace(navigation_timing_); visitor->Trace(user_timing_); - visitor->Trace(server_timing_buffer_); visitor->Trace(first_paint_timing_); visitor->Trace(first_contentful_paint_timing_); visitor->Trace(observers_);
diff --git a/third_party/WebKit/Source/core/timing/PerformanceBase.h b/third_party/WebKit/Source/core/timing/PerformanceBase.h index ff36a6a..9d8fc5d1 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceBase.h +++ b/third_party/WebKit/Source/core/timing/PerformanceBase.h
@@ -112,12 +112,6 @@ void AddResourceTiming(const ResourceTimingInfo&); - enum class ShouldAddToBuffer { - Always, - Never, - }; - void AddServerTiming(const ResourceResponse&, ShouldAddToBuffer); - void NotifyNavigationTimingToObservers(); void AddFirstPaintTiming(double start_time); @@ -179,7 +173,6 @@ unsigned frame_timing_buffer_size_; PerformanceEntryVector resource_timing_buffer_; unsigned resource_timing_buffer_size_; - PerformanceEntryVector server_timing_buffer_; Member<PerformanceEntry> navigation_timing_; Member<UserTiming> user_timing_; Member<PerformanceEntry> first_paint_timing_;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp b/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp index 9afabfb..9e74757 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp
@@ -83,19 +83,18 @@ return kTaskAttribution; if (entry_type == "paint") return kPaint; - if (entry_type == "server") - return kServer; return kInvalid; } ScriptValue PerformanceEntry::toJSONForBinding( ScriptState* script_state) const { V8ObjectBuilder result(script_state); - BuildJSONValue(result); + BuildJSONValue(script_state, result); return result.GetScriptValue(); } -void PerformanceEntry::BuildJSONValue(V8ObjectBuilder& builder) const { +void PerformanceEntry::BuildJSONValue(ScriptState* script_state, + V8ObjectBuilder& builder) const { builder.AddString("name", name()); builder.AddString("entryType", entryType()); builder.AddNumber("startTime", startTime());
diff --git a/third_party/WebKit/Source/core/timing/PerformanceEntry.h b/third_party/WebKit/Source/core/timing/PerformanceEntry.h index 9067ec9..2f74ff3 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceEntry.h +++ b/third_party/WebKit/Source/core/timing/PerformanceEntry.h
@@ -65,8 +65,7 @@ kResource = 1 << 5, kLongTask = 1 << 6, kTaskAttribution = 1 << 7, - kPaint = 1 << 8, - kServer = 1 << 9 + kPaint = 1 << 8 }; String name() const; @@ -102,7 +101,7 @@ const String& entry_type, double start_time, double finish_time); - virtual void BuildJSONValue(V8ObjectBuilder&) const; + virtual void BuildJSONValue(ScriptState*, V8ObjectBuilder&) const; private: const String name_;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.cpp b/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.cpp index f0263af90..df433a2 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.cpp
@@ -18,11 +18,13 @@ PerformanceNavigationTiming::PerformanceNavigationTiming( LocalFrame* frame, ResourceTimingInfo* info, - double time_origin) + double time_origin, + PerformanceServerTimingVector& serverTiming) : PerformanceResourceTiming(info ? info->InitialURL().GetString() : "", "navigation", 0.0, - 0.0), + 0.0, + serverTiming), ContextClient(frame), time_origin_(time_origin), resource_timing_info_(info) { @@ -34,7 +36,7 @@ DEFINE_TRACE(PerformanceNavigationTiming) { ContextClient::Trace(visitor); - PerformanceEntry::Trace(visitor); + PerformanceResourceTiming::Trace(visitor); } DocumentLoadTiming* PerformanceNavigationTiming::GetDocumentLoadTiming() const { @@ -264,8 +266,9 @@ } void PerformanceNavigationTiming::BuildJSONValue( + ScriptState* script_state, V8ObjectBuilder& builder) const { - PerformanceResourceTiming::BuildJSONValue(builder); + PerformanceResourceTiming::BuildJSONValue(script_state, builder); builder.AddNumber("unloadEventStart", unloadEventStart()); builder.AddNumber("unloadEventEnd", unloadEventEnd()); builder.AddNumber("domInteractive", domInteractive());
diff --git a/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.h b/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.h index baf431eb..62050d4 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.h +++ b/third_party/WebKit/Source/core/timing/PerformanceNavigationTiming.h
@@ -32,7 +32,8 @@ public: PerformanceNavigationTiming(LocalFrame*, ResourceTimingInfo*, - double time_origin); + double time_origin, + PerformanceServerTimingVector&); // Attributes inheritted from PerformanceEntry. DOMHighResTimeStamp duration() const override; @@ -60,7 +61,7 @@ DECLARE_VIRTUAL_TRACE(); protected: - void BuildJSONValue(V8ObjectBuilder&) const override; + void BuildJSONValue(ScriptState*, V8ObjectBuilder&) const override; private: ~PerformanceNavigationTiming() override;
diff --git a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp index 7133ad5..20cb249 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp
@@ -45,7 +45,8 @@ double start_time, double last_redirect_end_time, bool allow_timing_details, - bool allow_redirect_details) + bool allow_redirect_details, + PerformanceServerTimingVector& serverTiming) : PerformanceEntry(info.InitialURL().GetString(), "resource", PerformanceBase::MonotonicTimeToDOMHighResTimeStamp( @@ -69,14 +70,18 @@ did_reuse_connection_(info.FinalResponse().ConnectionReused()), allow_timing_details_(allow_timing_details), allow_redirect_details_(allow_redirect_details), - allow_negative_value_(info.NegativeAllowed()) {} + allow_negative_value_(info.NegativeAllowed()), + serverTiming_(serverTiming) {} // This constructor is for PerformanceNavigationTiming. -PerformanceResourceTiming::PerformanceResourceTiming(const String& name, - const String& entry_type, - double start_time, - double duration) - : PerformanceEntry(name, entry_type, start_time, duration) {} +PerformanceResourceTiming::PerformanceResourceTiming( + const String& name, + const String& entry_type, + double start_time, + double duration, + PerformanceServerTimingVector& serverTiming) + : PerformanceEntry(name, entry_type, start_time, duration), + serverTiming_(serverTiming) {} PerformanceResourceTiming::~PerformanceResourceTiming() {} @@ -307,8 +312,13 @@ return GetDecodedBodySize(); } -void PerformanceResourceTiming::BuildJSONValue(V8ObjectBuilder& builder) const { - PerformanceEntry::BuildJSONValue(builder); +PerformanceServerTimingVector PerformanceResourceTiming::serverTiming() const { + return serverTiming_; +} + +void PerformanceResourceTiming::BuildJSONValue(ScriptState* script_state, + V8ObjectBuilder& builder) const { + PerformanceEntry::BuildJSONValue(script_state, builder); builder.AddString("initiatorType", initiatorType()); builder.AddString("nextHopProtocol", nextHopProtocol()); builder.AddNumber("workerStart", workerStart()); @@ -326,6 +336,17 @@ builder.AddNumber("transferSize", transferSize()); builder.AddNumber("encodedBodySize", encodedBodySize()); builder.AddNumber("decodedBodySize", decodedBodySize()); + + Vector<ScriptValue> serverTiming; + for (unsigned i = 0; i < serverTiming_.size(); i++) { + serverTiming.push_back(serverTiming_[i]->toJSONForBinding(script_state)); + } + builder.Add("serverTiming", serverTiming); +} + +DEFINE_TRACE(PerformanceResourceTiming) { + visitor->Trace(serverTiming_); + PerformanceEntry::Trace(visitor); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h index 45f5d4e0..805add0 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h +++ b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h
@@ -34,6 +34,7 @@ #include "core/dom/DOMHighResTimeStamp.h" #include "core/timing/PerformanceEntry.h" +#include "core/timing/PerformanceServerTiming.h" #include "platform/heap/Handle.h" #include "platform/wtf/Forward.h" @@ -48,23 +49,28 @@ public: ~PerformanceResourceTiming() override; - static PerformanceResourceTiming* Create(const ResourceTimingInfo& info, - double time_origin, - double start_time, - double last_redirect_end_time, - bool allow_timing_details, - bool allow_redirect_details) { + static PerformanceResourceTiming* Create( + const ResourceTimingInfo& info, + double time_origin, + double start_time, + double last_redirect_end_time, + bool allow_timing_details, + bool allow_redirect_details, + PerformanceServerTimingVector& serverTiming) { return new PerformanceResourceTiming( info, time_origin, start_time, last_redirect_end_time, - allow_timing_details, allow_redirect_details); + allow_timing_details, allow_redirect_details, serverTiming); } - static PerformanceResourceTiming* Create(const ResourceTimingInfo& info, - double time_origin, - double start_time, - bool allow_timing_details) { + static PerformanceResourceTiming* Create( + const ResourceTimingInfo& info, + double time_origin, + double start_time, + bool allow_timing_details, + PerformanceServerTimingVector& serverTiming) { return new PerformanceResourceTiming(info, time_origin, start_time, 0.0, - allow_timing_details, false); + allow_timing_details, false, + serverTiming); } // Related doc: https://goo.gl/uNecAj. virtual AtomicString initiatorType() const; @@ -84,16 +90,20 @@ unsigned long long transferSize() const; unsigned long long encodedBodySize() const; unsigned long long decodedBodySize() const; + PerformanceServerTimingVector serverTiming() const; + + DECLARE_VIRTUAL_TRACE(); protected: - void BuildJSONValue(V8ObjectBuilder&) const override; + void BuildJSONValue(ScriptState*, V8ObjectBuilder&) const override; // This constructor is for PerformanceNavigationTiming. // Related doc: https://goo.gl/uNecAj. PerformanceResourceTiming(const String& name, const String& entry_type, double start_time, - double duration); + double duration, + PerformanceServerTimingVector&); virtual AtomicString AlpnNegotiatedProtocol() const; virtual AtomicString ConnectionInfo() const; @@ -103,7 +113,8 @@ double start_time, double last_redirect_end_time, bool allow_timing_details, - bool allow_redirect_details); + bool allow_redirect_details, + PerformanceServerTimingVector&); static AtomicString GetNextHopProtocol( const AtomicString& alpn_negotiated_protocol, @@ -132,6 +143,7 @@ bool allow_timing_details_; bool allow_redirect_details_; bool allow_negative_value_; + PerformanceServerTimingVector serverTiming_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl index 27cd520..eb7b281 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl +++ b/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl
@@ -49,6 +49,7 @@ [MeasureAs=PerformanceResourceTimingSizes] readonly attribute unsigned long long transferSize; [MeasureAs=PerformanceResourceTimingSizes] readonly attribute unsigned long long encodedBodySize; [MeasureAs=PerformanceResourceTimingSizes] readonly attribute unsigned long long decodedBodySize; + [RuntimeEnabled=ServerTiming] readonly attribute FrozenArray<PerformanceServerTiming> serverTiming; // TODO(foolip): The spec has a serializer: // serializer = {inherit, attribute}; };
diff --git a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.cpp b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.cpp index 120613c..597b765 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.cpp +++ b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.cpp
@@ -5,18 +5,20 @@ #include "core/timing/PerformanceServerTiming.h" #include "bindings/core/v8/V8ObjectBuilder.h" -#include "core/timing/PerformanceBase.h" +#include "platform/loader/fetch/ResourceTimingInfo.h" #include "platform/wtf/text/WTFString.h" namespace blink { -PerformanceServerTiming::PerformanceServerTiming(const String& name, - const String& metric, - double duration, - const String& description) - : PerformanceEntry(name, "server", 0.0, duration), - metric_(metric), - description_(description) {} +PerformanceServerTiming::PerformanceServerTiming( + const String& metric, + double value, + const String& description, + ShouldAllowTimingDetails shouldAllowTimingDetails) + : metric_(metric), + value_(value), + description_(description), + shouldAllowTimingDetails_(shouldAllowTimingDetails) {} PerformanceServerTiming::~PerformanceServerTiming() {} @@ -24,14 +26,41 @@ return metric_; } -String PerformanceServerTiming::description() const { - return description_; +double PerformanceServerTiming::value() const { + return shouldAllowTimingDetails_ == ShouldAllowTimingDetails::Yes ? value_ + : 0.0; } -void PerformanceServerTiming::BuildJSONValue(V8ObjectBuilder& builder) const { - PerformanceEntry::BuildJSONValue(builder); +String PerformanceServerTiming::description() const { + return shouldAllowTimingDetails_ == ShouldAllowTimingDetails::Yes + ? description_ + : ""; +} + +ScriptValue PerformanceServerTiming::toJSONForBinding( + ScriptState* script_state) const { + V8ObjectBuilder builder(script_state); builder.AddString("metric", metric()); + builder.AddNumber("value", value()); builder.AddString("description", description()); + return builder.GetScriptValue(); +} + +PerformanceServerTimingVector PerformanceServerTiming::ParseServerTiming( + const ResourceTimingInfo& info, + ShouldAllowTimingDetails shouldAllowTimingDetails) { + PerformanceServerTimingVector entries; + if (RuntimeEnabledFeatures::ServerTimingEnabled()) { + const ResourceResponse& response = info.FinalResponse(); + std::unique_ptr<ServerTimingHeaderVector> headers = ParseServerTimingHeader( + response.HttpHeaderField(HTTPNames::Server_Timing)); + for (const auto& header : *headers) { + entries.push_back(new PerformanceServerTiming( + header->metric, header->value, header->description, + shouldAllowTimingDetails)); + } + } + return entries; } } // namespace blink
diff --git a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.h b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.h index 814dfe41..815bb363 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.h +++ b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.h
@@ -5,37 +5,52 @@ #ifndef PerformanceServerTiming_h #define PerformanceServerTiming_h -#include "core/timing/PerformanceEntry.h" +#include "bindings/core/v8/V8ObjectBuilder.h" +#include "platform/bindings/ScriptWrappable.h" +#include "platform/wtf/text/WTFString.h" namespace blink { -class CORE_EXPORT PerformanceServerTiming : public PerformanceEntry { +class ResourceTimingInfo; +class PerformanceServerTiming; + +using PerformanceServerTimingVector = + HeapVector<Member<PerformanceServerTiming>>; + +class CORE_EXPORT PerformanceServerTiming final + : public GarbageCollectedFinalized<PerformanceServerTiming>, + public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: - ~PerformanceServerTiming() override; + enum class ShouldAllowTimingDetails { + Yes, + No, + }; - static PerformanceServerTiming* create(const String& name, - const String& metric, - double duration, - const String& description) { - return new PerformanceServerTiming(name, metric, duration, description); - } + PerformanceServerTiming(const String& metric, + double value, + const String& description, + ShouldAllowTimingDetails); + ~PerformanceServerTiming(); String metric() const; + double value() const; String description() const; - protected: - void BuildJSONValue(V8ObjectBuilder&) const override; + static PerformanceServerTimingVector ParseServerTiming( + const ResourceTimingInfo&, + ShouldAllowTimingDetails); + + ScriptValue toJSONForBinding(ScriptState*) const; + + DEFINE_INLINE_VIRTUAL_TRACE() {} private: - PerformanceServerTiming(const String& name, - const String& metric, - double duration, - const String& description); - const String metric_; + double value_; const String description_; + ShouldAllowTimingDetails shouldAllowTimingDetails_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.idl b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.idl index 608aa15..fd4069e 100644 --- a/third_party/WebKit/Source/core/timing/PerformanceServerTiming.idl +++ b/third_party/WebKit/Source/core/timing/PerformanceServerTiming.idl
@@ -6,7 +6,8 @@ [ RuntimeEnabled=ServerTiming -] interface PerformanceServerTiming : PerformanceEntry { +] interface PerformanceServerTiming { readonly attribute DOMString metric; + readonly attribute double value; readonly attribute DOMString description; };
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp index 0639420..117baf3 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.cpp
@@ -8,6 +8,7 @@ #include "core/dom/TaskRunnerHelper.h" #include "core/frame/Deprecation.h" #include "core/inspector/ConsoleMessage.h" +#include "core/loader/WorkerFetchContext.h" #include "core/probe/CoreProbes.h" #include "core/workers/WorkerReportingProxy.h" #include "core/workers/WorkerThread.h" @@ -56,13 +57,15 @@ ReportDeprecation(feature); } -WorkerFetchContext* WorkerOrWorkletGlobalScope::GetFetchContext() { +ResourceFetcher* WorkerOrWorkletGlobalScope::GetResourceFetcher() { DCHECK(RuntimeEnabledFeatures::OffMainThreadFetchEnabled()); DCHECK(!IsMainThreadWorkletGlobalScope()); - if (fetch_context_) - return fetch_context_; - fetch_context_ = WorkerFetchContext::Create(*this); - return fetch_context_; + if (resource_fetcher_) + return resource_fetcher_; + WorkerFetchContext* fetch_context = WorkerFetchContext::Create(*this); + resource_fetcher_ = + ResourceFetcher::Create(fetch_context, fetch_context->GetTaskRunner()); + return resource_fetcher_; } bool WorkerOrWorkletGlobalScope::IsJSExecutionForbidden() const { @@ -83,15 +86,14 @@ script_controller_->Dispose(); script_controller_.Clear(); - if (fetch_context_) { - ResourceFetcher* fetcher = fetch_context_->GetResourceFetcher(); - fetcher->StopFetching(); - fetcher->ClearContext(); + if (resource_fetcher_) { + resource_fetcher_->StopFetching(); + resource_fetcher_->ClearContext(); } } DEFINE_TRACE(WorkerOrWorkletGlobalScope) { - visitor->Trace(fetch_context_); + visitor->Trace(resource_fetcher_); visitor->Trace(script_controller_); ExecutionContext::Trace(visitor); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h index 63686cd..4810215 100644 --- a/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h +++ b/third_party/WebKit/Source/core/workers/WorkerOrWorkletGlobalScope.h
@@ -7,11 +7,11 @@ #include "core/dom/ExecutionContext.h" #include "core/frame/UseCounter.h" -#include "core/loader/WorkerFetchContext.h" #include "core/workers/WorkerClients.h" namespace blink { +class ResourceFetcher; class ScriptWrappable; class WorkerOrWorkletScriptController; class WorkerThread; @@ -51,7 +51,7 @@ virtual WorkerThread* GetThread() const = 0; // Available only when off-main-thread-fetch is enabled. - WorkerFetchContext* GetFetchContext(); + ResourceFetcher* GetResourceFetcher(); WorkerClients* Clients() const { return worker_clients_.Get(); } @@ -67,7 +67,7 @@ private: CrossThreadPersistent<WorkerClients> worker_clients_; - Member<WorkerFetchContext> fetch_context_; + Member<ResourceFetcher> resource_fetcher_; Member<WorkerOrWorkletScriptController> script_controller_; // This is the set of features that this worker has used.
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp index 26ad839..a3a75aa 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -46,6 +46,7 @@ #include "core/workers/WorkerThreadStartupData.h" #include "platform/CrossThreadFunctional.h" #include "platform/Histogram.h" +#include "platform/RuntimeEnabledFeatures.h" #include "platform/WaitableEvent.h" #include "platform/WebThreadSupportingGC.h" #include "platform/bindings/Microtask.h" @@ -59,15 +60,26 @@ #include "platform/wtf/PtrUtil.h" #include "platform/wtf/Threading.h" #include "platform/wtf/text/WTFString.h" +#include "public/platform/InterfaceProvider.h" #include "public/platform/Platform.h" namespace blink { using ExitCode = WorkerThread::ExitCode; +namespace { + // TODO(nhiroki): Adjust the delay based on UMA. constexpr TimeDelta kForcibleTerminationDelay = TimeDelta::FromSeconds(2); +void ForwardInterfaceRequest(const std::string& name, + mojo::ScopedMessagePipeHandle handle) { + Platform::Current()->GetInterfaceProvider()->GetInterface(name.c_str(), + std::move(handle)); +} + +} // namespace + static Mutex& ThreadSetMutex() { DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ()); return mutex; @@ -304,12 +316,11 @@ return exit_code_; } -InterfaceProvider* WorkerThread::GetInterfaceProvider() { - // TODO(https://crbug.com/734210): Instead of returning this interface - // provider, which maps to a RenderProcessHost in the browser process, this - // method should return an interface provider which maps to a specific worker - // context such as a SharedWorkerHost or EmbeddedWorkerInstance. - return Platform::Current()->GetInterfaceProvider(); +service_manager::InterfaceProvider& WorkerThread::GetInterfaceProvider() { + // TODO(https://crbug.com/734210): Instead of forwarding to the process-wide + // interface provider a worker-specific interface provider pipe should be + // passed in as part of the WorkerThreadStartupData. + return interface_provider_; } WorkerThread::WorkerThread(ThreadableLoadingContext* loading_context, @@ -326,6 +337,8 @@ DCHECK(IsMainThread()); MutexLocker lock(ThreadSetMutex()); WorkerThreads().insert(this); + interface_provider_.Forward( + ConvertToBaseCallback(WTF::Bind(&ForwardInterfaceRequest))); } bool WorkerThread::ShouldScheduleToTerminateExecution(const MutexLocker& lock) { @@ -447,7 +460,8 @@ String source_code; std::unique_ptr<Vector<char>> cached_meta_data; - if (GetInstalledScriptsManager() && + if (RuntimeEnabledFeatures::ServiceWorkerScriptStreamingEnabled() && + GetInstalledScriptsManager() && GetInstalledScriptsManager()->IsScriptInstalled(script_url)) { // TODO(shimazu): Set ContentSecurityPolicy, ReferrerPolicy and // OriginTrialTokens to |startup_data|.
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.h b/third_party/WebKit/Source/core/workers/WorkerThread.h index ef5b0c0..815143c0 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.h +++ b/third_party/WebKit/Source/core/workers/WorkerThread.h
@@ -42,6 +42,7 @@ #include "platform/wtf/Functional.h" #include "platform/wtf/PassRefPtr.h" #include "public/platform/WebThread.h" +#include "services/service_manager/public/cpp/interface_provider.h" #include "v8/include/v8.h" namespace blink { @@ -49,7 +50,6 @@ class ConsoleMessageStorage; class InspectorTaskRunner; class InstalledScriptsManager; -class InterfaceProvider; class WorkerBackingThread; class WorkerInspectorController; class WorkerOrWorkletGlobalScope; @@ -160,7 +160,7 @@ return global_scope_scheduler_.get(); } - InterfaceProvider* GetInterfaceProvider(); + service_manager::InterfaceProvider& GetInterfaceProvider(); // For ServiceWorkerScriptStreaming. Returns nullptr otherwise. virtual InstalledScriptsManager* GetInstalledScriptsManager() { @@ -263,6 +263,10 @@ CrossThreadPersistent<ParentFrameTaskRunners> parent_frame_task_runners_; + // Mojo interface provider serving interface requests scoped to this worker + // context. + service_manager::InterfaceProvider interface_provider_; + // Tasks managed by this scheduler are canceled when the global scope is // closed. std::unique_ptr<scheduler::WorkerGlobalScopeScheduler>
diff --git a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp index 071c7027..a07e29b 100644 --- a/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp +++ b/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -456,10 +456,7 @@ if (error_occurred) { script_loader->DispatchErrorEvent(); - } else { - // TODO(hiroshige): Remove |was_canceled| once it is confirmed that this - // CHECK never fails. - CHECK(!was_canceled); + } else if (!was_canceled) { if (script_parser_blocking_time > 0.0) { DocumentParserTiming::From(*GetDocument()) .RecordParserBlockedOnScriptLoadDuration(
diff --git a/third_party/WebKit/Source/devtools/BUILD.gn b/third_party/WebKit/Source/devtools/BUILD.gn index 377f7fa2..1aee815 100644 --- a/third_party/WebKit/Source/devtools/BUILD.gn +++ b/third_party/WebKit/Source/devtools/BUILD.gn
@@ -320,11 +320,13 @@ "front_end/main/RequestAppBannerActionDelegate.js", "front_end/main/SimpleApp.js", "front_end/main/targetCrashedScreen.css", - "front_end/mobile_throttling/CPUThrottlingManager.js", + "front_end/mobile_throttling/MobileThrottlingSelector.js", "front_end/mobile_throttling/module.json", - "front_end/mobile_throttling/NetworkConditionsSelector.js", - "front_end/mobile_throttling/networkConditionsSettingsTab.css", - "front_end/mobile_throttling/NetworkConditionsSettingsTab.js", + "front_end/mobile_throttling/NetworkThrottlingSelector.js", + "front_end/mobile_throttling/ThrottlingManager.js", + "front_end/mobile_throttling/ThrottlingPresets.js", + "front_end/mobile_throttling/throttlingSettingsTab.css", + "front_end/mobile_throttling/ThrottlingSettingsTab.js", "front_end/network/blockedURLsPane.css", "front_end/network/BlockedURLsPane.js", "front_end/network/eventSourceMessagesView.css",
diff --git a/third_party/WebKit/Source/devtools/front_end/Tests.js b/third_party/WebKit/Source/devtools/front_end/Tests.js index d761fbcb..837870dd 100644 --- a/third_party/WebKit/Source/devtools/front_end/Tests.js +++ b/third_party/WebKit/Source/devtools/front_end/Tests.js
@@ -697,19 +697,19 @@ function step1() { testPreset( - MobileThrottling.NetworkConditionsSelector.presets[0], + MobileThrottling.networkPresets[2], ['offline event: online = false', 'connection change event: type = none; downlinkMax = 0'], step2); } function step2() { testPreset( - MobileThrottling.NetworkConditionsSelector.presets[1], + MobileThrottling.networkPresets[1], ['online event: online = true', 'connection change event: type = cellular; downlinkMax = 0.390625'], step3); } function step3() { testPreset( - MobileThrottling.NetworkConditionsSelector.presets[2], + MobileThrottling.networkPresets[0], ['connection change event: type = cellular; downlinkMax = 1.4400000000000002'], test.releaseControl.bind(test)); }
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AXBreadcrumbsPane.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AXBreadcrumbsPane.js index 417b495aa..72de23e 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AXBreadcrumbsPane.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AXBreadcrumbsPane.js
@@ -25,7 +25,7 @@ this._rootElement.addEventListener('mousemove', this._onMouseMove.bind(this), false); this._rootElement.addEventListener('mouseleave', this._onMouseLeave.bind(this), false); this._rootElement.addEventListener('click', this._onClick.bind(this), false); - + this._rootElement.addEventListener('contextmenu', this._contextMenuEventFired.bind(this), false); this.registerRequiredCSS('accessibility/axBreadcrumbs.css'); } @@ -237,6 +237,31 @@ return true; } + + /** + * @param {!Event} event + */ + _contextMenuEventFired(event) { + var breadcrumbElement = event.target.enclosingNodeOrSelfWithClass('ax-node'); + if (!breadcrumbElement) + return; + + var axNode = breadcrumbElement.breadcrumb.axNode(); + if (!axNode.isDOMNode() || !axNode.deferredDOMNode()) + return; + + var contextMenu = new UI.ContextMenu(event); + contextMenu.appendItem(Common.UIString('Scroll into view'), () => { + axNode.deferredDOMNode().resolvePromise().then(domNode => { + if (!domNode) + return; + domNode.scrollIntoView(); + }); + }); + + contextMenu.appendApplicableItems(axNode.deferredDOMNode()); + contextMenu.show(); + } }; Accessibility.AXBreadcrumb = class {
diff --git a/third_party/WebKit/Source/devtools/front_end/emulated_devices/module.json b/third_party/WebKit/Source/devtools/front_end/emulated_devices/module.json index 4ea61a83..50f6e89 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulated_devices/module.json +++ b/third_party/WebKit/Source/devtools/front_end/emulated_devices/module.json
@@ -500,13 +500,13 @@ "title": "Nokia N9", "screen": { "horizontal": { - "width": 640, - "height": 360 + "width": 854, + "height": 480 }, "device-pixel-ratio": 1, "vertical": { - "width": 360, - "height": 640 + "width": 480, + "height": 854 } }, "capabilities": [ @@ -717,13 +717,13 @@ "title": "Kindle Fire HDX", "screen": { "horizontal": { - "width": 2560, - "height": 1600 + "width": 1280, + "height": 800 }, "device-pixel-ratio": 2, "vertical": { - "width": 1600, - "height": 2560 + "width": 800, + "height": 1280 } }, "capabilities": [
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js index 2ad4f24e..e5fcad4d 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js
@@ -22,9 +22,6 @@ this._showUserAgentTypeSetting = Common.settings.createSetting('emulation.showUserAgentType', false); this._showUserAgentTypeSetting.addChangeListener(this._updateUserAgentTypeVisibility, this); - this._showNetworkConditionsSetting = Common.settings.createSetting('emulation.showNetworkConditions', false); - this._showNetworkConditionsSetting.addChangeListener(this._updateNetworkConditionsVisibility, this); - /** @type {!Map<!Emulation.EmulatedDevice, !Emulation.EmulatedDevice.Mode>} */ this._lastMode = new Map(); @@ -169,6 +166,9 @@ this._uaItem.setGlyph(''); this._uaItem.turnIntoSelect(); toolbar.appendToolbarItem(this._uaItem); + + this._throttlingConditionsItem = MobileThrottling.throttlingManager().createMobileThrottlingButton(); + toolbar.appendToolbarItem(this._throttlingConditionsItem); } /** @@ -186,12 +186,6 @@ * @param {!UI.Toolbar} toolbar */ _fillOptionsToolbar(toolbar) { - this._networkConditionsItem = MobileThrottling.NetworkConditionsSelector.createToolbarMenuButton(); - this._networkConditionsItem.setVisible(this._showNetworkConditionsSetting.get()); - this._networkConditionsItem.setTitle(Common.UIString('Network throttling')); - this._networkConditionsItem.element.style.maxWidth = '140px'; - toolbar.appendToolbarItem(this._networkConditionsItem); - var moreOptionsButton = new UI.ToolbarMenuButton(this._appendOptionsMenuItems.bind(this)); moreOptionsButton.setTitle(Common.UIString('More options')); toolbar.appendToolbarItem(moreOptionsButton); @@ -300,9 +294,6 @@ Common.UIString('Add device pixel ratio')); appendToggleItem( this._showUserAgentTypeSetting, Common.UIString('Remove device type'), Common.UIString('Add device type')); - appendToggleItem( - this._showNetworkConditionsSetting, Common.UIString('Remove network throttling'), - Common.UIString('Add network throttling')); contextMenu.appendSeparator(); contextMenu.appendItemsAtLocation('deviceModeMenu'); contextMenu.appendSeparator(); @@ -327,7 +318,6 @@ this._showUserAgentTypeSetting.set(false); this._showMediaInspectorSetting.set(false); this._showRulersSetting.set(false); - this._showNetworkConditionsSetting.set(false); this._model.reset(); } @@ -442,10 +432,6 @@ this._uaItem.setVisible(this._showUserAgentTypeSetting.get()); } - _updateNetworkConditionsVisibility() { - this._networkConditionsItem.setVisible(this._showNetworkConditionsSetting.get()); - } - /** * @param {!Common.Event} event */
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/CPUThrottlingManager.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/CPUThrottlingManager.js deleted file mode 100644 index 412e9e9fe..0000000 --- a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/CPUThrottlingManager.js +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @implements {SDK.SDKModelObserver<!SDK.EmulationModel>} - */ -MobileThrottling.CPUThrottlingManager = class extends Common.Object { - constructor() { - super(); - this._throttlingRate = 1; // No throttling - /** @type {!Set<!UI.ToolbarComboBox>} */ - this._controls = new Set(); - this._rates = [1, 2, 5, 10, 20]; - SDK.targetManager.observeModels(SDK.EmulationModel, this); - } - - /** - * @param {number} index - */ - _setRateIndex(index) { - this._throttlingRate = this._rates[index]; - for (var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) - emulationModel.setCPUThrottlingRate(this._throttlingRate); - var icon = null; - if (this._throttlingRate !== 1) { - Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled); - icon = UI.Icon.create('smallicon-warning'); - icon.title = Common.UIString('CPU throttling is enabled'); - } - for (var control of this._controls) - control.setSelectedIndex(index); - UI.inspectorView.setPanelIcon('timeline', icon); - this.dispatchEventToListeners(MobileThrottling.CPUThrottlingManager.Events.RateChanged); - } - - /** - * @return {number} - */ - rate() { - return this._throttlingRate; - } - - /** - * @override - * @param {!SDK.EmulationModel} emulationModel - */ - modelAdded(emulationModel) { - if (this._throttlingRate !== 1) - emulationModel.setCPUThrottlingRate(this._throttlingRate); - } - - /** - * @override - * @param {!SDK.EmulationModel} emulationModel - */ - modelRemoved(emulationModel) { - } - - /** - * @return {!UI.ToolbarComboBox} - */ - createControl() { - var control = new UI.ToolbarComboBox(event => this._setRateIndex(event.target.selectedIndex)); - this._controls.add(control); - var currentRate = this._throttlingRate; - - for (var i = 0; i < this._rates.length; ++i) { - var rate = this._rates[i]; - var title = rate === 1 ? Common.UIString('No throttling') : Common.UIString('%d\xD7 slowdown', rate); - var option = control.createOption(title); - control.addOption(option); - if (currentRate === rate) - control.setSelectedIndex(i); - } - return control; - } - - /** - * @param {!UI.ToolbarComboBox} control - */ - disposeControl(control) { - this._controls.delete(control); - } -}; - -/** @enum {symbol} */ -MobileThrottling.CPUThrottlingManager.Events = { - RateChanged: Symbol('RateChanged') -};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/MobileThrottlingSelector.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/MobileThrottlingSelector.js new file mode 100644 index 0000000..f1cdc76 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/MobileThrottlingSelector.js
@@ -0,0 +1,52 @@ +// 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. + +MobileThrottling.MobileThrottlingSelector = class { + /** + * @param {function(!Array<!MobileThrottling.MobileThrottlingConditionsGroup>):!MobileThrottling.ConditionsList} populateCallback + * @param {function(number)} selectCallback + */ + constructor(populateCallback, selectCallback) { + this._populateCallback = populateCallback; + this._selectCallback = selectCallback; + MobileThrottling.throttlingManager().addEventListener( + MobileThrottling.ThrottlingManager.Events.RateChanged, this._conditionsChanged, this); + SDK.multitargetNetworkManager.addEventListener( + SDK.MultitargetNetworkManager.Events.ConditionsChanged, this._conditionsChanged, this); + /** @type {!MobileThrottling.ConditionsList} */ + this._options = this._populateOptions(); + this._conditionsChanged(); + } + + /** + * @param {!MobileThrottling.Conditions} conditions + */ + optionSelected(conditions) { + SDK.multitargetNetworkManager.setNetworkConditions(conditions.network); + MobileThrottling.throttlingManager().setCPUThrottlingRate(conditions.cpuThrottlingRate); + } + + /** + * @return {!MobileThrottling.ConditionsList} + */ + _populateOptions() { + var disabledGroup = {title: Common.UIString('Disabled'), items: [MobileThrottling.NoThrottlingConditions]}; + var presetsGroup = {title: Common.UIString('Presets'), items: MobileThrottling.mobilePresets}; + var advancedGroup = {title: Common.UIString('Advanced'), items: MobileThrottling.advancedMobilePresets}; + return this._populateCallback([disabledGroup, presetsGroup, advancedGroup]); + } + + _conditionsChanged() { + var networkConditions = SDK.multitargetNetworkManager.networkConditions(); + var cpuThrottlingRate = MobileThrottling.throttlingManager().cpuThrottlingRate(); + for (var index = 0; index < this._options.length; ++index) { + var option = this._options[index]; + if (option && option.network === networkConditions && option.cpuThrottlingRate === cpuThrottlingRate) { + this._selectCallback(index); + return; + } + } + this._selectCallback(this._options.indexOf(MobileThrottling.CustomConditions)); + } +};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSelector.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSelector.js deleted file mode 100644 index 3c25698..0000000 --- a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSelector.js +++ /dev/null
@@ -1,248 +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. -/** - * @unrestricted - */ -MobileThrottling.NetworkConditionsSelector = class { - /** - * @param {function(!Array<!MobileThrottling.NetworkConditionsGroup>):!Array<?SDK.NetworkManager.Conditions>} populateCallback - * @param {function(number)} selectCallback - */ - constructor(populateCallback, selectCallback) { - this._populateCallback = populateCallback; - this._selectCallback = selectCallback; - this._customSetting = Common.moduleSetting('customNetworkConditions'); - this._customSetting.addChangeListener(this._populateOptions, this); - this._manager = SDK.multitargetNetworkManager; - this._manager.addEventListener( - SDK.MultitargetNetworkManager.Events.ConditionsChanged, this._conditionsChanged, this); - this._populateOptions(); - } - - /** - * @param {number} throughput - * @param {boolean=} plainText - * @return {string} - */ - static throughputText(throughput, plainText) { - if (throughput < 0) - return ''; - var throughputInKbps = throughput / (1024 / 8); - var delimiter = plainText ? '' : ' '; - if (throughputInKbps < 1024) - return Common.UIString('%d%skb/s', throughputInKbps, delimiter); - if (throughputInKbps < 1024 * 10) - return Common.UIString('%.1f%sMb/s', throughputInKbps / 1024, delimiter); - return Common.UIString('%d%sMb/s', (throughputInKbps / 1024) | 0, delimiter); - } - - /** - * @param {!HTMLSelectElement} selectElement - */ - static decorateSelect(selectElement) { - var options = []; - var selector = new MobileThrottling.NetworkConditionsSelector(populate, select); - selectElement.addEventListener('change', optionSelected, false); - - /** - * @param {!Array.<!MobileThrottling.NetworkConditionsGroup>} groups - * @return {!Array<?SDK.NetworkManager.Conditions>} - */ - function populate(groups) { - selectElement.removeChildren(); - options = []; - for (var i = 0; i < groups.length; ++i) { - var group = groups[i]; - var groupElement = selectElement.createChild('optgroup'); - groupElement.label = group.title; - for (var conditions of group.items) { - var title = Common.UIString(conditions.title); - var option = new Option(title, title); - groupElement.appendChild(option); - options.push(conditions); - } - if (i === groups.length - 1) { - groupElement.appendChild(new Option(Common.UIString('Add\u2026'), Common.UIString('Add\u2026'))); - options.push(null); - } - } - return options; - } - - function optionSelected() { - if (selectElement.selectedIndex === selectElement.options.length - 1) - selector.revealAndUpdate(); - else - selector.optionSelected(options[selectElement.selectedIndex]); - } - - /** - * @param {number} index - */ - function select(index) { - if (selectElement.selectedIndex !== index) - selectElement.selectedIndex = index; - } - } - - /** - * @return {!UI.ToolbarMenuButton} - */ - static createToolbarMenuButton() { - var button = new UI.ToolbarMenuButton(appendItems); - button.setGlyph(''); - button.turnIntoSelect(); - - /** @type {!Array<?SDK.NetworkManager.Conditions>} */ - var options = []; - var selectedIndex = -1; - var selector = new MobileThrottling.NetworkConditionsSelector(populate, select); - return button; - - /** - * @param {!UI.ContextMenu} contextMenu - */ - function appendItems(contextMenu) { - for (var index = 0; index < options.length; ++index) { - var conditions = options[index]; - if (!conditions) { - contextMenu.appendSeparator(); - } else { - contextMenu.appendCheckboxItem( - Common.UIString(conditions.title), selector.optionSelected.bind(selector, conditions), - selectedIndex === index); - } - } - contextMenu.appendItem(Common.UIString('Edit\u2026'), selector.revealAndUpdate.bind(selector)); - } - - /** - * @param {!Array.<!MobileThrottling.NetworkConditionsGroup>} groups - * @return {!Array<?SDK.NetworkManager.Conditions>} - */ - function populate(groups) { - options = []; - for (var group of groups) { - for (var conditions of group.items) - options.push(conditions); - options.push(null); - } - return options; - } - - /** - * @param {number} index - */ - function select(index) { - selectedIndex = index; - button.setText(options[index].title); - } - } - - /** - * @return {!UI.ToolbarCheckbox} - */ - static createOfflineToolbarCheckbox() { - var checkbox = new UI.ToolbarCheckbox( - Common.UIString('Offline'), Common.UIString('Force disconnected from network'), forceOffline); - SDK.multitargetNetworkManager.addEventListener( - SDK.MultitargetNetworkManager.Events.ConditionsChanged, networkConditionsChanged); - checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions() === SDK.NetworkManager.OfflineConditions); - - function forceOffline() { - if (checkbox.checked()) { - MobileThrottling.NetworkConditionsSelector._lastNetworkConditions = - SDK.multitargetNetworkManager.networkConditions(); - SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); - } else { - SDK.multitargetNetworkManager.setNetworkConditions( - MobileThrottling.NetworkConditionsSelector._lastNetworkConditions); - } - } - - function networkConditionsChanged() { - var conditions = SDK.multitargetNetworkManager.networkConditions(); - checkbox.setChecked(conditions === SDK.NetworkManager.OfflineConditions); - } - return checkbox; - } - - _populateOptions() { - var customGroup = {title: Common.UIString('Custom'), items: this._customSetting.get()}; - var presetsGroup = {title: Common.UIString('Presets'), items: MobileThrottling.NetworkConditionsSelector.presets}; - var disabledGroup = {title: Common.UIString('Disabled'), items: [SDK.NetworkManager.NoThrottlingConditions]}; - this._options = this._populateCallback([disabledGroup, presetsGroup, customGroup]); - if (!this._conditionsChanged()) { - for (var i = this._options.length - 1; i >= 0; i--) { - if (this._options[i]) { - this.optionSelected(/** @type {!SDK.NetworkManager.Conditions} */ (this._options[i])); - break; - } - } - } - } - - revealAndUpdate() { - Common.Revealer.reveal(this._customSetting); - this._conditionsChanged(); - } - - /** - * @param {!SDK.NetworkManager.Conditions} conditions - */ - optionSelected(conditions) { - this._manager.setNetworkConditions(conditions); - } - - /** - * @return {boolean} - */ - _conditionsChanged() { - var value = this._manager.networkConditions(); - for (var index = 0; index < this._options.length; ++index) { - var option = this._options[index]; - if (option && option.download === value.download && option.upload === value.upload && - option.latency === value.latency && option.title === value.title) { - this._selectCallback(index); - return true; - } - } - return false; - } -}; - -/** @typedef {!{title: string, items: !Array<!SDK.NetworkManager.Conditions>}} */ -MobileThrottling.NetworkConditionsGroup; - - -/** @type {!Array.<!SDK.NetworkManager.Conditions>} */ -MobileThrottling.NetworkConditionsSelector.presets = [ - SDK.NetworkManager.OfflineConditions, - {title: 'Slow 3G', download: 500 * 1024 / 8 * .8, upload: 500 * 1024 / 8 * .8, latency: 400 * 5}, - {title: 'Fast 3G', download: 1.6 * 1024 * 1024 / 8 * .9, upload: 750 * 1024 / 8 * .9, latency: 150 * 3.75} -]; - -/** - * @implements {UI.ActionDelegate} - * @unrestricted - */ -MobileThrottling.NetworkConditionsActionDelegate = class { - /** - * @override - * @param {!UI.Context} context - * @param {string} actionId - * @return {boolean} - */ - handleAction(context, actionId) { - if (actionId === 'network-conditions.network-online') { - SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.NoThrottlingConditions); - return true; - } - if (actionId === 'network-conditions.network-offline') { - SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); - return true; - } - return false; - } -};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkThrottlingSelector.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkThrottlingSelector.js new file mode 100644 index 0000000..3539db4 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkThrottlingSelector.js
@@ -0,0 +1,65 @@ +// 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. + +MobileThrottling.NetworkThrottlingSelector = class { + /** + * @param {function(!Array<!MobileThrottling.NetworkThrottlingConditionsGroup>):!Array<?SDK.NetworkManager.Conditions>} populateCallback + * @param {function(number)} selectCallback + * @param {!Common.Setting<!Array<!SDK.NetworkManager.Conditions>>} customNetworkConditionsSetting + */ + constructor(populateCallback, selectCallback, customNetworkConditionsSetting) { + this._populateCallback = populateCallback; + this._selectCallback = selectCallback; + this._customNetworkConditionsSetting = customNetworkConditionsSetting; + this._customNetworkConditionsSetting.addChangeListener(this._populateOptions, this); + SDK.multitargetNetworkManager.addEventListener( + SDK.MultitargetNetworkManager.Events.ConditionsChanged, this._networkConditionsChanged, this); + /** @type {!Array<?SDK.NetworkManager.Conditions>} */ + this._options; + this._populateOptions(); + } + + revealAndUpdate() { + Common.Revealer.reveal(this._customNetworkConditionsSetting); + this._networkConditionsChanged(); + } + + /** + * @param {!SDK.NetworkManager.Conditions} conditions + */ + optionSelected(conditions) { + SDK.multitargetNetworkManager.setNetworkConditions(conditions); + } + + _populateOptions() { + var disabledGroup = {title: Common.UIString('Disabled'), items: [SDK.NetworkManager.NoThrottlingConditions]}; + var presetsGroup = {title: Common.UIString('Presets'), items: MobileThrottling.networkPresets}; + var customGroup = {title: Common.UIString('Custom'), items: this._customNetworkConditionsSetting.get()}; + this._options = this._populateCallback([disabledGroup, presetsGroup, customGroup]); + if (!this._networkConditionsChanged()) { + for (var i = this._options.length - 1; i >= 0; i--) { + if (this._options[i]) { + this.optionSelected(/** @type {!SDK.NetworkManager.Conditions} */ (this._options[i])); + break; + } + } + } + } + + /** + * @return {boolean} returns false if selected condition no longer exists + */ + _networkConditionsChanged() { + var value = SDK.multitargetNetworkManager.networkConditions(); + for (var index = 0; index < this._options.length; ++index) { + var option = this._options[index]; + if (option && option.download === value.download && option.upload === value.upload && + option.latency === value.latency && option.title === value.title) { + this._selectCallback(index); + return true; + } + } + return false; + } +};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingManager.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingManager.js new file mode 100644 index 0000000..5381321 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingManager.js
@@ -0,0 +1,268 @@ +// 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. + +/** + * @implements {SDK.SDKModelObserver<!SDK.EmulationModel>} + */ +MobileThrottling.ThrottlingManager = class extends Common.Object { + constructor() { + super(); + /** @type {!MobileThrottling.CPUThrottlingRates} */ + this._cpuThrottlingRate = MobileThrottling.CPUThrottlingRates.NoThrottling; + /** @type {!Set<!UI.ToolbarComboBox>} */ + this._cpuThrottlingControls = new Set(); + this._cpuThrottlingRates = MobileThrottling.cpuThrottlingPresets; + /** @type {!Common.Setting<!Array<!SDK.NetworkManager.Conditions>>} */ + this._customNetworkConditionsSetting = Common.moduleSetting('customNetworkConditions'); + /** @type {!SDK.NetworkManager.Conditions} */ + this._currentNetworkThrottlingConditions = SDK.NetworkManager.NoThrottlingConditions; + /** @type {!SDK.NetworkManager.Conditions} */ + this._lastNetworkThrottlingConditions; + + SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged, () => { + this._lastNetworkThrottlingConditions = this._currentNetworkThrottlingConditions; + this._currentNetworkThrottlingConditions = SDK.multitargetNetworkManager.networkConditions(); + }); + + SDK.targetManager.observeModels(SDK.EmulationModel, this); + } + + + /** + * @param {!HTMLSelectElement} selectElement + * @return {!MobileThrottling.NetworkThrottlingSelector} + */ + decorateSelectWithNetworkThrottling(selectElement) { + var options = []; + var selector = + new MobileThrottling.NetworkThrottlingSelector(populate, select, this._customNetworkConditionsSetting); + selectElement.addEventListener('change', optionSelected, false); + return selector; + + /** + * @param {!Array.<!MobileThrottling.NetworkThrottlingConditionsGroup>} groups + * @return {!Array<?SDK.NetworkManager.Conditions>} + */ + function populate(groups) { + selectElement.removeChildren(); + options = []; + for (var i = 0; i < groups.length; ++i) { + var group = groups[i]; + var groupElement = selectElement.createChild('optgroup'); + groupElement.label = group.title; + for (var conditions of group.items) { + var title = conditions.title; + var option = new Option(title, title); + groupElement.appendChild(option); + options.push(conditions); + } + if (i === groups.length - 1) { + groupElement.appendChild(new Option(Common.UIString('Add\u2026'), Common.UIString('Add\u2026'))); + options.push(null); + } + } + return options; + } + + function optionSelected() { + if (selectElement.selectedIndex === selectElement.options.length - 1) + selector.revealAndUpdate(); + else + selector.optionSelected(options[selectElement.selectedIndex]); + } + + /** + * @param {number} index + */ + function select(index) { + if (selectElement.selectedIndex !== index) + selectElement.selectedIndex = index; + } + } + + /** + * @return {!UI.ToolbarCheckbox} + */ + createOfflineToolbarCheckbox() { + var checkbox = new UI.ToolbarCheckbox( + Common.UIString('Offline'), Common.UIString('Force disconnected from network'), forceOffline.bind(this)); + SDK.multitargetNetworkManager.addEventListener( + SDK.MultitargetNetworkManager.Events.ConditionsChanged, networkConditionsChanged); + checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions() === SDK.NetworkManager.OfflineConditions); + + /** + * @this {!MobileThrottling.ThrottlingManager} + */ + function forceOffline() { + if (checkbox.checked()) + SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); + else + SDK.multitargetNetworkManager.setNetworkConditions(this._lastNetworkThrottlingConditions); + } + + function networkConditionsChanged() { + checkbox.setChecked(SDK.multitargetNetworkManager.networkConditions() === SDK.NetworkManager.OfflineConditions); + } + + return checkbox; + } + + + /** + * @return {!UI.ToolbarMenuButton} + */ + createMobileThrottlingButton() { + var button = new UI.ToolbarMenuButton(appendItems); + button.setTitle(Common.UIString('Throttling')); + button.setGlyph(''); + button.turnIntoSelect(); + + /** @type {!MobileThrottling.ConditionsList} */ + var options = []; + var selectedIndex = -1; + var selector = new MobileThrottling.MobileThrottlingSelector(populate, select); + return button; + + /** + * @param {!UI.ContextMenu} contextMenu + */ + function appendItems(contextMenu) { + for (var index = 0; index < options.length; ++index) { + var conditions = options[index]; + if (!conditions) { + contextMenu.appendSeparator(); + continue; + } + if (conditions.title === MobileThrottling.CustomConditions.title && + conditions.description === MobileThrottling.CustomConditions.description) + continue; + contextMenu.appendCheckboxItem( + Common.UIString(conditions.title), + selector.optionSelected.bind(selector, /** @type {!MobileThrottling.Conditions} */ (conditions)), + selectedIndex === index); + } + } + + /** + * @param {!Array.<!MobileThrottling.MobileThrottlingConditionsGroup>} groups + * @return {!MobileThrottling.ConditionsList} + */ + function populate(groups) { + options = []; + for (var group of groups) { + for (var conditions of group.items) + options.push(conditions); + options.push(null); + } + return options; + } + + /** + * @param {number} index + */ + function select(index) { + selectedIndex = index; + button.setText(options[index].title); + button.setTitle(options[index].description); + } + } + + /** + * @return {number} + */ + cpuThrottlingRate() { + return this._cpuThrottlingRate; + } + + /** + * @param {!MobileThrottling.CPUThrottlingRates} rate + */ + setCPUThrottlingRate(rate) { + this._cpuThrottlingRate = rate; + for (var emulationModel of SDK.targetManager.models(SDK.EmulationModel)) + emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate); + var icon = null; + if (this._cpuThrottlingRate !== MobileThrottling.CPUThrottlingRates.NoThrottling) { + Host.userMetrics.actionTaken(Host.UserMetrics.Action.CpuThrottlingEnabled); + icon = UI.Icon.create('smallicon-warning'); + icon.title = Common.UIString('CPU throttling is enabled'); + } + var index = this._cpuThrottlingRates.indexOf(this._cpuThrottlingRate); + for (var control of this._cpuThrottlingControls) + control.setSelectedIndex(index); + UI.inspectorView.setPanelIcon('timeline', icon); + this.dispatchEventToListeners(MobileThrottling.ThrottlingManager.Events.RateChanged, this._cpuThrottlingRate); + } + + /** + * @override + * @param {!SDK.EmulationModel} emulationModel + */ + modelAdded(emulationModel) { + if (this._cpuThrottlingRate !== MobileThrottling.CPUThrottlingRates.NoThrottling) + emulationModel.setCPUThrottlingRate(this._cpuThrottlingRate); + } + + /** + * @override + * @param {!SDK.EmulationModel} emulationModel + */ + modelRemoved(emulationModel) { + } + + /** + * @return {!UI.ToolbarComboBox} + */ + createCPUThrottlingSelector() { + var control = new UI.ToolbarComboBox( + event => this.setCPUThrottlingRate(this._cpuThrottlingRates[event.target.selectedIndex])); + this._cpuThrottlingControls.add(control); + var currentRate = this._cpuThrottlingRate; + + for (var i = 0; i < this._cpuThrottlingRates.length; ++i) { + var rate = this._cpuThrottlingRates[i]; + var title = rate === 1 ? Common.UIString('No throttling') : Common.UIString('%d\xD7 slowdown', rate); + var option = control.createOption(title); + control.addOption(option); + if (currentRate === rate) + control.setSelectedIndex(i); + } + return control; + } +}; + +/** @enum {symbol} */ +MobileThrottling.ThrottlingManager.Events = { + RateChanged: Symbol('RateChanged') +}; + +/** + * @implements {UI.ActionDelegate} + */ +MobileThrottling.ThrottlingManager.ActionDelegate = class { + /** + * @override + * @param {!UI.Context} context + * @param {string} actionId + * @return {boolean} + */ + handleAction(context, actionId) { + if (actionId === 'network-conditions.network-online') { + SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.NoThrottlingConditions); + return true; + } + if (actionId === 'network-conditions.network-offline') { + SDK.multitargetNetworkManager.setNetworkConditions(SDK.NetworkManager.OfflineConditions); + return true; + } + return false; + } +}; + +/** + * @return {!MobileThrottling.ThrottlingManager} + */ +MobileThrottling.throttlingManager = function() { + return self.singleton(MobileThrottling.ThrottlingManager); +};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingPresets.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingPresets.js new file mode 100644 index 0000000..463ddb08 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingPresets.js
@@ -0,0 +1,99 @@ +// 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. + +/** @enum {number} */ +MobileThrottling.CPUThrottlingRates = { + NoThrottling: 1, + MidTierMobile: 4, + LowEndMobile: 6, +}; + +/** + * @typedef {{ + * title: string, + * description: string, + * network: !SDK.NetworkManager.Conditions, + * cpuThrottlingRate: !MobileThrottling.CPUThrottlingRates + * }} + **/ +MobileThrottling.Conditions; + +/** @type {!MobileThrottling.Conditions} */ +MobileThrottling.NoThrottlingConditions = { + title: SDK.NetworkManager.NoThrottlingConditions.title, + description: Common.UIString('No throttling'), + network: SDK.NetworkManager.NoThrottlingConditions, + cpuThrottlingRate: MobileThrottling.CPUThrottlingRates.NoThrottling, +}; + +/** @type {!MobileThrottling.Conditions} */ +MobileThrottling.OfflineConditions = { + title: SDK.NetworkManager.OfflineConditions.title, + description: Common.UIString('No internet connectivity'), + network: SDK.NetworkManager.OfflineConditions, + cpuThrottlingRate: MobileThrottling.CPUThrottlingRates.NoThrottling, +}; + +/** @type {!MobileThrottling.Conditions} */ +MobileThrottling.LowEndMobileConditions = { + title: Common.UIString('Low-end mobile'), + description: Common.UIString('Slow 3G & 6x CPU slowdown'), + network: SDK.NetworkManager.Slow3GConditions, + cpuThrottlingRate: MobileThrottling.CPUThrottlingRates.LowEndMobile, +}; + +/** @type {!MobileThrottling.Conditions} */ +MobileThrottling.MidTierMobileConditions = { + title: Common.UIString('Mid-tier mobile'), + description: Common.UIString('Fast 3G & 4x CPU slowdown'), + network: SDK.NetworkManager.Fast3GConditions, + cpuThrottlingRate: MobileThrottling.CPUThrottlingRates.MidTierMobile, +}; + +/** + * @typedef {{ + * title: string, + * description: string + * }} + **/ +MobileThrottling.PlaceholderConditions; + +/** @type {!MobileThrottling.PlaceholderConditions} */ +MobileThrottling.CustomConditions = { + title: Common.UIString('Custom'), + description: Common.UIString('Check Network and Performance panels'), +}; + +/** @typedef {!{title: string, items: !Array<!SDK.NetworkManager.Conditions>}} */ +MobileThrottling.NetworkThrottlingConditionsGroup; + +/** @typedef {!{title: string, items: !Array<!MobileThrottling.Conditions|!MobileThrottling.PlaceholderConditions>}} */ +MobileThrottling.MobileThrottlingConditionsGroup; + +/** @typedef {!Array<?MobileThrottling.Conditions|!MobileThrottling.PlaceholderConditions>} */ +MobileThrottling.ConditionsList; + +/** @type {!Array.<!MobileThrottling.Conditions>} */ +MobileThrottling.mobilePresets = [ + MobileThrottling.MidTierMobileConditions, MobileThrottling.LowEndMobileConditions, MobileThrottling.CustomConditions +]; + +/** @type {!Array.<!MobileThrottling.Conditions>} */ +MobileThrottling.advancedMobilePresets = [ + MobileThrottling.OfflineConditions, +]; + +/** @type {!Array<!SDK.NetworkManager.Conditions>} */ +MobileThrottling.networkPresets = [ + SDK.NetworkManager.Fast3GConditions, + SDK.NetworkManager.Slow3GConditions, + SDK.NetworkManager.OfflineConditions, +]; + +/** @type {!Array<!MobileThrottling.CPUThrottlingRates>} */ +MobileThrottling.cpuThrottlingPresets = [ + MobileThrottling.CPUThrottlingRates.NoThrottling, + MobileThrottling.CPUThrottlingRates.MidTierMobile, + MobileThrottling.CPUThrottlingRates.LowEndMobile, +];
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSettingsTab.js b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js similarity index 88% rename from third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSettingsTab.js rename to third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js index a8a86fc1..4c31ac20 100644 --- a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/NetworkConditionsSettingsTab.js +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/ThrottlingSettingsTab.js
@@ -6,10 +6,10 @@ * @implements {UI.ListWidget.Delegate} * @unrestricted */ -MobileThrottling.NetworkConditionsSettingsTab = class extends UI.VBox { +MobileThrottling.ThrottlingSettingsTab = class extends UI.VBox { constructor() { super(true); - this.registerRequiredCSS('mobile_throttling/networkConditionsSettingsTab.css'); + this.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css'); this.contentElement.createChild('div', 'header').textContent = Common.UIString('Network Throttling Profiles'); @@ -19,7 +19,7 @@ this._list = new UI.ListWidget(this); this._list.element.classList.add('conditions-list'); - this._list.registerRequiredCSS('mobile_throttling/networkConditionsSettingsTab.css'); + this._list.registerRequiredCSS('mobile_throttling/throttlingSettingsTab.css'); this._list.show(this.contentElement); this._customSetting = Common.moduleSetting('customNetworkConditions'); @@ -66,10 +66,9 @@ titleText.title = conditions.title; element.createChild('div', 'conditions-list-separator'); element.createChild('div', 'conditions-list-text').textContent = - MobileThrottling.NetworkConditionsSelector.throughputText(conditions.download); + MobileThrottling.throughputText(conditions.download); element.createChild('div', 'conditions-list-separator'); - element.createChild('div', 'conditions-list-text').textContent = - MobileThrottling.NetworkConditionsSelector.throughputText(conditions.upload); + element.createChild('div', 'conditions-list-text').textContent = MobileThrottling.throughputText(conditions.upload); element.createChild('div', 'conditions-list-separator'); element.createChild('div', 'conditions-list-text').textContent = Common.UIString('%dms', conditions.latency); return element; @@ -199,3 +198,20 @@ } } }; + +/** + * @param {number} throughput + * @param {boolean=} plainText + * @return {string} + */ +MobileThrottling.throughputText = function(throughput, plainText) { + if (throughput < 0) + return ''; + var throughputInKbps = throughput / (1024 / 8); + var delimiter = plainText ? '' : ' '; + if (throughputInKbps < 1024) + return Common.UIString('%d%skb/s', throughputInKbps, delimiter); + if (throughputInKbps < 1024 * 10) + return Common.UIString('%.1f%sMb/s', throughputInKbps / 1024, delimiter); + return Common.UIString('%d%sMb/s', (throughputInKbps / 1024) | 0, delimiter); +};
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/module.json b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/module.json index f9741fd3..b367751d7 100644 --- a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/module.json +++ b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/module.json
@@ -11,7 +11,7 @@ "actionId": "network-conditions.network-offline", "category": "Network", "title": "Go offline", - "className": "MobileThrottling.NetworkConditionsActionDelegate", + "className": "MobileThrottling.ThrottlingManager.ActionDelegate", "tags": "device" }, { @@ -19,16 +19,16 @@ "actionId": "network-conditions.network-online", "category": "Network", "title": "Go online", - "className": "MobileThrottling.NetworkConditionsActionDelegate", + "className": "MobileThrottling.ThrottlingManager.ActionDelegate", "tags": "device" }, { "type": "view", "location": "settings-view", - "id": "network-conditions", + "id": "throttling-conditions", "title": "Throttling", "order": 35, - "className": "MobileThrottling.NetworkConditionsSettingsTab", + "className": "MobileThrottling.ThrottlingSettingsTab", "settings": [ "customNetworkConditions" ] @@ -41,11 +41,13 @@ "protocol" ], "scripts": [ - "NetworkConditionsSelector.js", - "NetworkConditionsSettingsTab.js", - "CPUThrottlingManager.js" + "ThrottlingPresets.js", + "MobileThrottlingSelector.js", + "NetworkThrottlingSelector.js", + "ThrottlingSettingsTab.js", + "ThrottlingManager.js" ], "resources": [ - "networkConditionsSettingsTab.css" + "throttlingSettingsTab.css" ] }
diff --git a/third_party/WebKit/Source/devtools/front_end/mobile_throttling/networkConditionsSettingsTab.css b/third_party/WebKit/Source/devtools/front_end/mobile_throttling/throttlingSettingsTab.css similarity index 100% rename from third_party/WebKit/Source/devtools/front_end/mobile_throttling/networkConditionsSettingsTab.css rename to third_party/WebKit/Source/devtools/front_end/mobile_throttling/throttlingSettingsTab.css
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js index 3b31721..bf6585a 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkConfigView.js
@@ -112,8 +112,9 @@ _createNetworkThrottlingSection() { var section = this._createSection(Common.UIString('Network throttling'), 'network-config-throttling'); - MobileThrottling.NetworkConditionsSelector.decorateSelect( - /** @type {!HTMLSelectElement} */ (section.createChild('select', 'chrome-select'))); + this._networkThrottlingSelect = + /** @type {!HTMLSelectElement} */ (section.createChild('select', 'chrome-select')); + MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(this._networkThrottlingSelect); } _createUserAgentSection() {
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js index f6b59ee..5764ffc0 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkLogView.js
@@ -244,13 +244,13 @@ */ static _requestMixedContentFilter(value, request) { if (value === Network.NetworkLogView.MixedContentFilterValues.Displayed) - return request.mixedContentType === 'optionally-blockable'; + return request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable; else if (value === Network.NetworkLogView.MixedContentFilterValues.Blocked) - return request.mixedContentType === 'blockable' && request.wasBlocked(); + return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && request.wasBlocked(); else if (value === Network.NetworkLogView.MixedContentFilterValues.BlockOverridden) - return request.mixedContentType === 'blockable' && !request.wasBlocked(); + return request.mixedContentType === Protocol.Security.MixedContentType.Blockable && !request.wasBlocked(); else if (value === Network.NetworkLogView.MixedContentFilterValues.All) - return request.mixedContentType !== 'none'; + return request.mixedContentType !== Protocol.Security.MixedContentType.None; return false; } @@ -1024,17 +1024,17 @@ Network.NetworkLogView.FilterType.Priority, NetworkPriorities.uiLabelForPriority(priority)); } - if (request.mixedContentType !== 'none') { + if (request.mixedContentType !== Protocol.Security.MixedContentType.None) { this._suggestionBuilder.addItem( Network.NetworkLogView.FilterType.MixedContent, Network.NetworkLogView.MixedContentFilterValues.All); } - if (request.mixedContentType === 'optionally-blockable') { + if (request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) { this._suggestionBuilder.addItem( Network.NetworkLogView.FilterType.MixedContent, Network.NetworkLogView.MixedContentFilterValues.Displayed); } - if (request.mixedContentType === 'blockable') { + if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable) { var suggestion = request.wasBlocked() ? Network.NetworkLogView.MixedContentFilterValues.Blocked : Network.NetworkLogView.MixedContentFilterValues.BlockOverridden; this._suggestionBuilder.addItem(Network.NetworkLogView.FilterType.MixedContent, suggestion);
diff --git a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js index f53b6b26..423f4c97 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/network/NetworkPanel.js
@@ -187,8 +187,10 @@ this._panelToolbar.appendToolbarItem(this._disableCacheCheckbox); this._panelToolbar.appendSeparator(); - this._panelToolbar.appendToolbarItem(MobileThrottling.NetworkConditionsSelector.createOfflineToolbarCheckbox()); - this._panelToolbar.appendToolbarItem(this._createNetworkConditionsSelect()); + this._offlineCheckbox = MobileThrottling.throttlingManager().createOfflineToolbarCheckbox(); + this._panelToolbar.appendToolbarItem(this._offlineCheckbox); + this._throttlingSelect = this._createThrottlingConditionsSelect(); + this._panelToolbar.appendToolbarItem(this._throttlingSelect); this._panelToolbar.appendToolbarItem(new UI.ToolbarItem(this._progressBarContainer)); } @@ -196,10 +198,10 @@ /** * @return {!UI.ToolbarComboBox} */ - _createNetworkConditionsSelect() { + _createThrottlingConditionsSelect() { var toolbarItem = new UI.ToolbarComboBox(null); - toolbarItem.setMaxWidth(140); - MobileThrottling.NetworkConditionsSelector.decorateSelect(toolbarItem.selectElement()); + toolbarItem.setMaxWidth(160); + MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement()); return toolbarItem; }
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js index d65ba03..fd8dead7 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ServiceWorkersView.js
@@ -18,7 +18,7 @@ /** @type {!Map<!SDK.ServiceWorkerRegistration, !Resources.ServiceWorkersView.Section>} */ this._sections = new Map(); - this._toolbar.appendToolbarItem(MobileThrottling.NetworkConditionsSelector.createOfflineToolbarCheckbox()); + this._toolbar.appendToolbarItem(MobileThrottling.throttlingManager().createOfflineToolbarCheckbox()); var updateOnReloadSetting = Common.settings.createSetting('serviceWorkerUpdateOnReload', false); updateOnReloadSetting.setTitle(Common.UIString('Update on reload')); var forceUpdate = new UI.ToolbarSettingCheckbox(
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js index 96d50d9..25792cd5 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkManager.js
@@ -182,23 +182,48 @@ 'text/vtt': {'texttrack': true}, }; - -/** @typedef {{download: number, upload: number, latency: number, title: string}} */ +/** + * @typedef {{ + * download: number, + * upload: number, + * latency: number, + * title: string, + * }} + **/ SDK.NetworkManager.Conditions; + /** @type {!SDK.NetworkManager.Conditions} */ SDK.NetworkManager.NoThrottlingConditions = { - title: Common.UIString('No throttling'), + title: Common.UIString('Online'), download: -1, upload: -1, latency: 0 }; + /** @type {!SDK.NetworkManager.Conditions} */ SDK.NetworkManager.OfflineConditions = { title: Common.UIString('Offline'), download: 0, upload: 0, - latency: 0 + latency: 0, }; + +/** @type {!SDK.NetworkManager.Conditions} */ +SDK.NetworkManager.Slow3GConditions = { + title: Common.UIString('Slow 3G'), + download: 500 * 1024 / 8 * .8, + upload: 500 * 1024 / 8 * .8, + latency: 400 * 5, +}; + +/** @type {!SDK.NetworkManager.Conditions} */ +SDK.NetworkManager.Fast3GConditions = { + title: Common.UIString('Fast 3G'), + download: 1.6 * 1024 * 1024 / 8 * .9, + upload: 750 * 1024 / 8 * .9, + latency: 150 * 3.75, +}; + /** @typedef {{url: string, enabled: boolean}} */ SDK.NetworkManager.BlockedPattern; @@ -243,7 +268,7 @@ networkRequest.setRequestHeaders(this._headersMapToHeadersArray(request.headers)); networkRequest.requestFormData = request.postData; networkRequest.setInitialPriority(request.initialPriority); - networkRequest.mixedContentType = request.mixedContentType || Protocol.Network.RequestMixedContentType.None; + networkRequest.mixedContentType = request.mixedContentType || Protocol.Security.MixedContentType.None; networkRequest.setReferrerPolicy(request.referrerPolicy); } @@ -329,7 +354,7 @@ * @override * @param {!Protocol.Network.RequestId} requestId * @param {!Protocol.Network.ResourcePriority} newPriority - * @param {!Protocol.Network.Timestamp} timestamp + * @param {!Protocol.Network.MonotonicTime} timestamp */ resourceChangedPriority(requestId, newPriority, timestamp) { var networkRequest = this._inflightRequestsById[requestId]; @@ -343,8 +368,8 @@ * @param {!Protocol.Network.LoaderId} loaderId * @param {string} documentURL * @param {!Protocol.Network.Request} request - * @param {!Protocol.Network.Timestamp} time - * @param {!Protocol.Network.Timestamp} wallTime + * @param {!Protocol.Network.MonotonicTime} time + * @param {!Protocol.Network.TimeSinceEpoch} wallTime * @param {!Protocol.Network.Initiator} initiator * @param {!Protocol.Network.Response=} redirectResponse * @param {!Protocol.Page.ResourceType=} resourceType @@ -389,7 +414,7 @@ * @override * @param {!Protocol.Network.RequestId} requestId * @param {!Protocol.Network.LoaderId} loaderId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {!Protocol.Page.ResourceType} resourceType * @param {!Protocol.Network.Response} response * @param {!Protocol.Page.FrameId=} frameId @@ -431,7 +456,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {number} dataLength * @param {number} encodedDataLength */ @@ -451,7 +476,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} finishTime + * @param {!Protocol.Network.MonotonicTime} finishTime * @param {number} encodedDataLength */ loadingFinished(requestId, finishTime, encodedDataLength) { @@ -464,7 +489,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {!Protocol.Page.ResourceType} resourceType * @param {string} localizedDescription * @param {boolean=} canceled @@ -506,8 +531,8 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time - * @param {!Protocol.Network.Timestamp} wallTime + * @param {!Protocol.Network.MonotonicTime} time + * @param {!Protocol.Network.TimeSinceEpoch} wallTime * @param {!Protocol.Network.WebSocketRequest} request */ webSocketWillSendHandshakeRequest(requestId, time, wallTime, request) { @@ -525,7 +550,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {!Protocol.Network.WebSocketResponse} response */ webSocketHandshakeResponseReceived(requestId, time, response) { @@ -550,7 +575,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {!Protocol.Network.WebSocketFrame} response */ webSocketFrameReceived(requestId, time, response) { @@ -567,7 +592,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {!Protocol.Network.WebSocketFrame} response */ webSocketFrameSent(requestId, time, response) { @@ -584,7 +609,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {string} errorMessage */ webSocketFrameError(requestId, time, errorMessage) { @@ -601,7 +626,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time */ webSocketClosed(requestId, time) { var networkRequest = this._inflightRequestsById[requestId]; @@ -613,7 +638,7 @@ /** * @override * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {string} eventName * @param {string} eventId * @param {string} data @@ -640,7 +665,7 @@ /** * @param {!Protocol.Network.RequestId} requestId - * @param {!Protocol.Network.Timestamp} time + * @param {!Protocol.Network.MonotonicTime} time * @param {string} redirectURL * @return {!SDK.NetworkRequest} */ @@ -677,7 +702,7 @@ /** * @param {!SDK.NetworkRequest} networkRequest - * @param {!Protocol.Network.Timestamp} finishTime + * @param {!Protocol.Network.MonotonicTime} finishTime * @param {number} encodedDataLength */ _finishNetworkRequest(networkRequest, finishTime, encodedDataLength) {
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js index 42768af..771f0819 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/NetworkRequest.js
@@ -63,8 +63,8 @@ this.requestMethod = ''; this.requestTime = 0; this.protocol = ''; - /** @type {!Protocol.Network.RequestMixedContentType} */ - this.mixedContentType = Protocol.Network.RequestMixedContentType.None; + /** @type {!Protocol.Security.MixedContentType} */ + this.mixedContentType = Protocol.Security.MixedContentType.None; /** @type {?Protocol.Network.ResourcePriority} */ this._initialPriority = null;
diff --git a/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js b/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js index 1025b2a..d7f3bd7 100644 --- a/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/security/SecurityPanel.js
@@ -180,11 +180,10 @@ var securityState = /** @type {!Protocol.Security.SecurityState} */ (request.securityState()); - if (request.mixedContentType === Protocol.Network.RequestMixedContentType.Blockable && - this._ranInsecureContentStyle) + if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable && this._ranInsecureContentStyle) securityState = this._ranInsecureContentStyle; else if ( - request.mixedContentType === Protocol.Network.RequestMixedContentType.OptionallyBlockable && + request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable && this._displayedInsecureContentStyle) securityState = this._displayedInsecureContentStyle; @@ -231,16 +230,16 @@ * @param {!SDK.NetworkRequest} request */ _updateFilterRequestCounts(request) { - if (request.mixedContentType === Protocol.Network.RequestMixedContentType.None) + if (request.mixedContentType === Protocol.Security.MixedContentType.None) return; /** @type {!Network.NetworkLogView.MixedContentFilterValues} */ var filterKey = Network.NetworkLogView.MixedContentFilterValues.All; if (request.wasBlocked()) filterKey = Network.NetworkLogView.MixedContentFilterValues.Blocked; - else if (request.mixedContentType === Protocol.Network.RequestMixedContentType.Blockable) + else if (request.mixedContentType === Protocol.Security.MixedContentType.Blockable) filterKey = Network.NetworkLogView.MixedContentFilterValues.BlockOverridden; - else if (request.mixedContentType === Protocol.Network.RequestMixedContentType.OptionallyBlockable) + else if (request.mixedContentType === Protocol.Security.MixedContentType.OptionallyBlockable) filterKey = Network.NetworkLogView.MixedContentFilterValues.Displayed; if (!this._filterRequestCounts.has(filterKey))
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js index ab052ef..efd952c7 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js
@@ -77,8 +77,6 @@ /** @type {?Timeline.PerformanceModel} */ this._pendingPerformanceModel = null; - this._cpuThrottlingManager = new MobileThrottling.CPUThrottlingManager(); - this._viewModeSetting = Common.settings.createSetting('timelineViewMode', Timeline.TimelinePanel.ViewMode.FlameChart); @@ -258,8 +256,8 @@ this._showSettingsPaneSetting, 'largeicon-settings-gear', Common.UIString('Capture settings')); SDK.multitargetNetworkManager.addEventListener( SDK.MultitargetNetworkManager.Events.ConditionsChanged, this._updateShowSettingsToolbarButton, this); - this._cpuThrottlingManager.addEventListener( - MobileThrottling.CPUThrottlingManager.Events.RateChanged, this._updateShowSettingsToolbarButton, this); + MobileThrottling.throttlingManager().addEventListener( + MobileThrottling.ThrottlingManager.Events.RateChanged, this._updateShowSettingsToolbarButton, this); this._disableCaptureJSProfileSetting.addChangeListener(this._updateShowSettingsToolbarButton, this); this._captureLayersAndPicturesSetting.addChangeListener(this._updateShowSettingsToolbarButton, this); @@ -281,12 +279,15 @@ throttlingPane.element.classList.add('flex-auto'); throttlingPane.show(this._settingsPane.element); - var throttlingToolbar1 = new UI.Toolbar('', throttlingPane.element); - throttlingToolbar1.appendText(Common.UIString('Network:')); - throttlingToolbar1.appendToolbarItem(this._createNetworkConditionsSelect()); - var throttlingToolbar2 = new UI.Toolbar('', throttlingPane.element); - throttlingToolbar2.appendText(Common.UIString('CPU:')); - throttlingToolbar2.appendToolbarItem(this._cpuThrottlingManager.createControl()); + var networkThrottlingToolbar = new UI.Toolbar('', throttlingPane.element); + networkThrottlingToolbar.appendText(Common.UIString('Network:')); + this._networkThrottlingSelect = this._createNetworkConditionsSelect(); + networkThrottlingToolbar.appendToolbarItem(this._networkThrottlingSelect); + + var cpuThrottlingToolbar = new UI.Toolbar('', throttlingPane.element); + cpuThrottlingToolbar.appendText(Common.UIString('CPU:')); + this._cpuThrottlingSelect = MobileThrottling.throttlingManager().createCPUThrottlingSelector(); + cpuThrottlingToolbar.appendToolbarItem(this._cpuThrottlingSelect); this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this)); this._updateSettingsPaneVisibility(); @@ -323,7 +324,7 @@ _createNetworkConditionsSelect() { var toolbarItem = new UI.ToolbarComboBox(null); toolbarItem.setMaxWidth(140); - MobileThrottling.NetworkConditionsSelector.decorateSelect(toolbarItem.selectElement()); + MobileThrottling.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement()); return toolbarItem; } @@ -498,7 +499,7 @@ _updateShowSettingsToolbarButton() { var messages = []; - if (this._cpuThrottlingManager.rate() !== 1) + if (MobileThrottling.throttlingManager().cpuThrottlingRate() !== 1) messages.push(Common.UIString('- CPU throttling is enabled')); if (SDK.multitargetNetworkManager.isThrottling()) messages.push(Common.UIString('- Network throttling is enabled'));
diff --git a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp index d00ae6c..4446167 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXMediaControls.cpp
@@ -30,6 +30,7 @@ #include "core/layout/LayoutObject.h" #include "modules/accessibility/AXObjectCacheImpl.h" +#include "modules/media_controls/elements/MediaControlTimeDisplayElement.h" #include "platform/text/PlatformLocale.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/accessibility/DEPS b/third_party/WebKit/Source/modules/accessibility/DEPS index 6526f09e..f0b9b68 100644 --- a/third_party/WebKit/Source/modules/accessibility/DEPS +++ b/third_party/WebKit/Source/modules/accessibility/DEPS
@@ -2,4 +2,5 @@ "-modules", "+modules/ModulesExport.h", "+modules/accessibility", + "+modules/media_controls", ]
diff --git a/third_party/WebKit/Source/modules/compositorworker/AnimationWorklet.cpp b/third_party/WebKit/Source/modules/compositorworker/AnimationWorklet.cpp index b097ac82b..a9c6483 100644 --- a/third_party/WebKit/Source/modules/compositorworker/AnimationWorklet.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/AnimationWorklet.cpp
@@ -8,9 +8,11 @@ #include "core/dom/AnimationWorkletProxyClient.h" #include "core/dom/Document.h" #include "core/frame/LocalFrame.h" +#include "core/frame/WebLocalFrameBase.h" #include "core/page/ChromeClient.h" #include "core/workers/WorkerClients.h" #include "modules/compositorworker/AnimationWorkletMessagingProxy.h" +#include "modules/compositorworker/AnimationWorkletProxyClientImpl.h" #include "modules/compositorworker/AnimationWorkletThread.h" namespace blink { @@ -36,8 +38,7 @@ Document* document = ToDocument(GetExecutionContext()); AnimationWorkletProxyClient* proxy_client = - document->GetFrame()->GetChromeClient().CreateAnimationWorkletProxyClient( - document->GetFrame()); + AnimationWorkletProxyClientImpl::FromDocument(document); WorkerClients* worker_clients = WorkerClients::Create(); ProvideAnimationWorkletProxyClientTo(worker_clients, proxy_client);
diff --git a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.cpp b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.cpp index 694f60b..572eed7 100644 --- a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.cpp
@@ -5,6 +5,9 @@ #include "modules/compositorworker/AnimationWorkletProxyClientImpl.h" #include "core/animation/CompositorMutatorImpl.h" +#include "core/dom/Document.h" +#include "core/frame/LocalFrame.h" +#include "core/frame/WebLocalFrameBase.h" namespace blink { @@ -46,4 +49,13 @@ return true; } +// static +AnimationWorkletProxyClientImpl* AnimationWorkletProxyClientImpl::FromDocument( + Document* document) { + WebLocalFrameBase* local_frame_base = + WebLocalFrameBase::FromFrame(document->GetFrame()); + return new AnimationWorkletProxyClientImpl( + local_frame_base->LocalRootFrameWidget()->CompositorMutator()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.h b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.h index a7e74105..6aa4d41 100644 --- a/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.h +++ b/third_party/WebKit/Source/modules/compositorworker/AnimationWorkletProxyClientImpl.h
@@ -15,6 +15,7 @@ namespace blink { class CompositorMutatorImpl; +class Document; class WorkletGlobalScope; // Mediates between one Animator and the associated CompositorMutatorImpl. There @@ -42,6 +43,8 @@ // This method is invoked in compositor thread bool Mutate(double monotonic_time_now) override; + static AnimationWorkletProxyClientImpl* FromDocument(Document*); + private: CrossThreadPersistent<CompositorMutatorImpl> mutator_;
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp index 656c7d6..0a7595a 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorker.cpp
@@ -13,6 +13,7 @@ #include "core/workers/WorkerClients.h" #include "modules/EventTargetModules.h" #include "modules/compositorworker/CompositorWorkerMessagingProxy.h" +#include "modules/compositorworker/CompositorWorkerProxyClientImpl.h" #include "modules/compositorworker/CompositorWorkerThread.h" namespace blink { @@ -56,8 +57,7 @@ Document* document = ToDocument(context); WorkerClients* worker_clients = WorkerClients::Create(); CompositorWorkerProxyClient* client = - document->GetFrame()->GetChromeClient().CreateCompositorWorkerProxyClient( - document->GetFrame()); + CompositorWorkerProxyClientImpl::FromDocument(document); ProvideCompositorWorkerProxyClientTo(worker_clients, client); return new CompositorWorkerMessagingProxy(this, worker_clients); }
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.cpp index 4cdde4e..59abb42 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.cpp
@@ -5,6 +5,9 @@ #include "modules/compositorworker/CompositorWorkerProxyClientImpl.h" #include "core/animation/CompositorMutatorImpl.h" +#include "core/dom/Document.h" +#include "core/frame/LocalFrame.h" +#include "core/frame/WebLocalFrameBase.h" #include "modules/compositorworker/CompositorWorkerGlobalScope.h" #include "platform/instrumentation/tracing/TraceEvent.h" #include "platform/wtf/CurrentTime.h" @@ -81,4 +84,13 @@ return global_scope_->ExecuteAnimationFrameCallbacks(high_res_time_ms); } +// static +CompositorWorkerProxyClientImpl* CompositorWorkerProxyClientImpl::FromDocument( + Document* document) { + WebLocalFrameBase* local_frame_base = + WebLocalFrameBase::FromFrame(document->GetFrame()); + return new CompositorWorkerProxyClientImpl( + local_frame_base->LocalRootFrameWidget()->CompositorMutator()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.h b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.h index ae73dc96..8fbe759 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.h +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerProxyClientImpl.h
@@ -15,6 +15,7 @@ class CompositorMutatorImpl; class CompositorWorkerGlobalScope; +class Document; class WorkerGlobalScope; // Mediates between one CompositorWorkerGlobalScope and the associated @@ -43,6 +44,8 @@ void SetGlobalScope(WorkerGlobalScope*) override; void RequestAnimationFrame() override; + static CompositorWorkerProxyClientImpl* FromDocument(Document*); + private: bool ExecuteAnimationFrameCallbacks(double monotonic_time_now);
diff --git a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp index f39d023..48ea22b2 100644 --- a/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/modules/exported/WebEmbeddedWorkerImpl.cpp
@@ -105,9 +105,6 @@ installed_scripts_manager, std::unique_ptr<WebContentSettingsClient> content_settings_client) : worker_context_client_(std::move(client)), - installed_scripts_manager_( - WTF::MakeUnique<ServiceWorkerInstalledScriptsManager>( - std::move(installed_scripts_manager))), content_settings_client_(std::move(content_settings_client)), worker_inspector_proxy_(WorkerInspectorProxy::Create()), web_view_(nullptr), @@ -117,6 +114,13 @@ pause_after_download_state_(kDontPauseAfterDownload), waiting_for_debugger_state_(kNotWaitingForDebugger) { RunningWorkerInstances().insert(this); + + if (RuntimeEnabledFeatures::ServiceWorkerScriptStreamingEnabled()) { + DCHECK(installed_scripts_manager); + installed_scripts_manager_ = + WTF::MakeUnique<ServiceWorkerInstalledScriptsManager>( + std::move(installed_scripts_manager)); + } } WebEmbeddedWorkerImpl::~WebEmbeddedWorkerImpl() { @@ -339,7 +343,8 @@ // Kickstart the worker before loading the script when the script has been // installed. - if (installed_scripts_manager_->IsScriptInstalled( + if (RuntimeEnabledFeatures::ServiceWorkerScriptStreamingEnabled() && + installed_scripts_manager_->IsScriptInstalled( worker_start_data_.script_url)) { // TODO(shimazu): Move WorkerScriptLoaded to the correct place which is // after InstalledScriptsManager::GetScriptData() called at
diff --git a/third_party/WebKit/Source/modules/media_controls/BUILD.gn b/third_party/WebKit/Source/modules/media_controls/BUILD.gn index 76d6b1f1..77f7560 100644 --- a/third_party/WebKit/Source/modules/media_controls/BUILD.gn +++ b/third_party/WebKit/Source/modules/media_controls/BUILD.gn
@@ -46,6 +46,8 @@ "elements/MediaControlRemainingTimeDisplayElement.h", "elements/MediaControlTextTrackListElement.cpp", "elements/MediaControlTextTrackListElement.h", + "elements/MediaControlTimeDisplayElement.cpp", + "elements/MediaControlTimeDisplayElement.h", "elements/MediaControlTimelineElement.cpp", "elements/MediaControlTimelineElement.h", "elements/MediaControlTimelineMetrics.cpp",
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h index 44bcee6..9ed1d4a 100644 --- a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h
@@ -5,7 +5,7 @@ #ifndef MediaControlCurrentTimeDisplayElement_h #define MediaControlCurrentTimeDisplayElement_h -#include "core/html/shadow/MediaControlElementTypes.h" +#include "modules/media_controls/elements/MediaControlTimeDisplayElement.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h index 5808743..b497a8a 100644 --- a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h
@@ -5,7 +5,7 @@ #ifndef MediaControlRemainingTimeDisplayElement_h #define MediaControlRemainingTimeDisplayElement_h -#include "core/html/shadow/MediaControlElementTypes.h" +#include "modules/media_controls/elements/MediaControlTimeDisplayElement.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.cpp b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.cpp new file mode 100644 index 0000000..f266021 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.cpp
@@ -0,0 +1,24 @@ +// 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 "modules/media_controls/elements/MediaControlTimeDisplayElement.h" + +#include "modules/media_controls/MediaControlsImpl.h" + +namespace blink { + +MediaControlTimeDisplayElement::MediaControlTimeDisplayElement( + MediaControlsImpl& media_controls, + MediaControlElementType display_type) + : MediaControlDivElement(media_controls, display_type) {} + +void MediaControlTimeDisplayElement::SetCurrentValue(double time) { + current_value_ = time; +} + +double MediaControlTimeDisplayElement::CurrentValue() const { + return current_value_; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.h b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.h new file mode 100644 index 0000000..85ab767d --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlTimeDisplayElement.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 MediaControlTimeDisplayElement_h +#define MediaControlTimeDisplayElement_h + +#include "core/html/shadow/MediaControlElementTypes.h" +#include "modules/ModulesExport.h" + +namespace blink { + +class MediaControlsImpl; + +class MediaControlTimeDisplayElement : public MediaControlDivElement { + public: + void SetCurrentValue(double); + // Exported to be used by modules/accessibility. + MODULES_EXPORT double CurrentValue() const; + + protected: + MediaControlTimeDisplayElement(MediaControlsImpl&, MediaControlElementType); + + private: + double current_value_ = 0; +}; + +} // namespace blink + +#endif // MediaControlTimeDisplayElement_h
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp b/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp index 58e16b2d..80b8193 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp +++ b/third_party/WebKit/Source/modules/mediastream/MediaStreamTrack.cpp
@@ -303,6 +303,11 @@ break; } } + if (platform_settings.HasEchoCancellationValue()) { + settings.setEchoCancellation( + static_cast<bool>(platform_settings.echo_cancellation)); + } + if (image_capture_) image_capture_->GetMediaTrackSettings(settings); }
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl index 53e12bf..ac779fef 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl
@@ -14,8 +14,7 @@ // double volume; // long sampleRate; // long sampleSize; - // echoCancellation is not implemented: crbug.com/682245 - // boolean echoCancellation; + boolean echoCancellation; // latency and channelCount are not implemented. // double latency; // long channelCount;
diff --git a/third_party/WebKit/Source/modules/modules_idl_files.gni b/third_party/WebKit/Source/modules/modules_idl_files.gni index 37aa5da..52a3d62 100644 --- a/third_party/WebKit/Source/modules/modules_idl_files.gni +++ b/third_party/WebKit/Source/modules/modules_idl_files.gni
@@ -234,6 +234,7 @@ "sensor/Accelerometer.idl", "sensor/AmbientLightSensor.idl", "sensor/Gyroscope.idl", + "sensor/LinearAccelerationSensor.idl", "sensor/Magnetometer.idl", "sensor/OrientationSensor.idl", "sensor/RelativeOrientationSensor.idl",
diff --git a/third_party/WebKit/Source/modules/payments/PaymentManager.cpp b/third_party/WebKit/Source/modules/payments/PaymentManager.cpp index 7f69bdef..855c429 100644 --- a/third_party/WebKit/Source/modules/payments/PaymentManager.cpp +++ b/third_party/WebKit/Source/modules/payments/PaymentManager.cpp
@@ -47,8 +47,7 @@ frame->GetInterfaceProvider()->GetInterface(std::move(request)); } else if (context && context->IsWorkerGlobalScope()) { WorkerThread* thread = ToWorkerGlobalScope(context)->GetThread(); - if (thread) - thread->GetInterfaceProvider()->GetInterface(std::move(request)); + thread->GetInterfaceProvider().GetInterface(std::move(request)); } manager_.set_connection_error_handler(ConvertToBaseCallback(WTF::Bind(
diff --git a/third_party/WebKit/Source/modules/permissions/PermissionUtils.cpp b/third_party/WebKit/Source/modules/permissions/PermissionUtils.cpp index d6a77fb..8510138a 100644 --- a/third_party/WebKit/Source/modules/permissions/PermissionUtils.cpp +++ b/third_party/WebKit/Source/modules/permissions/PermissionUtils.cpp
@@ -22,21 +22,18 @@ bool ConnectToPermissionService( ExecutionContext* execution_context, mojom::blink::PermissionServiceRequest request) { - if (execution_context->IsDocument()) { - LocalFrame* frame = ToDocument(execution_context)->GetFrame(); - if (frame) { - frame->Client()->GetInterfaceProvider()->GetInterface(std::move(request)); - return true; - } - } else if (execution_context->IsWorkerGlobalScope()) { + if (execution_context->IsWorkerGlobalScope()) { WorkerThread* thread = ToWorkerGlobalScope(execution_context)->GetThread(); - if (thread) { - thread->GetInterfaceProvider()->GetInterface(std::move(request)); - return true; - } + thread->GetInterfaceProvider().GetInterface(std::move(request)); + return true; } - return false; + LocalFrame* frame = ToDocument(execution_context)->GetFrame(); + if (!frame) + return false; + + frame->GetInterfaceProvider()->GetInterface(std::move(request)); + return true; } PermissionDescriptorPtr CreatePermissionDescriptor(PermissionName name) {
diff --git a/third_party/WebKit/Source/modules/sensor/Accelerometer.cpp b/third_party/WebKit/Source/modules/sensor/Accelerometer.cpp index 4ece718c..21fcf8c 100644 --- a/third_party/WebKit/Source/modules/sensor/Accelerometer.cpp +++ b/third_party/WebKit/Source/modules/sensor/Accelerometer.cpp
@@ -11,7 +11,8 @@ Accelerometer* Accelerometer::Create(ExecutionContext* execution_context, const SensorOptions& options, ExceptionState& exception_state) { - return new Accelerometer(execution_context, options, exception_state); + return new Accelerometer(execution_context, options, exception_state, + SensorType::ACCELEROMETER); } // static @@ -22,11 +23,9 @@ Accelerometer::Accelerometer(ExecutionContext* execution_context, const SensorOptions& options, - ExceptionState& exception_state) - : Sensor(execution_context, - options, - exception_state, - SensorType::ACCELEROMETER) {} + ExceptionState& exception_state, + SensorType sensor_type) + : Sensor(execution_context, options, exception_state, sensor_type) {} double Accelerometer::x(bool& is_null) const { return ReadingValue(0, is_null);
diff --git a/third_party/WebKit/Source/modules/sensor/Accelerometer.h b/third_party/WebKit/Source/modules/sensor/Accelerometer.h index 9fd1d9a1..f604f4b 100644 --- a/third_party/WebKit/Source/modules/sensor/Accelerometer.h +++ b/third_party/WebKit/Source/modules/sensor/Accelerometer.h
@@ -9,7 +9,7 @@ namespace blink { -class Accelerometer final : public Sensor { +class Accelerometer : public Sensor { DEFINE_WRAPPERTYPEINFO(); public: @@ -24,8 +24,11 @@ DECLARE_VIRTUAL_TRACE(); - private: - Accelerometer(ExecutionContext*, const SensorOptions&, ExceptionState&); + protected: + Accelerometer(ExecutionContext*, + const SensorOptions&, + ExceptionState&, + device::mojom::blink::SensorType); }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/sensor/BUILD.gn b/third_party/WebKit/Source/modules/sensor/BUILD.gn index 5154b933..5d56057a 100644 --- a/third_party/WebKit/Source/modules/sensor/BUILD.gn +++ b/third_party/WebKit/Source/modules/sensor/BUILD.gn
@@ -14,6 +14,8 @@ "AmbientLightSensor.h", "Gyroscope.cpp", "Gyroscope.h", + "LinearAccelerationSensor.cpp", + "LinearAccelerationSensor.h", "Magnetometer.cpp", "Magnetometer.h", "OrientationSensor.cpp", @@ -32,9 +34,9 @@ deps = [ "//device/base/synchronization", - "//device/generic_sensor/public/cpp", - "//device/generic_sensor/public/interfaces:interfaces_blink", + "//services/device/public/cpp/generic_sensor", "//services/device/public/interfaces:constants_blink", + "//services/device/public/interfaces:generic_sensor_blink", "//services/service_manager/public/cpp", ] }
diff --git a/third_party/WebKit/Source/modules/sensor/DEPS b/third_party/WebKit/Source/modules/sensor/DEPS index 1ba448a5..6cffc204 100644 --- a/third_party/WebKit/Source/modules/sensor/DEPS +++ b/third_party/WebKit/Source/modules/sensor/DEPS
@@ -1,11 +1,12 @@ include_rules = [ - "+device/generic_sensor/public/cpp", - "+device/generic_sensor/public/interfaces", "-modules", "+modules/EventModules.h", "+modules/EventTargetModules.h", "+modules/ModulesExport.h", "+modules/sensor", "+mojo/public/cpp/bindings", + "+services/device/public/cpp/generic_sensor", + "+services/device/public/interfaces/sensor.mojom-blink.h", + "+services/device/public/interfaces/sensor_provider.mojom-blink.h", "+services/device/public/interfaces/constants.mojom-blink.h", ]
diff --git a/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.cpp b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.cpp new file mode 100644 index 0000000..81231833 --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.cpp
@@ -0,0 +1,39 @@ +// 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 "modules/sensor/LinearAccelerationSensor.h" + +using device::mojom::blink::SensorType; + +namespace blink { + +LinearAccelerationSensor* LinearAccelerationSensor::Create( + ExecutionContext* execution_context, + const SensorOptions& options, + ExceptionState& exception_state) { + return new LinearAccelerationSensor(execution_context, options, + exception_state); +} + +// static +LinearAccelerationSensor* LinearAccelerationSensor::Create( + ExecutionContext* execution_context, + ExceptionState& exception_state) { + return Create(execution_context, SensorOptions(), exception_state); +} + +LinearAccelerationSensor::LinearAccelerationSensor( + ExecutionContext* execution_context, + const SensorOptions& options, + ExceptionState& exception_state) + : Accelerometer(execution_context, + options, + exception_state, + SensorType::LINEAR_ACCELERATION) {} + +DEFINE_TRACE(LinearAccelerationSensor) { + Accelerometer::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.h b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.h new file mode 100644 index 0000000..7cfd04d --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.h
@@ -0,0 +1,31 @@ +// 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 LinearAccelerationSensor_h +#define LinearAccelerationSensor_h + +#include "modules/sensor/Accelerometer.h" + +namespace blink { + +class LinearAccelerationSensor final : public Accelerometer { + DEFINE_WRAPPERTYPEINFO(); + + public: + static LinearAccelerationSensor* Create(ExecutionContext*, + const SensorOptions&, + ExceptionState&); + static LinearAccelerationSensor* Create(ExecutionContext*, ExceptionState&); + + DECLARE_VIRTUAL_TRACE(); + + private: + LinearAccelerationSensor(ExecutionContext*, + const SensorOptions&, + ExceptionState&); +}; + +} // namespace blink + +#endif // LinearAccelerationSensor_h
diff --git a/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.idl b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.idl new file mode 100644 index 0000000..3c954ff --- /dev/null +++ b/third_party/WebKit/Source/modules/sensor/LinearAccelerationSensor.idl
@@ -0,0 +1,15 @@ +// 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. + +// Specification at: +// https://w3c.github.io/accelerometer/#linearaccelerationsensor + +[ + RuntimeEnabled=Sensor, + Constructor(optional SensorOptions sensorOptions), + ConstructorCallWith=ExecutionContext, + RaisesException=Constructor, + MeasureAs=LinearAccelerationSensorConstructor +] interface LinearAccelerationSensor : Accelerometer { +};
diff --git a/third_party/WebKit/Source/modules/sensor/Sensor.cpp b/third_party/WebKit/Source/modules/sensor/Sensor.cpp index 8438589..69305dba 100644 --- a/third_party/WebKit/Source/modules/sensor/Sensor.cpp +++ b/third_party/WebKit/Source/modules/sensor/Sensor.cpp
@@ -10,9 +10,9 @@ #include "core/inspector/ConsoleMessage.h" #include "core/timing/DOMWindowPerformance.h" #include "core/timing/Performance.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom-blink.h" #include "modules/sensor/SensorErrorEvent.h" #include "modules/sensor/SensorProviderProxy.h" +#include "services/device/public/interfaces/sensor.mojom-blink.h" using namespace device::mojom::blink;
diff --git a/third_party/WebKit/Source/modules/sensor/SensorProviderProxy.h b/third_party/WebKit/Source/modules/sensor/SensorProviderProxy.h index 211359c..737e9ba2 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorProviderProxy.h +++ b/third_party/WebKit/Source/modules/sensor/SensorProviderProxy.h
@@ -6,10 +6,10 @@ #define SensorProviderProxy_h #include "core/frame/LocalFrame.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom-blink.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom-blink.h" #include "platform/Supplementable.h" #include "platform/heap/Handle.h" +#include "services/device/public/interfaces/sensor.mojom-blink.h" +#include "services/device/public/interfaces/sensor_provider.mojom-blink.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp b/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp index 1c247a24..44a4eb2 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp +++ b/third_party/WebKit/Source/modules/sensor/SensorProxy.cpp
@@ -113,7 +113,7 @@ } void SensorProxy::UpdateSensorReading() { - DCHECK(IsInitialized()); + DCHECK(ShouldProcessReadings()); int read_attempts = 0; const int kMaxReadAttemptsCount = 10; device::SensorReading reading_data; @@ -139,7 +139,8 @@ void SensorProxy::SensorReadingChanged() { DCHECK_EQ(ReportingMode::ON_CHANGE, mode_); - UpdateSensorReading(); + if (ShouldProcessReadings()) + UpdateSensorReading(); } void SensorProxy::PageVisibilityChanged() { @@ -270,11 +271,15 @@ UpdateSensorReading(); } +bool SensorProxy::ShouldProcessReadings() const { + return IsInitialized() && !suspended_ && !frequencies_used_.IsEmpty(); +} + void SensorProxy::UpdatePollingStatus() { - bool start_polling = (mode_ == ReportingMode::CONTINUOUS) && - IsInitialized() && !suspended_ && - !frequencies_used_.IsEmpty(); - if (start_polling) { + if (mode_ != ReportingMode::CONTINUOUS) + return; + + if (ShouldProcessReadings()) { // TODO(crbug/721297) : We need to find out an algorithm for resulting // polling frequency. polling_timer_.StartRepeating(1 / frequencies_used_.back(),
diff --git a/third_party/WebKit/Source/modules/sensor/SensorProxy.h b/third_party/WebKit/Source/modules/sensor/SensorProxy.h index 4279f841..939bcea3 100644 --- a/third_party/WebKit/Source/modules/sensor/SensorProxy.h +++ b/third_party/WebKit/Source/modules/sensor/SensorProxy.h
@@ -8,14 +8,14 @@ #include "core/dom/ExceptionCode.h" #include "core/page/FocusChangedObserver.h" #include "core/page/PageVisibilityObserver.h" -#include "device/generic_sensor/public/cpp/sensor_reading.h" -#include "device/generic_sensor/public/interfaces/sensor.mojom-blink.h" -#include "device/generic_sensor/public/interfaces/sensor_provider.mojom-blink.h" #include "mojo/public/cpp/bindings/binding.h" #include "platform/Supplementable.h" #include "platform/Timer.h" #include "platform/heap/Handle.h" #include "platform/wtf/Vector.h" +#include "services/device/public/cpp/generic_sensor/sensor_reading.h" +#include "services/device/public/interfaces/sensor.mojom-blink.h" +#include "services/device/public/interfaces/sensor_provider.mojom-blink.h" namespace blink { @@ -115,10 +115,16 @@ bool TryReadFromBuffer(device::SensorReading& result); void OnPollingTimer(TimerBase*); - // Starts polling timer if needed (continuous reporting, initialized, not - // suspended and has configurations added). + + // Returns 'true' if readings should be propagated to Observers + // (i.e. proxy is initialized, not suspended and has active configurations); + // returns 'false' otherwise. + bool ShouldProcessReadings() const; + + // Starts or stops polling timer. void UpdatePollingStatus(); + // Suspends or resumes the wrapped sensor. void UpdateSuspendedStatus(); device::mojom::blink::SensorType type_;
diff --git a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp index 64fd62f..3559fbf 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/WebEmbeddedWorkerImplTest.cpp
@@ -5,6 +5,7 @@ #include "public/web/WebEmbeddedWorker.h" #include <memory> +#include "platform/RuntimeEnabledFeatures.h" #include "platform/WaitableEvent.h" #include "platform/WebTaskRunner.h" #include "platform/testing/URLTestHelpers.h" @@ -130,7 +131,11 @@ auto installed_scripts_manager = WTF::MakeUnique<MockServiceWorkerInstalledScriptsManager>(); mock_client_ = client.get(); - mock_installed_scripts_manager_ = installed_scripts_manager.get(); + if (RuntimeEnabledFeatures::ServiceWorkerScriptStreamingEnabled()) { + mock_installed_scripts_manager_ = installed_scripts_manager.get(); + } else { + mock_installed_scripts_manager_ = nullptr; + } worker_ = WebEmbeddedWorker::Create( std::move(client), std::move(installed_scripts_manager), nullptr); @@ -168,7 +173,6 @@ EXPECT_CALL(*mock_client_, WorkerReadyForInspection()).Times(1); worker_->StartWorkerContext(start_data_); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); EXPECT_CALL(*mock_client_, WorkerContextFailedToStart()).Times(1); worker_->TerminateWorkerContext(); @@ -181,7 +185,6 @@ WebEmbeddedWorkerStartData::kWaitForDebugger; worker_->StartWorkerContext(start_data_); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); EXPECT_CALL(*mock_client_, WorkerContextFailedToStart()).Times(1); worker_->TerminateWorkerContext(); @@ -192,18 +195,22 @@ EXPECT_CALL(*mock_client_, WorkerReadyForInspection()).Times(1); worker_->StartWorkerContext(start_data_); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Terminate before loading the script. EXPECT_CALL(*mock_client_, WorkerContextFailedToStart()).Times(1); @@ -221,13 +228,18 @@ // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Load the script. EXPECT_CALL(*mock_client_, WorkerScriptLoaded()).Times(1); @@ -262,13 +274,18 @@ // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Load the script. EXPECT_CALL(*mock_client_, WorkerScriptLoaded()).Times(0); @@ -288,13 +305,18 @@ // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Load the script. mock_client_->SetHasAssociatedRegistration(false); @@ -320,27 +342,37 @@ // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Load the script. EXPECT_CALL(*mock_client_, WorkerScriptLoaded()).Times(1); EXPECT_CALL(*mock_client_, CreateServiceWorkerProviderProxy()) .WillOnce(::testing::Return(nullptr)); // This is called on the worker thread. - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); mock_client_->WaitUntilScriptEvaluated(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Terminate the running worker thread. EXPECT_CALL(*mock_client_, WorkerContextFailedToStart()).Times(0); @@ -365,12 +397,18 @@ // Load the shadow page. EXPECT_CALL(*mock_client_, CreateServiceWorkerNetworkProviderProxy()) .WillOnce(::testing::Return(nullptr)); - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } Platform::Current()->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Load the script. EXPECT_CALL(*mock_client_, WorkerScriptLoaded()).Times(1); @@ -382,14 +420,19 @@ EXPECT_CALL(*mock_client_, CreateServiceWorkerProviderProxy()) .WillOnce(::testing::Return(nullptr)); // This is called on the worker thread. - EXPECT_CALL(*mock_installed_scripts_manager_, - IsScriptInstalled(start_data_.script_url)) - .Times(1) - .WillOnce(::testing::Return(false)); + if (mock_installed_scripts_manager_) { + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(start_data_.script_url)) + .Times(1) + .WillOnce(::testing::Return(false)); + } worker_->ResumeAfterDownload(); mock_client_->WaitUntilScriptEvaluated(); ::testing::Mock::VerifyAndClearExpectations(mock_client_); - ::testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + if (mock_installed_scripts_manager_) { + ::testing::Mock::VerifyAndClearExpectations( + mock_installed_scripts_manager_); + } // Terminate the running worker thread. EXPECT_CALL(*mock_client_, WorkerContextFailedToStart()).Times(0);
diff --git a/third_party/WebKit/Source/modules/shapedetection/BarcodeDetector.cpp b/third_party/WebKit/Source/modules/shapedetection/BarcodeDetector.cpp index eafffd8..a4b60bb 100644 --- a/third_party/WebKit/Source/modules/shapedetection/BarcodeDetector.cpp +++ b/third_party/WebKit/Source/modules/shapedetection/BarcodeDetector.cpp
@@ -6,14 +6,12 @@ #include "core/dom/DOMException.h" #include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameClient.h" #include "core/geometry/DOMRect.h" #include "core/html/canvas/CanvasImageSource.h" #include "core/workers/WorkerThread.h" #include "modules/imagecapture/Point2D.h" #include "modules/shapedetection/DetectedBarcode.h" #include "public/platform/InterfaceProvider.h" -#include "public/platform/Platform.h" #include "services/service_manager/public/cpp/interface_provider.h" namespace blink { @@ -27,11 +25,10 @@ if (context->IsDocument()) { LocalFrame* frame = ToDocument(context)->GetFrame(); if (frame) - frame->Client()->GetInterfaceProvider()->GetInterface(std::move(request)); - } else if (context->IsWorkerGlobalScope()) { + frame->GetInterfaceProvider()->GetInterface(std::move(request)); + } else { WorkerThread* thread = ToWorkerGlobalScope(context)->GetThread(); - if (thread) - thread->GetInterfaceProvider()->GetInterface(std::move(request)); + thread->GetInterfaceProvider().GetInterface(std::move(request)); } barcode_service_.set_connection_error_handler(ConvertToBaseCallback(
diff --git a/third_party/WebKit/Source/modules/shapedetection/FaceDetector.cpp b/third_party/WebKit/Source/modules/shapedetection/FaceDetector.cpp index cca2570..f14dc03 100644 --- a/third_party/WebKit/Source/modules/shapedetection/FaceDetector.cpp +++ b/third_party/WebKit/Source/modules/shapedetection/FaceDetector.cpp
@@ -6,7 +6,6 @@ #include "core/dom/DOMException.h" #include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameClient.h" #include "core/geometry/DOMRect.h" #include "core/html/canvas/CanvasImageSource.h" #include "core/workers/WorkerThread.h" @@ -39,11 +38,10 @@ if (context->IsDocument()) { LocalFrame* frame = ToDocument(context)->GetFrame(); if (frame) - frame->Client()->GetInterfaceProvider()->GetInterface(std::move(request)); - } else if (context->IsWorkerGlobalScope()) { + frame->GetInterfaceProvider()->GetInterface(std::move(request)); + } else { WorkerThread* thread = ToWorkerGlobalScope(context)->GetThread(); - if (thread) - thread->GetInterfaceProvider()->GetInterface(std::move(request)); + thread->GetInterfaceProvider().GetInterface(std::move(request)); } provider->CreateFaceDetection(mojo::MakeRequest(&face_service_), std::move(face_detector_options));
diff --git a/third_party/WebKit/Source/modules/shapedetection/TextDetector.cpp b/third_party/WebKit/Source/modules/shapedetection/TextDetector.cpp index 82ba130c..09fb158 100644 --- a/third_party/WebKit/Source/modules/shapedetection/TextDetector.cpp +++ b/third_party/WebKit/Source/modules/shapedetection/TextDetector.cpp
@@ -6,13 +6,11 @@ #include "core/dom/DOMException.h" #include "core/frame/LocalFrame.h" -#include "core/frame/LocalFrameClient.h" #include "core/geometry/DOMRect.h" #include "core/html/canvas/CanvasImageSource.h" #include "core/workers/WorkerThread.h" #include "modules/shapedetection/DetectedText.h" #include "public/platform/InterfaceProvider.h" -#include "public/platform/Platform.h" #include "services/service_manager/public/cpp/interface_provider.h" namespace blink { @@ -26,11 +24,10 @@ if (context->IsDocument()) { LocalFrame* frame = ToDocument(context)->GetFrame(); if (frame) - frame->Client()->GetInterfaceProvider()->GetInterface(std::move(request)); - } else if (context->IsWorkerGlobalScope()) { + frame->GetInterfaceProvider()->GetInterface(std::move(request)); + } else { WorkerThread* thread = ToWorkerGlobalScope(context)->GetThread(); - if (thread) - thread->GetInterfaceProvider()->GetInterface(std::move(request)); + thread->GetInterfaceProvider().GetInterface(std::move(request)); } text_service_.set_connection_error_handler(ConvertToBaseCallback(WTF::Bind(
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp index ffb6b1e..832d9d1 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.cpp +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.cpp
@@ -56,7 +56,18 @@ : vr_display_(vr_display) {} ~VRDisplayFrameRequestCallback() override {} void handleEvent(double high_res_time_ms) override { - vr_display_->OnMagicWindowVSync(high_res_time_ms / 1000.0); + double monotonic_time; + if (!vr_display_->GetDocument() || !vr_display_->GetDocument()->Loader()) { + monotonic_time = WTF::MonotonicallyIncreasingTime(); + } else { + // Convert document-zero time back to monotonic time. + double reference_monotonic_time = vr_display_->GetDocument() + ->Loader() + ->GetTiming() + .ReferenceMonotonicTime(); + monotonic_time = (high_res_time_ms / 1000.0) + reference_monotonic_time; + } + vr_display_->OnMagicWindowVSync(monotonic_time); } DEFINE_INLINE_VIRTUAL_TRACE() { @@ -885,11 +896,6 @@ } pending_vsync_ = false; - // Ensure a consistent timebase with document rAF. - if (timebase_ < 0) { - timebase_ = WTF::MonotonicallyIncreasingTime() - time_delta.InSecondsF(); - } - frame_pose_ = std::move(pose); vr_frame_id_ = frame_id; @@ -904,7 +910,7 @@ Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask( BLINK_FROM_HERE, WTF::Bind(&VRDisplay::ProcessScheduledAnimations, - WrapWeakPersistent(this), timebase_ + time_delta.InSecondsF())); + WrapWeakPersistent(this), time_delta.InSecondsF())); } void VRDisplay::OnMagicWindowVSync(double timestamp) {
diff --git a/third_party/WebKit/Source/modules/vr/VRDisplay.h b/third_party/WebKit/Source/modules/vr/VRDisplay.h index 9e2f954..828a750524 100644 --- a/third_party/WebKit/Source/modules/vr/VRDisplay.h +++ b/third_party/WebKit/Source/modules/vr/VRDisplay.h
@@ -206,7 +206,6 @@ bool did_submit_this_frame_ = false; bool in_display_activate_ = false; bool display_blurred_ = false; - double timebase_ = -1; bool pending_previous_frame_render_ = false; bool pending_submit_frame_ = false; bool pending_present_request_ = false;
diff --git a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp index 83ccd58..ad4478cb 100644 --- a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp +++ b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.cpp
@@ -81,12 +81,16 @@ Document& document = *ToDocument(ExecutionContext::From(script_state)); if (options.hasSysex() && options.sysex()) { - UseCounter::Count(document, WebFeature::kRequestMIDIAccessWithSysExOption); + UseCounter::Count( + document, + WebFeature::kRequestMIDIAccessWithSysExOption_ObscuredByFootprinting); UseCounter::CountCrossOriginIframe( - document, WebFeature::kRequestMIDIAccessIframeWithSysExOption); + document, + WebFeature:: + kRequestMIDIAccessIframeWithSysExOption_ObscuredByFootprinting); } - UseCounter::CountCrossOriginIframe(document, - WebFeature::kRequestMIDIAccessIframe); + UseCounter::CountCrossOriginIframe( + document, WebFeature::kRequestMIDIAccessIframe_ObscuredByFootprinting); return MIDIAccessInitializer::Start(script_state, options); }
diff --git a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.idl b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.idl index 586f887..df250bc 100644 --- a/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.idl +++ b/third_party/WebKit/Source/modules/webmidi/NavigatorWebMIDI.idl
@@ -31,5 +31,8 @@ // https://webaudio.github.io/web-midi-api/#requestMIDIAccess partial interface Navigator { - [CallWith=ScriptState, MeasureAs=RequestMIDIAccess] Promise requestMIDIAccess(optional MIDIOptions options); + [ + CallWith = ScriptState, MeasureAs = RequestMIDIAccess_ObscuredByFootprinting + ] Promise + requestMIDIAccess(optional MIDIOptions options); };
diff --git a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp index 46fe4d4..ab15d531 100644 --- a/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp +++ b/third_party/WebKit/Source/modules/websockets/WorkerWebSocketChannel.cpp
@@ -403,7 +403,7 @@ TaskRunnerHelper::Get(TaskType::kNetworking, worker_global_scope_.Get()); WorkerThread* worker_thread = worker_global_scope_->GetThread(); mojom::blink::WebSocketPtrInfo socket_ptr_info; - worker_thread->GetInterfaceProvider()->GetInterface( + worker_thread->GetInterfaceProvider().GetInterface( mojo::MakeRequest(&socket_ptr_info)); parent_frame_task_runners_->Get(TaskType::kNetworking) ->PostTask(
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 093d6e6..79c3117 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -2010,7 +2010,6 @@ "//cc", "//cc:test_support", "//cc/blink", - "//components/variations", "//device/base/synchronization", "//mojo/common:test_common_custom_types_blink", "//mojo/edk/system",
diff --git a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 index c7d5cad..9a68778 100644 --- a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 +++ b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
@@ -933,6 +933,9 @@ status: "stable", }, { + name: "ServiceWorkerScriptStreaming", + }, + { name: "SetRootScroller", status: "experimental", }, @@ -1038,6 +1041,7 @@ }, { name: "ValidationBubbleInRenderer", + status: "experimental", }, { name: "VibrateRequiresUserGesture",
diff --git a/third_party/WebKit/Source/platform/audio/AudioDestination.cpp b/third_party/WebKit/Source/platform/audio/AudioDestination.cpp index 75aaa58..b3075646 100644 --- a/third_party/WebKit/Source/platform/audio/AudioDestination.cpp +++ b/third_party/WebKit/Source/platform/audio/AudioDestination.cpp
@@ -50,12 +50,6 @@ // that we would ever need. The current UMA stats indicates that this is, in // fact, probably too small. There are Android devices out there with a size of // 8000 or so. We might need to make this larger. See: crbug.com/670747 -// TODO(andrew.macpherson): This either needs to be bigger since some OSes allow -// buffer sizes of 8192 via latencyHint now or else we need to do some -// validation of the latencyHint 'exact' size before passing it to -// CreateAudioDevice. Clamping may be tricky though as the buffer size is -// dependent on the sample rate for some platforms and we're passing in a time -// value and not a buffer size in the latencyHint. See: crbug.com/737047 const size_t kFIFOSize = 8192; std::unique_ptr<AudioDestination> AudioDestination::Create(
diff --git a/third_party/WebKit/Source/platform/exported/WebMediaStreamSource.cpp b/third_party/WebKit/Source/platform/exported/WebMediaStreamSource.cpp index b1fb39b..cc7cb6c 100644 --- a/third_party/WebKit/Source/platform/exported/WebMediaStreamSource.cpp +++ b/third_party/WebKit/Source/platform/exported/WebMediaStreamSource.cpp
@@ -31,6 +31,8 @@ #include "public/platform/WebMediaStreamSource.h" #include <memory> +#include <utility> + #include "platform/audio/AudioBus.h" #include "platform/mediastream/MediaStreamSource.h" #include "platform/wtf/PtrUtil.h" @@ -152,6 +154,11 @@ WTF::WrapUnique(new ExtraDataContainer(WTF::WrapUnique(extra_data)))); } +void WebMediaStreamSource::SetEchoCancellation(bool echo_cancellation) { + DCHECK(!private_.IsNull()); + private_->SetEchoCancellation(echo_cancellation); +} + WebMediaConstraints WebMediaStreamSource::Constraints() { DCHECK(!private_.IsNull()); return private_->Constraints();
diff --git a/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp b/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp index 7a0bd44..584a51f7 100644 --- a/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRuntimeFeatures.cpp
@@ -364,6 +364,10 @@ RuntimeEnabledFeatures::SetServiceWorkerNavigationPreloadEnabled(enable); } +void WebRuntimeFeatures::EnableServiceWorkerScriptStreaming(bool enable) { + RuntimeEnabledFeatures::SetServiceWorkerScriptStreamingEnabled(enable); +} + void WebRuntimeFeatures::EnableAutoplayMutedVideos(bool enable) { RuntimeEnabledFeatures::SetAutoplayMutedVideosEnabled(enable); }
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp index 5ed0c32..36e1b2d 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp
@@ -344,11 +344,13 @@ ImageFrame* frame = (*decoder)->FrameBufferAtIndex(index); + // SetMemoryAllocator() can try to access decoder's data, so + // we have to do it before clearing SegmentReader. + if (using_external_allocator) + (*decoder)->SetMemoryAllocator(nullptr); (*decoder)->SetData(PassRefPtr<SegmentReader>(nullptr), false); // Unref SegmentReader from ImageDecoder. (*decoder)->ClearCacheExceptFrame(index); - if (using_external_allocator) - (*decoder)->SetMemoryAllocator(0); if (!frame || frame->GetStatus() == ImageFrame::kFrameEmpty) return false;
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.cpp b/third_party/WebKit/Source/platform/heap/HeapPage.cpp index a9a73038..962a2765 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapPage.cpp
@@ -52,8 +52,6 @@ #include "public/platform/Platform.h" #ifdef ANNOTATE_CONTIGUOUS_CONTAINER -// FIXME: have ContainerAnnotations.h define an ENABLE_-style name instead. -#define ENABLE_ASAN_CONTAINER_ANNOTATIONS 1 // When finalizing a non-inlined vector backing store/container, remove // its contiguous container annotation. Required as it will not be destructed @@ -81,7 +79,6 @@ static_cast<LargeObjectPage*>(large_page)->SetIsVectorBackingPage(); \ } #else -#define ENABLE_ASAN_CONTAINER_ANNOTATIONS 0 #define ASAN_RETIRE_CONTAINER_ANNOTATION(payload, payloadSize) #define ASAN_MARK_LARGE_VECTOR_CONTAINER(arena, largeObject) #endif @@ -1713,7 +1710,7 @@ size_t payload_size) : BasePage(storage, arena), payload_size_(payload_size) -#if ENABLE(ASAN_CONTAINER_ANNOTATIONS) +#ifdef ANNOTATE_CONTIGUOUS_CONTAINER , is_vector_backing_page_(false) #endif
diff --git a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp index ad122f2..65b2dc1 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoder.cpp
@@ -85,6 +85,8 @@ bool ICOImageDecoder::FrameIsCompleteAtIndex(size_t index) const { if (index >= dir_entries_.size()) return false; + + SECURITY_DCHECK(data_); const IconDirectoryEntry& dir_entry = dir_entries_[index]; return (dir_entry.image_offset_ + dir_entry.byte_size_) <= data_->size(); } @@ -126,7 +128,7 @@ // If DecodeSize() fails, return the existing number of frames. This way // if we get halfway through the image before decoding fails, we won't // suddenly start reporting that the image has zero frames. - if (Failed()) + if (Failed() || !data_) return frame_buffer_cache_.size(); // If the file is incomplete, return the length of the sequence of completely @@ -152,7 +154,7 @@ } void ICOImageDecoder::Decode(size_t index, bool only_size) { - if (Failed()) + if (Failed() || !data_) return; // Defensively clear the FastSharedBufferReader's cache, as another caller @@ -234,6 +236,7 @@ bool ICOImageDecoder::ProcessDirectory() { // Read directory. + SECURITY_DCHECK(data_); DCHECK(!decoded_offset_); if (data_->size() < kSizeOfDirectory) return false; @@ -252,6 +255,7 @@ bool ICOImageDecoder::ProcessDirectoryEntries() { // Read directory entries. + SECURITY_DCHECK(data_); DCHECK_EQ(decoded_offset_, kSizeOfDirectory); if ((decoded_offset_ > data_->size()) || ((data_->size() - decoded_offset_) < @@ -328,6 +332,7 @@ ICOImageDecoder::ImageType ICOImageDecoder::ImageTypeAtIndex(size_t index) { // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic // number. + SECURITY_DCHECK(data_); SECURITY_DCHECK(index < dir_entries_.size()); const uint32_t image_offset = dir_entries_[index].image_offset_; if ((image_offset > data_->size()) || ((data_->size() - image_offset) < 4))
diff --git a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoderTest.cpp b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoderTest.cpp index f5b0b4a..4b776e6 100644 --- a/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoderTest.cpp +++ b/third_party/WebKit/Source/platform/image-decoders/ico/ICOImageDecoderTest.cpp
@@ -88,4 +88,29 @@ kAnimationNone); } +TEST(ICOImageDecoderTests, NullData) { + static constexpr size_t kSizeOfBadBlock = 6 + 16 + 1; + + RefPtr<SharedBuffer> ico_file_data = + ReadFile("/LayoutTests/images/resources/png-in-ico.ico"); + ASSERT_FALSE(ico_file_data->IsEmpty()); + ASSERT_LT(kSizeOfBadBlock, ico_file_data->size()); + + RefPtr<SharedBuffer> truncated_data = + SharedBuffer::Create(ico_file_data->Data(), kSizeOfBadBlock); + auto decoder = CreateDecoder(); + + decoder->SetData(truncated_data.Get(), false); + decoder->SetMemoryAllocator(nullptr); + EXPECT_FALSE(decoder->Failed()); + + auto* frame = decoder->FrameBufferAtIndex(0); + EXPECT_EQ(nullptr, frame); + + decoder->SetData(PassRefPtr<SegmentReader>(nullptr), false); + decoder->ClearCacheExceptFrame(0); + decoder->SetMemoryAllocator(nullptr); + EXPECT_FALSE(decoder->Failed()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/loader/fetch/RawResource.h b/third_party/WebKit/Source/platform/loader/fetch/RawResource.h index 6594f6f6..f80ae88 100644 --- a/third_party/WebKit/Source/platform/loader/fetch/RawResource.h +++ b/third_party/WebKit/Source/platform/loader/fetch/RawResource.h
@@ -106,7 +106,7 @@ void ReportResourceTimingToClients(const ResourceTimingInfo&) override; }; -// TODO(yhirano): Recover #if ENABLE(SECURITY_ASSERT) when we stop adding +// TODO(yhirano): Recover #if ENABLE_SECURITY_ASSERT when we stop adding // RawResources to MemoryCache. inline bool IsRawResource(const Resource& resource) { Resource::Type type = resource.GetType();
diff --git a/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.cpp b/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.cpp index 5cab26fb..7f5ab9c 100644 --- a/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.cpp +++ b/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.cpp
@@ -108,6 +108,9 @@ void MediaStreamSource::GetSettings(WebMediaStreamTrack::Settings& settings) { settings.device_id = Id(); + + if (echo_cancellation_.has_value()) + settings.echo_cancellation = *echo_cancellation_; } void MediaStreamSource::SetAudioFormat(size_t number_of_channels,
diff --git a/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.h b/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.h index 649db998..c075e9e1 100644 --- a/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.h +++ b/third_party/WebKit/Source/platform/mediastream/MediaStreamSource.h
@@ -33,9 +33,12 @@ #define MediaStreamSource_h #include <memory> +#include <utility> + #include "platform/PlatformExport.h" #include "platform/audio/AudioDestinationConsumer.h" #include "platform/wtf/Allocator.h" +#include "platform/wtf/Optional.h" #include "platform/wtf/ThreadingPrimitives.h" #include "platform/wtf/Vector.h" #include "platform/wtf/text/WTFString.h" @@ -90,6 +93,10 @@ extra_data_ = std::move(extra_data); } + void SetEchoCancellation(bool echo_cancellation) { + echo_cancellation_ = WTF::make_optional(echo_cancellation); + } + void SetConstraints(WebMediaConstraints constraints) { constraints_ = constraints; } @@ -131,6 +138,7 @@ HashSet<AudioDestinationConsumer*> audio_consumers_; std::unique_ptr<ExtraData> extra_data_; WebMediaConstraints constraints_; + WTF::Optional<bool> echo_cancellation_; }; typedef HeapVector<Member<MediaStreamSource>> MediaStreamSourceVector;
diff --git a/third_party/WebKit/Source/platform/network/HTTPParsers.cpp b/third_party/WebKit/Source/platform/network/HTTPParsers.cpp index c4ab815..6057e43 100644 --- a/third_party/WebKit/Source/platform/network/HTTPParsers.cpp +++ b/third_party/WebKit/Source/platform/network/HTTPParsers.cpp
@@ -880,12 +880,12 @@ break; } - double duration = 0.0; + double value = 0.0; String description = ""; if (tokenizer.Consume('=')) { - StringView durationOutput; - if (tokenizer.ConsumeToken(Mode::kNormal, durationOutput)) { - duration = durationOutput.ToString().ToDouble(); + StringView valueOutput; + if (tokenizer.ConsumeToken(Mode::kNormal, valueOutput)) { + value = valueOutput.ToString().ToDouble(); } } if (tokenizer.Consume(';')) { @@ -893,7 +893,7 @@ } headers->push_back(WTF::MakeUnique<ServerTimingHeader>( - metric.ToString(), duration, description)); + metric.ToString(), value, description)); if (!tokenizer.Consume(',')) { break;
diff --git a/third_party/WebKit/Source/platform/network/HTTPParsers.h b/third_party/WebKit/Source/platform/network/HTTPParsers.h index 3294bbd..40fee8b 100644 --- a/third_party/WebKit/Source/platform/network/HTTPParsers.h +++ b/third_party/WebKit/Source/platform/network/HTTPParsers.h
@@ -85,11 +85,11 @@ struct ServerTimingHeader { String metric; - double duration; + double value; String description; - ServerTimingHeader(String metric, double duration, String description) - : metric(metric), duration(duration), description(description) {} + ServerTimingHeader(String metric, double value, String description) + : metric(metric), value(value), description(description) {} }; using ServerTimingHeaderVector = Vector<std::unique_ptr<ServerTimingHeader>>;
diff --git a/third_party/WebKit/Source/platform/network/HTTPParsersTest.cpp b/third_party/WebKit/Source/platform/network/HTTPParsersTest.cpp index bd61d01..16760f9 100644 --- a/third_party/WebKit/Source/platform/network/HTTPParsersTest.cpp +++ b/third_party/WebKit/Source/platform/network/HTTPParsersTest.cpp
@@ -486,7 +486,7 @@ for (const auto& header : *results) { Vector<String> expectedResult = expectedResults[i++]; EXPECT_EQ(header->metric, expectedResult[0]); - EXPECT_EQ(header->duration, expectedResult[1].ToDouble()); + EXPECT_EQ(header->value, expectedResult[1].ToDouble()); EXPECT_EQ(header->description, expectedResult[2]); } }
diff --git a/third_party/WebKit/Source/platform/scheduler/DEPS b/third_party/WebKit/Source/platform/scheduler/DEPS index c8e15bb..e4af261 100644 --- a/third_party/WebKit/Source/platform/scheduler/DEPS +++ b/third_party/WebKit/Source/platform/scheduler/DEPS
@@ -29,7 +29,7 @@ specific_include_rules = { ".*test\.cc": [ + "+base/metrics/field_trial_param_associator.h", "+testing", - "+components/variations/variations_associated_data.h", ], }
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl_unittest.cc index 4964b29..25524888 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/web_view_scheduler_impl_unittest.cc
@@ -9,10 +9,10 @@ #include "base/callback.h" #include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" +#include "base/metrics/field_trial_param_associator.h" #include "base/metrics/field_trial_params.h" #include "base/test/simple_test_tick_clock.h" #include "cc/test/ordered_simple_task_runner.h" -#include "components/variations/variations_associated_data.h" #include "platform/WebTaskRunner.h" #include "platform/scheduler/base/test_time_source.h" #include "platform/scheduler/child/scheduler_tqm_delegate_for_test.h" @@ -783,7 +783,7 @@ ElementsAre(base::TimeTicks() + base::TimeDelta::FromSeconds(4), base::TimeTicks() + base::TimeDelta::FromSeconds(26))); - variations::testing::ClearAllVariationParams(); + base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting(); } TEST_F(WebViewSchedulerImplTest, OpenWebSocketExemptsFromBudgetThrottling) { @@ -899,7 +899,7 @@ base::TimeTicks() + base::TimeDelta::FromSeconds(109), base::TimeTicks() + base::TimeDelta::FromSeconds(134))); - variations::testing::ClearAllVariationParams(); + base::FieldTrialParamAssociator::GetInstance()->ClearAllParamsForTesting(); } } // namespace scheduler
diff --git a/third_party/WebKit/Source/platform/wtf/Assertions.h b/third_party/WebKit/Source/platform/wtf/Assertions.h index cb506e514..aed8561 100644 --- a/third_party/WebKit/Source/platform/wtf/Assertions.h +++ b/third_party/WebKit/Source/platform/wtf/Assertions.h
@@ -109,8 +109,8 @@ LAZY_STREAM(logging::LogMessage(file, line, #assertion).stream(), \ DCHECK_IS_ON() ? !(assertion) : false) -// Users must test "#if ENABLE(SECURITY_ASSERT)", which helps ensure -// that code testing this macro has included this header. +// Users must test "#if ENABLE_SECURITY_ASSERT", which helps ensure that code +// testing this macro has included this header. #if defined(ADDRESS_SANITIZER) || DCHECK_IS_ON() #define ENABLE_SECURITY_ASSERT 1 #else
diff --git a/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp b/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp index fd4e9562..32ff23ee 100644 --- a/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp +++ b/third_party/WebKit/Source/platform/wtf/AssertionsTest.cpp
@@ -26,7 +26,7 @@ EXPECT_DEATH_IF_SUPPORTED(CHECK(false), ""); SECURITY_DCHECK(true); -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT EXPECT_DEATH_IF_SUPPORTED(SECURITY_DCHECK(false), ""); #else SECURITY_DCHECK(false);
diff --git a/third_party/WebKit/Source/platform/wtf/HashTable.h b/third_party/WebKit/Source/platform/wtf/HashTable.h index 0afa349c..3d5f2513 100644 --- a/third_party/WebKit/Source/platform/wtf/HashTable.h +++ b/third_party/WebKit/Source/platform/wtf/HashTable.h
@@ -568,7 +568,7 @@ bool is_new_entry) : stored_value(stored_value), is_new_entry(is_new_entry) -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT , container_(container), container_modifications_(container->Modifications()) @@ -581,7 +581,7 @@ ValueType* stored_value; bool is_new_entry; -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT ~HashTableAddResult() { // If rehash happened before accessing storedValue, it's // use-after-free. Any modification may cause a rehash, so we check for
diff --git a/third_party/WebKit/Source/platform/wtf/RefCounted.h b/third_party/WebKit/Source/platform/wtf/RefCounted.h index 7808469..9bcd861 100644 --- a/third_party/WebKit/Source/platform/wtf/RefCounted.h +++ b/third_party/WebKit/Source/platform/wtf/RefCounted.h
@@ -67,7 +67,7 @@ protected: RefCountedBase() : ref_count_(1) -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT , deletion_has_begun_(false) #endif @@ -96,7 +96,7 @@ DCHECK_GT(ref_count_, 0); --ref_count_; if (!ref_count_) { -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT deletion_has_begun_ = true; #endif return true; @@ -110,12 +110,12 @@ #endif private: -#if CHECK_REF_COUNTED_LIFECYCLE || ENABLE(SECURITY_ASSERT) +#if CHECK_REF_COUNTED_LIFECYCLE || ENABLE_SECURITY_ASSERT friend void Adopted(RefCountedBase*); #endif mutable int ref_count_; -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT mutable bool deletion_has_begun_; #endif #if CHECK_REF_COUNTED_LIFECYCLE @@ -124,7 +124,7 @@ #endif }; -#if CHECK_REF_COUNTED_LIFECYCLE || ENABLE(SECURITY_ASSERT) +#if CHECK_REF_COUNTED_LIFECYCLE || ENABLE_SECURITY_ASSERT inline void Adopted(RefCountedBase* object) { if (!object) return;
diff --git a/third_party/WebKit/Source/platform/wtf/SizeLimits.cpp b/third_party/WebKit/Source/platform/wtf/SizeLimits.cpp index b3707dc5..c064e227 100644 --- a/third_party/WebKit/Source/platform/wtf/SizeLimits.cpp +++ b/third_party/WebKit/Source/platform/wtf/SizeLimits.cpp
@@ -41,11 +41,11 @@ namespace WTF { -#if DCHECK_IS_ON() || ENABLE(SECURITY_ASSERT) +#if DCHECK_IS_ON() || ENABLE_SECURITY_ASSERT // The debug/assertion version may get bigger. struct SameSizeAsRefCounted { int a; -#if ENABLE(SECURITY_ASSERT) +#if ENABLE_SECURITY_ASSERT bool b; #endif #if DCHECK_IS_ON()
diff --git a/third_party/WebKit/Source/platform/wtf/build_config.h b/third_party/WebKit/Source/platform/wtf/build_config.h index 145977f66..d40ab5f 100644 --- a/third_party/WebKit/Source/platform/wtf/build_config.h +++ b/third_party/WebKit/Source/platform/wtf/build_config.h
@@ -45,9 +45,6 @@ /* USE() - use a particular third-party library or optional OS service */ #define USE(WTF_FEATURE) \ (defined WTF_USE_##WTF_FEATURE && WTF_USE_##WTF_FEATURE) -/* ENABLE() - turn on a specific feature of WebKit */ -#define ENABLE(WTF_FEATURE) \ - (defined ENABLE_##WTF_FEATURE && ENABLE_##WTF_FEATURE) // There is an assumption in the project that either OS_WIN or OS_POSIX is set. #if !defined(OS_WIN) && !defined(OS_POSIX)
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.cpp b/third_party/WebKit/Source/web/ChromeClientImpl.cpp index b9ffc49..1ae58e0 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.cpp +++ b/third_party/WebKit/Source/web/ChromeClientImpl.cpp
@@ -1069,22 +1069,6 @@ web_view_->DidUpdateBrowserControls(); } -CompositorWorkerProxyClient* -ChromeClientImpl::CreateCompositorWorkerProxyClient(LocalFrame* frame) { - WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame); - return web_frame->LocalRoot() - ->FrameWidget() - ->CreateCompositorWorkerProxyClient(); -} - -AnimationWorkletProxyClient* -ChromeClientImpl::CreateAnimationWorkletProxyClient(LocalFrame* frame) { - WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(frame); - return web_frame->LocalRoot() - ->FrameWidget() - ->CreateAnimationWorkletProxyClient(); -} - void ChromeClientImpl::RegisterPopupOpeningObserver( PopupOpeningObserver* observer) { DCHECK(observer);
diff --git a/third_party/WebKit/Source/web/ChromeClientImpl.h b/third_party/WebKit/Source/web/ChromeClientImpl.h index 450f1108..a769456 100644 --- a/third_party/WebKit/Source/web/ChromeClientImpl.h +++ b/third_party/WebKit/Source/web/ChromeClientImpl.h
@@ -210,11 +210,6 @@ void OnMouseDown(Node&) override; void DidUpdateBrowserControls() const override; - CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient( - LocalFrame*) override; - AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient( - LocalFrame*) override; - FloatSize ElasticOverscroll() const override; void DidObserveNonGetFetchFromScript() const override;
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp index 347146b..b534d49 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp +++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp
@@ -62,8 +62,6 @@ #include "core/page/Page.h" #include "core/page/PointerLockController.h" #include "core/page/ValidationMessageClient.h" -#include "modules/compositorworker/AnimationWorkletProxyClientImpl.h" -#include "modules/compositorworker/CompositorWorkerProxyClientImpl.h" #include "platform/KeyboardCodes.h" #include "platform/WebFrameScheduler.h" #include "platform/animation/CompositorAnimationHost.h" @@ -484,6 +482,10 @@ } CompositorMutatorImpl& WebFrameWidgetImpl::Mutator() { + return *CompositorMutator(); +} + +CompositorMutatorImpl* WebFrameWidgetImpl::CompositorMutator() { if (!mutator_) { std::unique_ptr<CompositorMutatorClient> mutator_client = CompositorMutatorImpl::CreateClient(); @@ -491,17 +493,7 @@ layer_tree_view_->SetMutatorClient(std::move(mutator_client)); } - return *mutator_; -} - -CompositorWorkerProxyClient* -WebFrameWidgetImpl::CreateCompositorWorkerProxyClient() { - return new CompositorWorkerProxyClientImpl(&Mutator()); -} - -AnimationWorkletProxyClient* -WebFrameWidgetImpl::CreateAnimationWorkletProxyClient() { - return new AnimationWorkletProxyClientImpl(&Mutator()); + return mutator_; } void WebFrameWidgetImpl::ApplyViewportDeltas(
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h index a3290d9..28b545c 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.h +++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.h
@@ -125,12 +125,11 @@ Element* FocusedElement() const; PaintLayerCompositor* Compositor() const; + CompositorMutatorImpl* CompositorMutator() override; // WebFrameWidgetBase overrides: bool ForSubframe() const override { return true; } void ScheduleAnimation() override; - CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient() override; - AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient() override; WebWidgetClient* Client() const override { return client_; } void SetRootGraphicsLayer(GraphicsLayer*) override;
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp index a1a52cb..14c2d52 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.cpp
@@ -2525,4 +2525,8 @@ spell_check_panel_host_client_ = spell_check_panel_host_client; } +WebFrameWidgetBase* WebLocalFrameImpl::LocalRootFrameWidget() { + return LocalRoot()->FrameWidget(); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/web/WebLocalFrameImpl.h b/third_party/WebKit/Source/web/WebLocalFrameImpl.h index 97bcc35..b1e67a0 100644 --- a/third_party/WebKit/Source/web/WebLocalFrameImpl.h +++ b/third_party/WebKit/Source/web/WebLocalFrameImpl.h
@@ -449,6 +449,8 @@ const WebURLRequest&, base::SingleThreadTaskRunner*) override; + WebFrameWidgetBase* LocalRootFrameWidget() override; + DECLARE_VIRTUAL_TRACE(); private:
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index ab712080..ec1f1ed 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -103,8 +103,6 @@ #include "core/paint/PaintLayer.h" #include "core/timing/DOMWindowPerformance.h" #include "core/timing/Performance.h" -#include "modules/compositorworker/AnimationWorkletProxyClientImpl.h" -#include "modules/compositorworker/CompositorWorkerProxyClientImpl.h" #include "modules/credentialmanager/CredentialManagerClient.h" #include "modules/encryptedmedia/MediaKeysController.h" #include "modules/quota/StorageQuotaClient.h" @@ -4097,6 +4095,10 @@ } CompositorMutatorImpl& WebViewImpl::Mutator() { + return *CompositorMutator(); +} + +CompositorMutatorImpl* WebViewImpl::CompositorMutator() { if (!mutator_) { std::unique_ptr<CompositorMutatorClient> mutator_client = CompositorMutatorImpl::CreateClient(); @@ -4104,15 +4106,7 @@ layer_tree_view_->SetMutatorClient(std::move(mutator_client)); } - return *mutator_; -} - -CompositorWorkerProxyClient* WebViewImpl::CreateCompositorWorkerProxyClient() { - return new CompositorWorkerProxyClientImpl(&Mutator()); -} - -AnimationWorkletProxyClient* WebViewImpl::CreateAnimationWorkletProxyClient() { - return new AnimationWorkletProxyClientImpl(&Mutator()); + return mutator_; } void WebViewImpl::UpdatePageOverlays() {
diff --git a/third_party/WebKit/Source/web/WebViewImpl.h b/third_party/WebKit/Source/web/WebViewImpl.h index 6d82359..68fc818 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.h +++ b/third_party/WebKit/Source/web/WebViewImpl.h
@@ -467,9 +467,6 @@ void ForceNextWebGLContextCreationToFail() override; void ForceNextDrawingBufferCreationToFail() override; - CompositorWorkerProxyClient* CreateCompositorWorkerProxyClient() override; - AnimationWorkletProxyClient* CreateAnimationWorkletProxyClient() override; - IntSize MainFrameSize() override; WebDisplayMode DisplayMode() const override { return display_mode_; } @@ -588,6 +585,7 @@ LocalFrame* FocusedLocalFrameAvailableForIme() const; CompositorMutatorImpl& Mutator(); + CompositorMutatorImpl* CompositorMutator() override; WebViewClient* client_; // Can be 0 (e.g. unittests, shared workers, etc.)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/common.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/common.py index ec2af486..1ed2f66b 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/common.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/common.py
@@ -94,11 +94,7 @@ # If there's a corresponding closed PR, then this commit should not # be considered exportable; the PR might have been merged and reverted, # or it might have been closed manually without merging. - pull_request = wpt_github.pr_with_change_id(chromium_commit.change_id()) - if not pull_request: - # The Change ID can't be used for commits made via Rietveld. - # TODO(qyearsley): Remove this fallback after Gerrit migration. - pull_request = wpt_github.pr_with_position(chromium_commit.position) + pull_request = wpt_github.pr_for_chromium_commit(chromium_commit) if pull_request and pull_request.state == 'closed': return False return True
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_exporter_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_exporter_unittest.py index c0b2ce58..04bcc5a64 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_exporter_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_exporter_unittest.py
@@ -78,12 +78,9 @@ self.assertEqual(test_exporter.wpt_github.calls, [ 'pr_with_change_id', - 'pr_with_position', 'pr_with_change_id', - 'pr_with_position', 'pr_with_change_id', 'pr_with_position', - 'pr_with_position', 'pr_with_change_id', 'create_pr', 'add_label "default"',
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py index 1b038fa..e5edf8f 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py
@@ -83,7 +83,7 @@ for commit in commits: _log.info('Commit: %s', commit.url()) _log.info('Subject: %s', commit.subject().strip()) - pull_request = self.wpt_github.pr_with_position(commit.position) + pull_request = self.wpt_github.pr_for_chromium_commit(commit) if pull_request: _log.info('PR: https://github.com/w3c/web-platform-tests/pull/%d', pull_request.number) else: @@ -360,7 +360,7 @@ if try_results and all(s == TryJobStatus('COMPLETED', 'SUCCESS') for _, s in try_results.iteritems()): _log.info('CQ appears to have passed; trying to commit.') - self.git_cl.run(['upload', '--send-mail']) # Turn off WIP mode. + self.git_cl.run(['upload', '-f', '--send-mail']) # Turn off WIP mode. self.git_cl.run(['set-commit']) _log.info('Update completed.') return True
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py index 30112c599..b93a31e9a 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer_unittest.py
@@ -17,11 +17,11 @@ def test_abort_on_exportable_commits_pr_found(self): host = MockHost() wpt_github = MockWPTGitHub(pull_requests=[ - PullRequest('Title', 5, 'Commit body\nCr-Commit-Position: refs/heads/master@{#431}', 'open'), + PullRequest('Title', 5, 'Commit body\nChange-Id: Iba5eba11', 'open'), ]) importer = TestImporter(host, wpt_github=wpt_github) importer.exportable_but_not_exported_commits = lambda _: [ - MockChromiumCommit(host, position='refs/heads/master@{#431}') + MockChromiumCommit(host, change_id='Iba5eba11') ] importer.checkout_is_okay = lambda _: True return_code = importer.main([]) @@ -30,7 +30,7 @@ 'INFO: Cloning repo: https://chromium.googlesource.com/external/w3c/web-platform-tests.git\n', 'INFO: Local path: /mock-checkout/third_party/WebKit/LayoutTests/wpt\n', 'INFO: There were exportable but not-yet-exported commits:\n', - 'INFO: Commit: https://fake-chromium-commit-viewer.org/+/fa2de685c0\n', + 'INFO: Commit: https://fake-chromium-commit-viewer.org/+/14fd77e88e\n', 'INFO: Subject: Fake commit message\n', 'INFO: PR: https://github.com/w3c/web-platform-tests/pull/5\n', 'INFO: Modified files in wpt directory in this commit:\n',
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github.py index a562dbc..963d03f 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github.py
@@ -6,10 +6,10 @@ import json import logging import urllib2 - from collections import namedtuple -from webkitpy.w3c.common import WPT_GH_ORG, WPT_GH_REPO_NAME + from webkitpy.common.memoized import memoized +from webkitpy.w3c.common import WPT_GH_ORG, WPT_GH_REPO_NAME _log = logging.getLogger(__name__) API_BASE = 'https://api.github.com' @@ -212,6 +212,17 @@ return data + def pr_for_chromium_commit(self, chromium_commit): + """Returns a PR corresponding to the given ChromiumCommit, or None.""" + pull_request = self.pr_with_change_id(chromium_commit.change_id()) + if pull_request: + return pull_request + # The Change ID can't be used for commits made via Rietveld, + # so we fall back to trying to use commit position here, although + # commit position is not correct sometimes (https://crbug.com/737178). + # TODO(qyearsley): Remove this fallback after full Gerrit migration. + pull_request = self.pr_with_position(chromium_commit.position) + def pr_with_change_id(self, target_change_id): for pull_request in self.all_pull_requests(): change_id = self.extract_metadata('Change-Id: ', pull_request.body)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github_mock.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github_mock.py index 951233c..babde44f 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github_mock.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_github_mock.py
@@ -58,6 +58,9 @@ self.calls.append('get_pr_branch') return 'fake branch for PR {}'.format(number) + def pr_for_chromium_commit(self, commit): + return self.pr_with_change_id(commit.change_id()) + def pr_with_position(self, position): self.calls.append('pr_with_position') for pr in self.pull_requests:
diff --git a/third_party/WebKit/public/blink_resources.grd b/third_party/WebKit/public/blink_resources.grd index f975805..d39139b 100644 --- a/third_party/WebKit/public/blink_resources.grd +++ b/third_party/WebKit/public/blink_resources.grd
@@ -33,6 +33,8 @@ <include name="IDR_INSPECTOR_OVERLAY_PAGE_HTML" file="../Source/core/inspector/InspectorOverlayPage.html" type="BINDATA" compress="gzip"/> <include name="IDR_DOCUMENTXMLTREEVIEWER_CSS" file="../Source/core/xml/DocumentXMLTreeViewer.css" type="BINDATA" compress="gzip"/> <include name="IDR_DOCUMENTXMLTREEVIEWER_JS" file="../Source/core/xml/DocumentXMLTreeViewer.js" type="BINDATA" compress="gzip"/> + <include name="IDR_VALIDATION_BUBBLE_ICON" file="../Source/core/html/forms/resources/input_alert.svg" type="BINDATA" compress="gzip"/> + <include name="IDR_VALIDATION_BUBBLE_CSS" file="../Source/core/html/forms/resources/validation_bubble.css" type="BINDATA" compress="gzip"/> <if expr="not is_android"> <include name="IDR_PICKER_COMMON_JS" file="../Source/core/html/forms/resources/pickerCommon.js" type="BINDATA" compress="gzip"/> <include name="IDR_PICKER_COMMON_CSS" file="../Source/core/html/forms/resources/pickerCommon.css" type="BINDATA" compress="gzip"/>
diff --git a/third_party/WebKit/public/platform/OWNERS b/third_party/WebKit/public/platform/OWNERS index c9f498f3..cabca80 100644 --- a/third_party/WebKit/public/platform/OWNERS +++ b/third_party/WebKit/public/platform/OWNERS
@@ -1,5 +1,10 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS + +# Extending enum WebFeature by adding new features is allowed without OWNERS +# review, but you should add a security team OWNER if you are changing others. +per-file web_feature.mojom=file://third_party/WebKit/Source/core/OWNERS + per-file *EnumTraits*.*=set noparent per-file *EnumTraits*.*=file://ipc/SECURITY_OWNERS per-file *StructTraits*.*=set noparent
diff --git a/third_party/WebKit/public/platform/WebContentSettingsClient.h b/third_party/WebKit/public/platform/WebContentSettingsClient.h index e2b2fcb..8732052 100644 --- a/third_party/WebKit/public/platform/WebContentSettingsClient.h +++ b/third_party/WebKit/public/platform/WebContentSettingsClient.h
@@ -44,11 +44,6 @@ return true; } - // Controls whether plugins are allowed for this frame. - virtual bool AllowPlugins(bool enabled_per_settings) { - return enabled_per_settings; - } - // Controls whether scripts are allowed to execute for this frame. virtual bool AllowScript(bool enabled_per_settings) { return enabled_per_settings;
diff --git a/third_party/WebKit/public/platform/WebMediaStreamSource.h b/third_party/WebKit/public/platform/WebMediaStreamSource.h index d888c3d..c4f1e79 100644 --- a/third_party/WebKit/public/platform/WebMediaStreamSource.h +++ b/third_party/WebKit/public/platform/WebMediaStreamSource.h
@@ -111,6 +111,8 @@ BLINK_PLATFORM_EXPORT ExtraData* GetExtraData() const; BLINK_PLATFORM_EXPORT void SetExtraData(ExtraData*); + BLINK_PLATFORM_EXPORT void SetEchoCancellation(bool echo_cancellation); + BLINK_PLATFORM_EXPORT WebMediaConstraints Constraints(); // Only used if if this is a WebAudio source.
diff --git a/third_party/WebKit/public/platform/WebMediaStreamTrack.h b/third_party/WebKit/public/platform/WebMediaStreamTrack.h index 0921b7d4..f493d853 100644 --- a/third_party/WebKit/public/platform/WebMediaStreamTrack.h +++ b/third_party/WebKit/public/platform/WebMediaStreamTrack.h
@@ -49,6 +49,7 @@ bool HasHeight() const { return height >= 0; } bool HasAspectRatio() const { return aspect_ratio >= 0.0; } bool HasFacingMode() const { return facing_mode != FacingMode::kNone; } + bool HasEchoCancellationValue() const { return echo_cancellation >= 0; } bool HasVideoKind() const { return !video_kind.IsNull(); } bool HasFocalLengthX() const { return focal_length_x >= 0.0; } bool HasFocalLengthY() const { return focal_length_y >= 0.0; } @@ -62,6 +63,9 @@ double aspect_ratio = -1.0; WebString device_id; FacingMode facing_mode = FacingMode::kNone; + // |echo_cancellation| should be some form of Optional<bool> instead of int, + // but none is available for this file. Using -1 to indicate no value. + int echo_cancellation = -1; // Media Capture Depth Stream Extensions. WebString video_kind; double focal_length_x = -1.0;
diff --git a/third_party/WebKit/public/platform/WebRuntimeFeatures.h b/third_party/WebKit/public/platform/WebRuntimeFeatures.h index 1e2cc6d..1f73ba74 100644 --- a/third_party/WebKit/public/platform/WebRuntimeFeatures.h +++ b/third_party/WebKit/public/platform/WebRuntimeFeatures.h
@@ -118,6 +118,7 @@ BLINK_PLATFORM_EXPORT static void EnableScriptedSpeech(bool); BLINK_PLATFORM_EXPORT static void EnableScrollAnchoring(bool); BLINK_PLATFORM_EXPORT static void EnableServiceWorkerNavigationPreload(bool); + BLINK_PLATFORM_EXPORT static void EnableServiceWorkerScriptStreaming(bool); BLINK_PLATFORM_EXPORT static void EnableSharedArrayBuffer(bool); BLINK_PLATFORM_EXPORT static void EnableSharedWorker(bool); BLINK_PLATFORM_EXPORT static void EnableSkipCompositingSmallScrollers(bool);
diff --git a/third_party/WebKit/public/platform/web_feature.mojom b/third_party/WebKit/public/platform/web_feature.mojom index 11670fa..84a933a 100644 --- a/third_party/WebKit/public/platform/web_feature.mojom +++ b/third_party/WebKit/public/platform/web_feature.mojom
@@ -549,7 +549,7 @@ kV8XPathEvaluator_CreateExpression_Method = 854, kV8XPathEvaluator_CreateNSResolver_Method = 855, kV8XPathEvaluator_Evaluate_Method = 856, - kRequestMIDIAccess = 857, + kRequestMIDIAccess_ObscuredByFootprinting = 857, kV8MouseEvent_LayerX_AttributeGetter = 858, kV8MouseEvent_LayerY_AttributeGetter = 859, kInnerTextWithShadowTree = 860, @@ -804,7 +804,7 @@ kEventComposed = 1140, kGeolocationInsecureOriginIframe = 1141, kGeolocationSecureOriginIframe = 1142, - kRequestMIDIAccessIframe = 1143, + kRequestMIDIAccessIframe_ObscuredByFootprinting = 1143, kGetUserMediaInsecureOriginIframe = 1144, kGetUserMediaSecureOriginIframe = 1145, kElementRequestPointerLockIframe = 1146, @@ -1497,8 +1497,8 @@ // The above items are available in M59 branch. kViewportFixedPositionUnderFilter = 1961, - kRequestMIDIAccessWithSysExOption = 1962, - kRequestMIDIAccessIframeWithSysExOption = 1963, + kRequestMIDIAccessWithSysExOption_ObscuredByFootprinting = 1962, + kRequestMIDIAccessIframeWithSysExOption_ObscuredByFootprinting = 1963, kGamepadAxes = 1964, kGamepadButtons = 1965, kVibrateWithoutUserGesture = 1966, @@ -1586,6 +1586,7 @@ kCSSSelectorWebkitMediaControlsVolumeSlider = 2048, kCSSSelectorWebkitMediaControlsFullscreenButton = 2049, kCSSSelectorWebkitMediaControlsToggleClosedCaptionsButton = 2050, + kLinearAccelerationSensorConstructor = 2051, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/flatbuffers/BUILD.gn b/third_party/flatbuffers/BUILD.gn index a1554f2..5ce0786 100644 --- a/third_party/flatbuffers/BUILD.gn +++ b/third_party/flatbuffers/BUILD.gn
@@ -7,6 +7,10 @@ config("flatbuffers_config") { include_dirs = [ "src/include" ] + + if (is_clang) { + cflags = [ "-Wno-exit-time-destructors" ] + } } # The part of FlatBuffers that Chrome is interested in.
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index f8fda05..8b6c8a6 100644 --- a/third_party/freetype/README.chromium +++ b/third_party/freetype/README.chromium
@@ -1,7 +1,7 @@ Name: FreeType URL: http://www.freetype.org/ -Version: VER-2-8-58 -Revision: 7819aeb622a94be0d89caf8382f290d0266c4aed +Version: VER-2-8-61 +Revision: c56d8851ea987023cc73981a70d261b3f6427545 License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses" License File: src/docs/FTL.TXT
diff --git a/third_party/freetype/roll-freetype.sh b/third_party/freetype/roll-freetype.sh index 10e775f..709b6441 100755 --- a/third_party/freetype/roll-freetype.sh +++ b/third_party/freetype/roll-freetype.sh
@@ -1,7 +1,7 @@ #!/bin/bash REVIEWERS=`paste -s -d, third_party/freetype/OWNERS` && -roll-dep -r ${REVIEWERS} src/third_party/freetype/src/ && +roll-dep -r "${REVIEWERS}" "$@" src/third_party/freetype/src/ && TMPFILE=`mktemp` && git -C third_party/freetype/src/ cat-file blob HEAD@{1}:include/freetype/config/ftoption.h >> ${TMPFILE} &&
diff --git a/third_party/leveldatabase/env_chromium.cc b/third_party/leveldatabase/env_chromium.cc index 928d4be..7a0f4ad0 100644 --- a/third_party/leveldatabase/env_chromium.cc +++ b/third_party/leveldatabase/env_chromium.cc
@@ -11,6 +11,7 @@ #include <sys/types.h> #endif +#include "base/bind.h" #include "base/files/file_enumerator.h" #include "base/files/file_util.h" #include "base/format_macros.h" @@ -1192,7 +1193,9 @@ public: bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args, base::trace_event::ProcessMemoryDump* pmd) override { - auto db_visitor = [&](TrackedDB* db) { + auto db_visitor = [](const base::trace_event::MemoryDumpArgs& args, + base::trace_event::ProcessMemoryDump* pmd, + TrackedDB* db) { std::string db_dump_name = base::StringPrintf( "leveldatabase/0x%" PRIXPTR, reinterpret_cast<uintptr_t>(db)); auto* db_dump = pmd->CreateAllocatorDump(db_dump_name.c_str()); @@ -1222,7 +1225,8 @@ } }; - DBTracker::GetInstance()->VisitDatabases(db_visitor); + DBTracker::GetInstance()->VisitDatabases( + base::BindRepeating(db_visitor, args, base::Unretained(pmd))); return true; } }; @@ -1256,7 +1260,7 @@ void DBTracker::VisitDatabases(const DatabaseVisitor& visitor) { base::AutoLock lock(databases_lock_); for (auto* i = databases_.head(); i != databases_.end(); i = i->next()) { - visitor(i->value()); + visitor.Run(i->value()); } }
diff --git a/third_party/leveldatabase/env_chromium.h b/third_party/leveldatabase/env_chromium.h index adc9c25..690a032a 100644 --- a/third_party/leveldatabase/env_chromium.h +++ b/third_party/leveldatabase/env_chromium.h
@@ -6,12 +6,12 @@ #define THIRD_PARTY_LEVELDATABASE_ENV_CHROMIUM_H_ #include <deque> -#include <functional> #include <memory> #include <set> #include <string> #include <vector> +#include "base/callback.h" #include "base/containers/linked_list.h" #include "base/files/file.h" #include "base/files/file_path.h" @@ -256,7 +256,7 @@ const std::string& name, TrackedDB** dbptr); - using DatabaseVisitor = std::function<void(TrackedDB*)>; + using DatabaseVisitor = base::RepeatingCallback<void(TrackedDB*)>; // Calls |visitor| for each live database. The database is live from the // point it was returned from OpenDatabase() and up until its instance is
diff --git a/third_party/leveldatabase/env_chromium_unittest.cc b/third_party/leveldatabase/env_chromium_unittest.cc index b113ad0a..12bad1e4 100644 --- a/third_party/leveldatabase/env_chromium_unittest.cc +++ b/third_party/leveldatabase/env_chromium_unittest.cc
@@ -5,6 +5,7 @@ #include <set> #include <vector> +#include "base/bind.h" #include "base/files/file.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" @@ -209,11 +210,12 @@ static VisitedDBSet VisitDatabases() { VisitedDBSet visited; - auto db_visitor = [&](DBTracker::TrackedDB* db) { - ASSERT_TRUE(visited.insert(db).second) + auto db_visitor = [](VisitedDBSet* visited, DBTracker::TrackedDB* db) { + ASSERT_TRUE(visited->insert(db).second) << "Database " << std::hex << db << " visited for the second time"; }; - DBTracker::GetInstance()->VisitDatabases(db_visitor); + DBTracker::GetInstance()->VisitDatabases( + base::BindRepeating(db_visitor, base::Unretained(&visited))); return visited; }
diff --git a/tools/android/eclipse/.classpath b/tools/android/eclipse/.classpath index 5c657c0d..06196be 100644 --- a/tools/android/eclipse/.classpath +++ b/tools/android/eclipse/.classpath
@@ -311,6 +311,7 @@ <classpathentry kind="lib" path="out/Debug/lib.java/third_party/android_support_test_runner/rules_java.jar"/> <classpathentry kind="lib" path="out/Debug/lib.java/third_party/WebKit/public/blink_headers_java.jar"/> <classpathentry kind="lib" path="out/Debug/lib.java/ui/accessibility/ui_accessibility_java.jar"/> + <classpathentry kind="lib" path="out/Debug/lib.java/ui/android/ui_full_java.interface.jar"/> <classpathentry kind="lib" path="out/Debug/lib.java/ui/android/ui_java.jar"/> <classpathentry kind="lib" path="out/Debug/lib.java/ui/base/mojo/mojo_bindings_java.jar"/>
diff --git a/tools/gn/builder.cc b/tools/gn/builder.cc index bfae69f6..540d83d6 100644 --- a/tools/gn/builder.cc +++ b/tools/gn/builder.cc
@@ -397,7 +397,7 @@ if (action_values.pool().label.is_null()) return true; - BuilderRecord* pool_record = GetResolvedRecordOfType( + BuilderRecord* pool_record = GetOrCreateRecordOfType( action_values.pool().label, action_values.pool().origin, BuilderRecord::ITEM_POOL, err); if (!pool_record)
diff --git a/tools/gn/docs/reference.md b/tools/gn/docs/reference.md index de924a7..cdc4ca4 100644 --- a/tools/gn/docs/reference.md +++ b/tools/gn/docs/reference.md
@@ -97,7 +97,6 @@ * [code_signing_sources: [file list] Sources for code signing step.](#code_signing_sources) * [complete_static_lib: [boolean] Links all deps into a static library.](#complete_static_lib) * [configs: [label list] Configs applying to this target or config.](#configs) - * [console: [label] Console pool object.](#console) * [data: [file list] Runtime data file dependencies.](#data) * [data_deps: [label list] Non-linked dependencies.](#data_deps) * [defines: [string list] C preprocessor defines.](#defines) @@ -1041,7 +1040,7 @@ #### **Variables** ``` - args, console, data, data_deps, depfile, deps, inputs, outputs*, + args, data, data_deps, depfile, deps, inputs, outputs*, pool, response_file_contents, script*, sources * = required ``` @@ -1119,7 +1118,7 @@ #### **Variables** ``` - args, console, data, data_deps, depfile, deps, inputs, outputs*, + args, data, data_deps, depfile, deps, inputs, outputs*, pool, response_file_contents, script*, sources* * = required ``` @@ -2146,7 +2145,9 @@ variable_to_ignore_list = []) Mark the variables in the current or given scope as not needed, which means - you will not get an error about unused variables for these. + you will not get an error about unused variables for these. The + variable_to_ignore_list allows excluding variables from "all matches" if + variable_list_or_star is "*". ``` #### **Example** @@ -4327,27 +4328,6 @@ } } ``` -### <a name="console"></a>**console**: Console pool objects. - -``` - Console pool is a special pool object that uses the built-in ninja "console" - pool. Target using this pool will have access to real stdin and stdout, and - output will not be buffered by ninja. This can be useful for long-running - actions with progress logs, or actions that require user input. - - Only one console pool target can run at any one time in Ninja. Refer to the - Ninja documentation on the console pool for more info. -``` - -#### **Example** - -``` - action("my_action") { - ... - pool = console - ... - } -``` ### <a name="data"></a>**data**: Runtime data file dependencies. ```
diff --git a/tools/gn/functions_target.cc b/tools/gn/functions_target.cc index fa97c86..903ab38 100644 --- a/tools/gn/functions_target.cc +++ b/tools/gn/functions_target.cc
@@ -136,7 +136,7 @@ R"( Variables - args, console, data, data_deps, depfile, deps, inputs, outputs*, + args, data, data_deps, depfile, deps, inputs, outputs*, pool, response_file_contents, script*, sources * = required @@ -209,7 +209,7 @@ R"( Variables - args, console, data, data_deps, depfile, deps, inputs, outputs*, + args, data, data_deps, depfile, deps, inputs, outputs*, pool, response_file_contents, script*, sources* * = required
diff --git a/tools/gn/ninja_action_target_writer_unittest.cc b/tools/gn/ninja_action_target_writer_unittest.cc index e24fb0d..3c4c05d 100644 --- a/tools/gn/ninja_action_target_writer_unittest.cc +++ b/tools/gn/ninja_action_target_writer_unittest.cc
@@ -75,8 +75,8 @@ } -// Tests an action with no sources and console = true -TEST(NinjaActionTargetWriter, ActionNoSourcesConsole) { +// Tests an action with no sources and pool +TEST(NinjaActionTargetWriter, ActionNoSourcesPool) { Err err; TestWithScope setup; @@ -89,8 +89,11 @@ target.action_values().outputs() = SubstitutionList::MakeForTest("//out/Debug/foo.out"); - Pool pool(setup.settings(), Label(SourceDir("//foo/"), "pool"), {}); - pool.set_console(true); + Pool pool(setup.settings(), + Label(SourceDir("//foo/"), "pool", setup.toolchain()->label().dir(), + setup.toolchain()->label().name()), + {}); + pool.set_depth(5); target.action_values().set_pool(LabelPtrPair<Pool>(&pool)); target.SetToolchain(setup.toolchain()); @@ -112,7 +115,7 @@ "../../foo/included.txt\n" "\n" "build foo.out: __foo_bar___rule | obj/foo/bar.inputdeps.stamp\n" - " pool = console\n" + " pool = foo_pool\n" "\n" "build obj/foo/bar.stamp: stamp foo.out\n"; EXPECT_EQ(expected, out.str());
diff --git a/tools/gn/pool.cc b/tools/gn/pool.cc index b1bb4904..75a7504 100644 --- a/tools/gn/pool.cc +++ b/tools/gn/pool.cc
@@ -25,9 +25,6 @@ } std::string Pool::GetNinjaName(bool include_toolchain) const { - if (console_) - return "console"; - std::ostringstream buffer; if (include_toolchain) { DCHECK(label().toolchain_dir().is_source_absolute());
diff --git a/tools/gn/pool.h b/tools/gn/pool.h index 08da33c..81a021d 100644 --- a/tools/gn/pool.h +++ b/tools/gn/pool.h
@@ -29,10 +29,6 @@ int64_t depth() const { return depth_; } void set_depth(int64_t depth) { depth_ = depth; } - // Console pool option - bool is_console() const { return console_; } - void set_console(bool value) { console_ = value; } - // The pool name in generated ninja files. std::string GetNinjaName(const Label& default_toolchain) const; @@ -40,7 +36,6 @@ std::string GetNinjaName(bool include_toolchain) const; int64_t depth_ = 0; - bool console_ = false; }; #endif // TOOLS_GN_POOL_H_
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index df9d421..8b3cc67 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -14440,7 +14440,7 @@ <int value="854" label="V8XPathEvaluator_CreateExpression_Method"/> <int value="855" label="V8XPathEvaluator_CreateNSResolver_Method"/> <int value="856" label="V8XPathEvaluator_Evaluate_Method"/> - <int value="857" label="RequestMIDIAccess"/> + <int value="857" label="RequestMIDIAccess_ObscuredByFootprinting"/> <int value="858" label="V8MouseEvent_LayerX_AttributeGetter"/> <int value="859" label="V8MouseEvent_LayerY_AttributeGetter"/> <int value="860" label="InnerTextWithShadowTree"/> @@ -14737,7 +14737,7 @@ <int value="1140" label="EventComposed"/> <int value="1141" label="GeolocationInsecureOriginIframe"/> <int value="1142" label="GeolocationSecureOriginIframe"/> - <int value="1143" label="RequestMIDIAccessIframe"/> + <int value="1143" label="RequestMIDIAccessIframe_ObscuredByFootprinting"/> <int value="1144" label="GetUserMediaInsecureOriginIframe"/> <int value="1145" label="GetUserMediaSecureOriginIframe"/> <int value="1146" label="ElementRequestPointerLockIframe"/> @@ -15577,8 +15577,10 @@ <int value="1959" label="MediaStreamConstraintsGoogNoiseReduction"/> <int value="1960" label="MediaStreamConstraintsGoogPowerLineFrequency"/> <int value="1961" label="ViewportFixedPositionUnderFilter"/> - <int value="1962" label="RequestMIDIAccessWithSysExOption"/> - <int value="1963" label="RequestMIDIAccessIframeWithSysExOption"/> + <int value="1962" + label="RequestMIDIAccessWithSysExOption_ObscuredByFootprinting"/> + <int value="1963" + label="RequestMIDIAccessIframeWithSysExOption_ObscuredByFootprinting"/> <int value="1964" label="GamepadAxes"/> <int value="1965" label="GamepadButtons"/> <int value="1966" label="VibrateWithoutUserGesture"/> @@ -15670,6 +15672,7 @@ <int value="2049" label="CSSSelectorWebkitMediaControlsFullscreenButton"/> <int value="2050" label="CSSSelectorWebkitMediaControlsToggleClosedCaptionsButton"/> + <int value="2051" label="LinearAccelerationSensorConstructor"/> </enum> <enum name="FeedbackSource"> @@ -20410,6 +20413,32 @@ <int value="1" label="identical"/> </enum> +<enum name="InstantTethering_ConnectionToHostResult_Failure"> + <int value="0" label="Unknown error"/> + <int value="1" label="Tethering timed out"/> + <int value="2" label="Client connection error"/> +</enum> + +<enum name="InstantTethering_ConnectionToHostResult_Failure_ClientConnection"> + <int value="0" label="Timeout while waiting to connect"/> + <int value="1" label="Canceled by a new connection attempt"/> +</enum> + +<enum name="InstantTethering_ConnectionToHostResult_Failure_TetheringTimeout"> + <int value="0" label="First-time setup was required"/> + <int value="1" label="First-time setup was not required"/> +</enum> + +<enum name="InstantTethering_ConnectionToHostResult_ProvisioningFailureRate"> + <int value="0" label="Provisioning failed"/> + <int value="1" label="Other"/> +</enum> + +<enum name="InstantTethering_ConnectionToHostResult_SuccessRate"> + <int value="0" label="Success"/> + <int value="1" label="Failure"/> +</enum> + <enum name="IntelMaxMicroArchitecture"> <int value="0" label="Pentium"/> <int value="1" label="SSE"/> @@ -22568,6 +22597,7 @@ <int value="-879031960" label="FetchKeepaliveTimeoutSetting:disabled"/> <int value="-876148583" label="ArcBootCompletedBroadcast:disabled"/> <int value="-867087281" label="enable-virtual-keyboard"/> + <int value="-866993841" label="OfflinePagesCTV2:disabled"/> <int value="-864266073" label="cros-regions-mode"/> <int value="-864205629" label="enable-offline-load-stale-cache"/> <int value="-861678473" label="disable-offer-upload-credit-cards"/> @@ -23048,6 +23078,8 @@ <int value="900614020" label="ContentSuggestionsShowSummary:disabled"/> <int value="902608487" label="AutofillUpstreamRequestCvcIfMissing:enabled"/> <int value="903267263" label="disable-offline-pages"/> + <int value="908302031" + label="OmniboxUIExperimentElideSuggestionUrlAfterHost:enabled"/> <int value="908523940" label="PassiveEventListenersDueToFling:disabled"/> <int value="909439558" label="disable-device-discovery"/> <int value="916316159" label="disable-new-app-list-mixer"/> @@ -23249,6 +23281,8 @@ <int value="1511140997" label="OfflinePagesAsyncDownload:disabled"/> <int value="1511161758" label="BackgroundLoader:enabled"/> <int value="1512249489" label="ModuleScripts:disabled"/> + <int value="1514036945" + label="OmniboxUIExperimentElideSuggestionUrlAfterHost:disabled"/> <int value="1515196403" label="fast-user-switching"/> <int value="1517863401" label="history-entry-requires-user-gesture"/> <int value="1533111748" label="Multidevice:enabled"/> @@ -23331,6 +23365,7 @@ <int value="1839740266" label="LocationHardReload:disabled"/> <int value="1844110073" label="enable-app-view"/> <int value="1847024354" label="enable-hotword-hardware"/> + <int value="1849379463" label="OfflinePagesCTV2:enabled"/> <int value="1852630189" label="NTPBookmarkSuggestions:disabled"/> <int value="1855524566" label="allow-insecure-websocket-from-https-origin"/> <int value="1860597983" label="AndroidSpellChecker:disabled"/> @@ -31661,6 +31696,42 @@ <int value="88" label="IDC_CONTENT_CONTEXT_EXIT_FULLSCREEN"/> </enum> +<enum name="ReportingHeaderEndpointOutcome"> + <int value="0" label="Discarded: not a dictionary"/> + <int value="1" label="Discarded: endpoint missing"/> + <int value="2" label="Discarded: endpoint not a string"/> + <int value="3" label="Discarded: endpoint URL invalid"/> + <int value="4" label="Discarded: endpoint URL insecure"/> + <int value="5" label="Discarded: TTL missing"/> + <int value="6" label="Discarded: TTL not an integer"/> + <int value="7" label="Discarded: TTL negative"/> + <int value="8" label="Discarded: group not a string"/> + <int value="9" label="Removed (max-age = 0)"/> + <int value="10" label="Set rejected by delegate (max-age > 0)"/> + <int value="11" label="Set (max-age > 0)"/> +</enum> + +<enum name="ReportingHeaderOutcome"> + <int value="0" label="Discarded: no ReportingService"/> + <int value="1" label="Discarded: invalid SSLInfo"/> + <int value="2" label="Discarded: cert status error"/> + <int value="3" label="Discarded: invalid JSON"/> + <int value="4" label="Parsed"/> +</enum> + +<enum name="ReportingReportOutcome"> + <int value="0" label="Unknown"/> + <int value="1" label="Discarded: no URLRequestContext"/> + <int value="2" label="Discarded: no ReportingService"/> + <int value="3" label="Erased: failed"/> + <int value="4" label="Erased: expired"/> + <int value="5" label="Erased: evicted"/> + <int value="6" label="Erased: network changed"/> + <int value="7" label="Erased: browsing data removed"/> + <int value="8" label="Erased: Reporting shut down"/> + <int value="9" label="Delivered"/> +</enum> + <enum name="ReportProcessingResult"> <int value="0" label="Success">A report was created and uploaded</int> <int value="1" label="Suppressed"> @@ -36736,6 +36807,7 @@ <int value="13" label="Aborted by translate ranker"/> <int value="14" label="Aborted by too often denied rule"/> <int value="15" label="Aborted by matches previous language"/> + <int value="16" label="Decision made to create infobar on Android"/> </enum> <enum name="TranslateLanguage"> @@ -37599,6 +37671,17 @@ <int value="4" label="Desktop/Tab capture stopped. No frames produced."/> </enum> +<enum name="VideoCaptureServiceEvent"> + <int value="0" label="Browser is using legacy video capture stack"/> + <int value="1" label="Browser connecting to video capture service"/> + <int value="2" label="Video capture service started"/> + <int value="3" + label="Video capture service closing because last client disconnected"/> + <int value="4" label="Video capture service lost connection to Browser"/> + <int value="5" label="Browser lost connection to video capture service"/> + <int value="6" label="Browser closing connection to video capture service"/> +</enum> + <enum name="VideoCodec"> <int value="0" label="kUnknownVideoCodec"/> <int value="1" label="kCodecH264"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 18ce1dad..50c8c16 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -1071,25 +1071,25 @@ <histogram name="Android.RecentTabsManager.OtherDevices" units="count"> <owner>huayinz@chromium.org</owner> <summary> - Records the number of other devices listed in recent tabs page - when recent tabs page is loaded. + Records the number of other devices listed in recent tabs page when recent + tabs page is loaded. </summary> </histogram> <histogram name="Android.RecentTabsManager.RecentlyClosedTabs" units="count"> <owner>huayinz@chromium.org</owner> <summary> - Records the number of recently-closed tabs shown in recent tabs page - when recent tabs page is loaded. + Records the number of recently-closed tabs shown in recent tabs page when + recent tabs page is loaded. </summary> </histogram> <histogram name="Android.RecentTabsManager.TotalTabs" units="count"> <owner>huayinz@chromium.org</owner> <summary> - Records the total number of tabs listed in recent tabs page (sum of all - tab from other devices plus recently-closed tabs) when recent tabs page - is loaded. + Records the total number of tabs listed in recent tabs page (sum of all tab + from other devices plus recently-closed tabs) when recent tabs page is + loaded. </summary> </histogram> @@ -26619,6 +26619,96 @@ </summary> </histogram> +<histogram name="InstantTethering.ConnectionToHostResult.Failure" + enum="InstantTethering_ConnectionToHostResult_Failure"> + <owner>hansberry@chromium.com</owner> + <summary> + Provides a top-level breakdown of the times a connection to a host has + failed. + + An "unknown error" is generally caused by the host returning an + "unknown error" response code. Tethering timing out and client + connection error and 3) are both broken down further in + InstantTethering.ConnectionToHostResult.Failure.TetheringTimeout and + InstantTethering.ConnectionToHostResult.Failure.ClientConnection, + respectively. + </summary> +</histogram> + +<histogram + name="InstantTethering.ConnectionToHostResult.Failure.ClientConnection" + enum="InstantTethering_ConnectionToHostResult_Failure_ClientConnection"> + <owner>hansberry@chromium.com</owner> + <summary> + Breaks down the reasons why the client failed to connect to the hotspot, and + the number of times they occurred. This histogram captures 2 reasons: 1) the + connection attempt to the hotspot timed out, or 2) any stage of the + connection attempt was canceled by a new connection attempt. + + This histogram breaks down the "client connection error" count of + InstantTethering.ConnectionToHostResult.Failure. + </summary> +</histogram> + +<histogram + name="InstantTethering.ConnectionToHostResult.Failure.TetheringTimeout" + enum="InstantTethering_ConnectionToHostResult_Failure_TetheringTimeout"> + <owner>hansberry@chromium.com</owner> + <summary> + Captures the number of times of whether or not first-time setup was required + when tethering timed out. + + Starting tethering on the host works like so: if first-time setup is + required on the host, a first-time setup UI is shown on the host; once the + user interacts with it, the provisioning app is called. If first-time setup + is not required, then the provisioning app is directly called. To be clear: + the provisioning app is always run. + + There are two possible ways for tethering to time out: either the + provisioning app flaked (crashed or hung, and never called back to Instant + Tethering), or the user never interacted with the first-time setup UI flow + (assuming first-time setup was required). + + Because it's very unlikely for the provisioning app to flake, we can read + the "was first-time setup" count as almost always indicative of + the user not interacting with the first-time setup UI. We expect the + "was not first-time setup" count to be low (because, as mentioned, + it's very unlikely for the provisioning app to flake). + + This histogram breaks down the "tethering timed out" count of + InstantTethering.ConnectionToHostResult.Failure. + </summary> +</histogram> + +<histogram + name="InstantTethering.ConnectionToHostResult.ProvisioningFailureRate" + enum="InstantTethering_ConnectionToHostResult_ProvisioningFailureRate"> + <owner>hansberry@chromium.org</owner> + <summary> + Provides a breakdown of the times a connection to a host was either + unsuccessful due to provisioning failure (the carrier disallows tethering) + or "other" (this is captured under + InstantTethering.ConnectionToHostResult.SuccessRate). + + This metric captures the rough percentage of connections which are + unsuccessful due to provisioning failure. It is separate from + InstantTethering.ConnectionToHostResult.SuccessRate and the metrics related + to it because provisioning failure is neither truly a success nor an error. + </summary> +</histogram> + +<histogram name="InstantTethering.ConnectionToHostResult.SuccessRate" + enum="InstantTethering_ConnectionToHostResult_SuccessRate"> + <owner>hansberry@chromium.com</owner> + <summary> + Captures the count of successful and failed connection attempts. + + This metric provides an immediate understanding of the Instant Tethering + connection success rate. The counts of failure are broken down in + InstantTethering.ConnectionToHostResult.Failure. + </summary> +</histogram> + <histogram name="InterProcessTimeTicks.BrowserAhead" units="ms"> <owner>ppi@chromium.org</owner> <summary> @@ -30738,6 +30828,15 @@ </summary> </histogram> +<histogram name="Media.VideoCapture.DelayUntilFirstFrame" units="ms"> + <owner>chfremer@chromium.org</owner> + <summary> + Time it takes from the moment that a VideoCaptureController is requested to + start to the moment the first video frame arrives at + VideoCaptureController::OnFrameReadyInBuffer(). + </summary> +</histogram> + <histogram name="Media.VideoCapture.FrameRate" units="fps"> <owner>mcasas@chromium.org</owner> <summary> @@ -30838,6 +30937,43 @@ </summary> </histogram> +<histogram + name="Media.VideoCaptureService.DurationFromLastConnectToClosingConnection" + units="ms"> + <owner>chfremer@chromium.org</owner> + <summary> + Measures the duration from the time the Browser connected to the video + capture service to the time it closed the connection. + </summary> +</histogram> + +<histogram + name="Media.VideoCaptureService.DurationFromLastConnectToConnectionLost" + units="ms"> + <owner>chfremer@chromium.org</owner> + <summary> + Measures the duration from the time the Browser connected to the video + capture service to the time the connection was lost. + </summary> +</histogram> + +<histogram name="Media.VideoCaptureService.DurationUntilReconnect" units="ms"> + <owner>chfremer@chromium.org</owner> + <summary> + Measures the duration from the time the Browser last closed or lost + connection to the video capture service to the time it reconnects. + </summary> +</histogram> + +<histogram name="Media.VideoCaptureService.Event" + enum="VideoCaptureServiceEvent"> + <owner>chfremer@chromium.org</owner> + <summary> + Counts video capture service events, such as startup, shutdown, and + connection lost. + </summary> +</histogram> + <histogram name="Media.VideoCodec" enum="VideoCodec"> <owner>scherkus@chromium.org</owner> <summary>Video codec used in HTML5 media.</summary> @@ -61891,6 +62027,49 @@ </summary> </histogram> +<histogram name="Reporting.HeaderEndpointOutcome" + enum="ReportingHeaderEndpointOutcome"> + <owner>juliatuttle@chromium.org</owner> + <summary> + The outcome of Reporting trying to process a single endpoint in a Report-To + header once the header itself has been parsed. + </summary> +</histogram> + +<histogram name="Reporting.HeaderOutcome" enum="ReportingHeaderOutcome"> + <owner>juliatuttle@chromium.org</owner> + <summary> + The outcome of Reporting trying to process a Report-To header. Once it is + parsed, Reporting.HeaderEndpointOutcome records the outcome of the endpoints + within it. + </summary> +</histogram> + +<histogram name="Reporting.ReportDeliveredAttempts" units="attempts"> + <owner>juliatuttle@chromium.org</owner> + <summary> + When Reporting successfully delivers a report, the number of unsuccessful + delivery attempts that preceded the successful one. + </summary> +</histogram> + +<histogram name="Reporting.ReportDeliveredLatency" units="ms"> + <owner>juliatuttle@chromium.org</owner> + <summary> + The delivery latency of reports successfully delivered by Reporting. Starts + when the report is queued and finishes when the delivery attempt returns + successfully. + </summary> +</histogram> + +<histogram name="Reporting.ReportOutcome" enum="ReportingReportOutcome"> + <owner>juliatuttle@chromium.org</owner> + <summary> + The outcome of Reporting trying to deliver a report, recorded when the + report is finally erased from memory. + </summary> +</histogram> + <histogram name="RequestAutocomplete.DismissalState" enum="AutofillDialogDismissalState"> <obsolete> @@ -87566,6 +87745,14 @@ </summary> </histogram> +<histogram name="WinJumplist.NotificationTimeInterval" units="ms"> + <owner>chengx@chromium.org</owner> + <summary> + The time interval between two adjacent update notifications if it's less + than 3500 ms. + </summary> +</histogram> + <histogram name="WinJumplist.OnFaviconDataAvailableDuration" units="ms"> <obsolete> Obsolete 06/22/2017 as it's no longer needed. @@ -87574,6 +87761,14 @@ <summary>Time spent in OnFaviconDataAvailable().</summary> </histogram> +<histogram name="WinJumplist.RatioAddCategoryTime" units="scaled ratio"> + <owner>chengx@chromium.org</owner> + <summary> + The ratio of the duration spent adding the most-visited category compared to + the duration spent adding the recently-closed category, multiplied by 10. + </summary> +</histogram> + <histogram name="WinJumplist.StartLoadingFaviconDuration" units="ms"> <obsolete> Obsolete 06/22/2017 as it's no longer needed. @@ -96576,6 +96771,7 @@ <suffix name="OfflinePageMetadata" label="OfflinePageMetadata"/> <suffix name="Passwords" label="Passwords"/> <suffix name="Precache" label="Precache"/> + <suffix name="PrefetchStore" label="PrefetchStore"/> <suffix name="Predictor" label="Predictor"/> <suffix name="PreviewsOptOut" label="PreviewsOptOut"/> <suffix name="Quota" label="Quota"/>
diff --git a/tools/perf/benchmarks/indexeddb_perf.py b/tools/perf/benchmarks/indexeddb_perf.py index 5f4af66613..d04c88d 100644 --- a/tools/perf/benchmarks/indexeddb_perf.py +++ b/tools/perf/benchmarks/indexeddb_perf.py
@@ -88,7 +88,6 @@ power.PowerMetric.CustomizeBrowserOptions(options) -@benchmark.Disabled('linux') # crbug.com/677972 @benchmark.Owner(emails=['cmumford@chromium.org']) class IndexedDbOriginalSectioned(perf_benchmark.PerfBenchmark): """Chromium's IndexedDB Performance tests.""" @@ -103,7 +102,6 @@ return page_sets.IndexedDBEndureStoryExpectations() -@benchmark.Disabled('linux') # crbug.com/677972 @benchmark.Owner(emails=['cmumford@chromium.org']) class IndexedDbTracing(perf_benchmark.PerfBenchmark): """IndexedDB Performance tests that use tracing."""
diff --git a/tools/perf/benchmarks/v8.py b/tools/perf/benchmarks/v8.py index 78f93a61..f285662 100644 --- a/tools/perf/benchmarks/v8.py +++ b/tools/perf/benchmarks/v8.py
@@ -133,6 +133,10 @@ class _Top25RuntimeStats(perf_benchmark.PerfBenchmark): options = {'pageset_repeat': 3} + def SetExtraBrowserOptions(self, options): + options.AppendExtraBrowserArgs( + '--enable-blink-features=BlinkRuntimeCallStats') + def CreateTimelineBasedMeasurementOptions(self): # TODO(fmeawad): most of the cat_filter information is extracted from # page_cycler_v2 TimelineBasedMeasurementOptionsForLoadingMetric because
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc index 40c2ab2a..f022b38 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc
@@ -11,7 +11,6 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "third_party/protobuf/src/google/protobuf/io/tokenizer.h" @@ -68,8 +67,6 @@ } // namespace -namespace traffic_annotation_auditor { - const int AuditorResult::kNoCodeLineSpecified = -1; AuditorResult::AuditorResult(ResultType type, @@ -164,7 +161,7 @@ } // Process test tags. - unique_id_hash_code = ComputeHashValue(unique_id); + unique_id_hash_code = TrafficAnnotationAuditor::ComputeHashValue(unique_id); if (unique_id_hash_code == TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code || unique_id_hash_code == PARTIAL_TRAFFIC_ANNOTATION_FOR_TESTS.unique_id_hash_code) { @@ -207,7 +204,7 @@ src->set_function(function_context); src->set_line(line_number); proto.set_unique_id(unique_id); - extra_id_hash_code = ComputeHashValue(extra_id); + extra_id_hash_code = TrafficAnnotationAuditor::ComputeHashValue(extra_id); return AuditorResult(AuditorResult::ResultType::RESULT_OK); } @@ -242,68 +239,73 @@ return AuditorResult(AuditorResult::ResultType::RESULT_OK); } -int ComputeHashValue(const std::string& unique_id) { +int TrafficAnnotationAuditor::ComputeHashValue(const std::string& unique_id) { return unique_id.length() ? static_cast<int>(recursive_hash( unique_id.c_str(), unique_id.length())) : -1; } -std::string RunClangTool(const base::FilePath& source_path, - const base::FilePath& build_path, - const base::CommandLine::StringVector& path_filters, - const bool full_run) { +TrafficAnnotationAuditor::TrafficAnnotationAuditor( + const base::FilePath& source_path, + const base::FilePath& build_path) + : source_path_(source_path), build_path_(build_path) { + LoadWhiteList(); +}; + +TrafficAnnotationAuditor::~TrafficAnnotationAuditor(){}; + +bool TrafficAnnotationAuditor::RunClangTool( + const std::vector<std::string>& path_filters, + const bool full_run) { base::FilePath options_filepath; if (!base::CreateTemporaryFile(&options_filepath)) { LOG(ERROR) << "Could not create temporary options file."; - return std::string(); + return false; } FILE* options_file = base::OpenFile(options_filepath, "wt"); if (!options_file) { LOG(ERROR) << "Could not create temporary options file."; - return std::string(); + return false; } fprintf(options_file, "--generate-compdb --tool=traffic_annotation_extractor -p=%s ", - build_path.MaybeAsASCII().c_str()); + build_path_.MaybeAsASCII().c_str()); + // |ignore_list_[ALL]| is not passed when |full_run| is happening as there is + // no way to pass it to run_tools.py except enumerating all alternatives. + // The paths in |ignore_list_[ALL]| are removed later from the results. if (full_run) { - for (const auto& file_path : path_filters) - fprintf(options_file, "%s ", -#if defined(OS_WIN) - base::WideToUTF8(file_path).c_str() -#else - file_path.c_str() -#endif - ); + for (const std::string& file_path : path_filters) + fprintf(options_file, "%s ", file_path.c_str()); } else { TrafficAnnotationFileFilter filter; std::vector<std::string> file_paths; if (path_filters.size()) { for (const auto& path_filter : path_filters) { - filter.GetRelevantFiles(source_path, -#if defined(OS_WIN) - base::UTF16ToASCII(path_filter), -#else - path_filter, -#endif - &file_paths); + filter.GetRelevantFiles(source_path_, + ignore_list_[static_cast<int>( + AuditorException::ExceptionType::ALL)], + path_filter, &file_paths); } } else { - filter.GetRelevantFiles(source_path, "", &file_paths); + filter.GetRelevantFiles( + source_path_, + ignore_list_[static_cast<int>(AuditorException::ExceptionType::ALL)], + "", &file_paths); } if (!file_paths.size()) { base::CloseFile(options_file); base::DeleteFile(options_filepath, false); - return std::string(); + return false; } for (const auto& file_path : file_paths) fprintf(options_file, "%s ", file_path.c_str()); } base::CloseFile(options_file); - base::CommandLine cmdline(source_path.Append(FILE_PATH_LITERAL("tools")) + base::CommandLine cmdline(source_path_.Append(FILE_PATH_LITERAL("tools")) .Append(FILE_PATH_LITERAL("clang")) .Append(FILE_PATH_LITERAL("scripts")) .Append(FILE_PATH_LITERAL("run_tool.py"))); @@ -315,24 +317,29 @@ cmdline.AppendArg(base::StringPrintf( "--options-file=%s", options_filepath.MaybeAsASCII().c_str())); - std::string results; - if (!base::GetAppOutput(cmdline, &results)) - results = std::string(); + bool result = base::GetAppOutput(cmdline, &clang_tool_raw_output_); base::DeleteFile(options_filepath, false); - return results; + return result; } -bool ParseClangToolRawOutput(const std::string& clang_output, - std::vector<AnnotationInstance>* annotations, - std::vector<CallInstance>* calls, - std::vector<AuditorResult>* errors) { +bool TrafficAnnotationAuditor::IsWhitelisted( + const std::string file_path, + const std::vector<std::string>& whitelist) { + for (const std::string& ignore_path : whitelist) { + if (!strncmp(file_path.c_str(), ignore_path.c_str(), ignore_path.length())) + return true; + } + return false; +} + +bool TrafficAnnotationAuditor::ParseClangToolRawOutput() { // Remove possible carriage return characters before splitting lines. - std::string trimmed_input; - base::RemoveChars(clang_output, "\r", &trimmed_input); - std::vector<std::string> lines = base::SplitString( - trimmed_input, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + base::RemoveChars(clang_tool_raw_output_, "\r", &clang_tool_raw_output_); + std::vector<std::string> lines = + base::SplitString(clang_tool_raw_output_, "\n", base::KEEP_WHITESPACE, + base::SPLIT_WANT_ALL); for (unsigned int current = 0; current < lines.size(); current++) { bool annotation_block; @@ -369,23 +376,31 @@ ? new_annotation.Deserialize(lines, current, end_line) : new_call.Deserialize(lines, current, end_line); - switch (result.type()) { - case AuditorResult::ResultType::RESULT_OK: { - if (annotation_block) - annotations->push_back(new_annotation); - else - calls->push_back(new_call); - break; + if (!IsWhitelisted(result.file_path(), + ignore_list_[static_cast<int>( + AuditorException::ExceptionType::ALL)]) && + (result.type() != AuditorResult::ResultType::ERROR_MISSING || + !IsWhitelisted(result.file_path(), + ignore_list_[static_cast<int>( + AuditorException::ExceptionType::MISSING)]))) { + switch (result.type()) { + case AuditorResult::ResultType::RESULT_OK: { + if (annotation_block) + extracted_annotations_.push_back(new_annotation); + else + extracted_calls_.push_back(new_call); + break; + } + case AuditorResult::ResultType::RESULT_IGNORE: + break; + case AuditorResult::ResultType::ERROR_FATAL: { + LOG(ERROR) << "Aborting after line " << current + << " because: " << result.ToText().c_str(); + return false; + } + default: + errors_.push_back(result); } - case AuditorResult::ResultType::RESULT_IGNORE: - break; - case AuditorResult::ResultType::ERROR_FATAL: { - LOG(ERROR) << "Aborting after line " << current - << " because: " << result.ToText().c_str(); - return false; - } - default: - errors->push_back(result); } current = end_line; @@ -394,4 +409,41 @@ return true; } -} // namespace traffic_annotation_auditor \ No newline at end of file +bool TrafficAnnotationAuditor::LoadWhiteList() { + base::FilePath white_list_file = base::MakeAbsoluteFilePath( + source_path_.Append(FILE_PATH_LITERAL("tools")) + .Append(FILE_PATH_LITERAL("traffic_annotation")) + .Append(FILE_PATH_LITERAL("auditor")) + .Append(FILE_PATH_LITERAL("white_list.txt"))); + std::string file_content; + if (base::ReadFileToString(white_list_file, &file_content)) { + base::RemoveChars(file_content, "\r", &file_content); + std::vector<std::string> lines = base::SplitString( + file_content, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); + for (const std::string& line : lines) { + // Ignore comments. + if (line.length() && line[0] == '#') + continue; + size_t comma = line.find(','); + if (comma == std::string::npos) { + LOG(ERROR) << "Unexpected syntax in white_list.txt, line: " << line; + return false; + } + + AuditorException::ExceptionType exception_type; + if (AuditorException::TypeFromString(line.substr(0, comma), + &exception_type)) { + ignore_list_[static_cast<int>(exception_type)].push_back( + line.substr(comma + 1, line.length() - comma - 1)); + } else { + LOG(ERROR) << "Unexpected type in white_list.txt line: " << line; + return false; + } + } + return true; + } + + LOG(ERROR) + << "Could not read tools/traffic_annotation/auditor/white_list.txt"; + return false; +} \ No newline at end of file
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.h b/tools/traffic_annotation/auditor/traffic_annotation_auditor.h index bb23738..14024a4 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor.h +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor.h
@@ -5,11 +5,36 @@ #ifndef TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ #define TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ +#include <vector> + #include "base/command_line.h" #include "base/files/file_path.h" #include "tools/traffic_annotation/traffic_annotation.pb.h" -namespace traffic_annotation_auditor { +// Holds an item of whitelist exception rule for auditor. +struct AuditorException { + enum class ExceptionType { + ALL, // Ignore all errors (doesn't check the files at all). + MISSING, // Ignore missing annotations. + EMPTY_MUTABLE, // Ignore empty mutable annotation constructor. + EXCEPTION_TYPE_LAST = EMPTY_MUTABLE + } type; + std::string partial_path; + + static bool TypeFromString(const std::string& type_string, + ExceptionType* type_value) { + if (type_string == "all") { + *type_value = ExceptionType::ALL; + } else if (type_string == "missing") { + *type_value = ExceptionType::MISSING; + } else if (type_string == "empty_mutable") { + *type_value = ExceptionType::EMPTY_MUTABLE; + } else { + return false; + } + return true; + } +}; // Holds the auditor processing results on one unit of annotation or function. class AuditorResult { @@ -36,6 +61,8 @@ ResultType type() const { return type_; }; + std::string file_path() const { return file_path_; } + // Formats the error message into one line of text. std::string ToText() const; @@ -130,23 +157,60 @@ bool is_annotated; }; -// Runs traffic_annotation_extractor clang tool and returns its output. -std::string RunClangTool(const base::FilePath& source_path, - const base::FilePath& build_path, - const base::CommandLine::StringVector& path_filters, - bool full_run); +class TrafficAnnotationAuditor { + public: + TrafficAnnotationAuditor(const base::FilePath& source_path, + const base::FilePath& build_path); + ~TrafficAnnotationAuditor(); -// Parses the output of clang tool and populates instances, calls, and errors. -// Errors include not finding the file, incorrect content, or missing or not -// provided annotations. -bool ParseClangToolRawOutput(const std::string& clang_output, - std::vector<AnnotationInstance>* annotations, - std::vector<CallInstance>* calls, - std::vector<AuditorResult>* errors); + // Runs traffic_annotation_extractor clang tool and puts its output in + // |clang_tool_raw_output_|. + bool RunClangTool(const std::vector<std::string>& path_filters, + bool full_run); -// Computes the hash value of a traffic annotation unique id. -int ComputeHashValue(const std::string& unique_id); + // Parses the output of clang tool (|clang_tool_raw_output_|) and populates + // |extracted_annotations_|, |extracted_calls_|, and |errors_|. + // Errors include not finding the file, incorrect content, or missing or not + // provided annotations. + bool ParseClangToolRawOutput(); -} // namespace traffic_annotation_auditor + // Computes the hash value of a traffic annotation unique id. + static int ComputeHashValue(const std::string& unique_id); + + std::string clang_tool_raw_output() const { return clang_tool_raw_output_; }; + + void set_clang_tool_raw_output(const std::string& raw_output) { + clang_tool_raw_output_ = raw_output; + }; + + const std::vector<AnnotationInstance>& extracted_annotations() const { + return extracted_annotations_; + } + + const std::vector<CallInstance>& extracted_calls() const { + return extracted_calls_; + } + + const std::vector<AuditorResult>& errors() const { return errors_; } + + private: + // Loads the whitelist file and populates ignore_list member variables. + bool LoadWhiteList(); + + // Checks to see if a |file_path| matches a |whitelist| of partial paths. + bool IsWhitelisted(const std::string file_path, + const std::vector<std::string>& whitelist); + + const base::FilePath source_path_; + const base::FilePath build_path_; + + std::string clang_tool_raw_output_; + std::vector<AnnotationInstance> extracted_annotations_; + std::vector<CallInstance> extracted_calls_; + std::vector<AuditorResult> errors_; + + std::vector<std::string> ignore_list_[static_cast<int>( + AuditorException::ExceptionType::EXCEPTION_TYPE_LAST)]; +}; #endif // TOOLS_TRAFFIC_ANNOTATION_AUDITOR_TRAFFIC_ANNOTATION_AUDITOR_H_ \ No newline at end of file
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc index f3299549..0e14b1f 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor_ui.cc
@@ -4,6 +4,8 @@ #include "base/files/file_util.h" #include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "third_party/protobuf/src/google/protobuf/text_format.h" @@ -63,7 +65,14 @@ bool full_run = command_line.HasSwitch("full-run"); base::FilePath summary_file = command_line.GetSwitchValuePath("summary-file"); base::FilePath ids_file = command_line.GetSwitchValuePath("ids-file"); - base::CommandLine::StringVector path_filters = command_line.GetArgs(); + std::vector<std::string> path_filters; + +#if defined(OS_WIN) + for (const auto& path : command_line.GetArgs()) + path_filters.push_back(base::UTF16ToASCII(path)); +#else + path_filters = command_line.GetArgs(); +#endif // If source path is not provided, guess it using build path or current // directory. @@ -75,8 +84,9 @@ .Append(base::FilePath::kParentDirectory); } + TrafficAnnotationAuditor auditor(source_path, build_path); + // Extract annotations. - std::string raw_output; if (extractor_input.empty()) { // Get build directory, if it is empty issue an error. if (build_path.empty()) { @@ -86,35 +96,37 @@ "extracted annotations already exist.\n"; return 1; } + if (!auditor.RunClangTool(path_filters, full_run)) + return 1; - raw_output = traffic_annotation_auditor::RunClangTool( - source_path, build_path, path_filters, full_run); + // Write extractor output if requested. + if (!extractor_output.empty()) { + std::string raw_output = auditor.clang_tool_raw_output(); + base::WriteFile(extractor_output, raw_output.c_str(), + raw_output.length()); + } } else { + std::string raw_output; if (!base::ReadFileToString(extractor_input, &raw_output)) { LOG(ERROR) << "Could not read input file: " << extractor_input.value().c_str(); return 1; + } else { + auditor.set_clang_tool_raw_output(raw_output); } } - // Write extractor output if requested. - if (!extractor_output.empty() && extractor_input.empty()) { - base::WriteFile(extractor_output, raw_output.c_str(), raw_output.length()); - } - // Process extractor output. - std::vector<traffic_annotation_auditor::AnnotationInstance> - annotation_instances; - std::vector<traffic_annotation_auditor::CallInstance> call_instances; - std::vector<traffic_annotation_auditor::AuditorResult> errors; - - if (!traffic_annotation_auditor::ParseClangToolRawOutput( - raw_output, &annotation_instances, &call_instances, &errors)) { + if (!auditor.ParseClangToolRawOutput()) return 1; - } // Write the summary file. if (!summary_file.empty()) { + const std::vector<AnnotationInstance>& annotation_instances = + auditor.extracted_annotations(); + const std::vector<CallInstance>& call_instances = auditor.extracted_calls(); + const std::vector<AuditorResult>& errors = auditor.errors(); + std::string report; std::vector<std::string> items; @@ -159,8 +171,10 @@ if (!ids_file.empty()) { std::string report; std::vector<std::pair<int, std::string>> items; + const std::vector<AnnotationInstance>& annotation_instances = + auditor.extracted_annotations(); for (auto& instance : annotation_instances) { - items.push_back(make_pair(traffic_annotation_auditor::ComputeHashValue( + items.push_back(make_pair(TrafficAnnotationAuditor::ComputeHashValue( instance.proto.unique_id()), instance.proto.unique_id())); } @@ -190,11 +204,10 @@ // Dump Errors and Warnings to stdout. // TODO(rhalavati@): The outputs are now limited to syntax errors. Will be // expanded when repository is full compatible. + const std::vector<AuditorResult>& errors = auditor.errors(); for (const auto& error : errors) { - if (error.type() == - traffic_annotation_auditor::AuditorResult::ResultType::ERROR_SYNTAX) { + if (error.type() == AuditorResult::ResultType::ERROR_SYNTAX) printf("Error: %s\n", error.ToText().c_str()); - } } return 0;
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc index 598b8bb..8373fb98 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc +++ b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.cc
@@ -116,6 +116,7 @@ void TrafficAnnotationFileFilter::GetRelevantFiles( const base::FilePath& source_path, + const std::vector<std::string>& ignore_list, std::string directory_name, std::vector<std::string>* file_paths) { if (!git_files_.size()) @@ -127,7 +128,17 @@ size_t name_length = directory_name.length(); for (const std::string& file_path : git_files_) { - if (!strncmp(file_path.c_str(), directory_name.c_str(), name_length)) - file_paths->push_back(file_path); + if (!strncmp(file_path.c_str(), directory_name.c_str(), name_length)) { + bool ignore = false; + for (const std::string& ignore_path : ignore_list) { + if (!strncmp(file_path.c_str(), ignore_path.c_str(), + ignore_path.length())) { + ignore = true; + break; + } + } + if (!ignore) + file_paths->push_back(file_path); + } } }
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h index 2e94919..0416c542 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h +++ b/tools/traffic_annotation/auditor/traffic_annotation_file_filter.h
@@ -26,7 +26,9 @@ // Returns the list of relevant files in the given |directory_name| into the // |file_paths|. If |directory_name| is empty, all files are returned. // |source_path| should be the repository source directory, e.g. C:/src. + // |ignore_list| provides a list of partial paths to ignore. void GetRelevantFiles(const base::FilePath& source_path, + const std::vector<std::string>& ignore_list, std::string directory_name, std::vector<std::string>* file_paths);
diff --git a/tools/traffic_annotation/auditor/white_list.txt b/tools/traffic_annotation/auditor/white_list.txt new file mode 100644 index 0000000..36500fc --- /dev/null +++ b/tools/traffic_annotation/auditor/white_list.txt
@@ -0,0 +1,7 @@ +# This is a comma separated file, specifying the white list for network traffic +# anntotation auditor. Refer to AuditorException::ExceptionType in +# 'tools/traffic_annotation/auditor/traffic_annotation_auditor.h' for types of +# exceptions.. +all,tools +missing,net/url_request/url_fetcher.cc +missing,net/url_request/url_request_context.cc \ No newline at end of file
diff --git a/ui/app_list/BUILD.gn b/ui/app_list/BUILD.gn index 979cde4..5ff7cec 100644 --- a/ui/app_list/BUILD.gn +++ b/ui/app_list/BUILD.gn
@@ -76,6 +76,7 @@ "//base/third_party/dynamic_annotations", "//components/keyed_service/core", "//components/sync", + "//components/wallpaper", "//skia", "//third_party/icu", "//ui/accessibility",
diff --git a/ui/app_list/OWNERS b/ui/app_list/OWNERS index 46b4daee..b3acb36f 100644 --- a/ui/app_list/OWNERS +++ b/ui/app_list/OWNERS
@@ -1,7 +1,5 @@ -benwells@chromium.org calamity@chromium.org jennyz@chromium.org -mgiuca@chromium.org +khmel@chromium.org stevenjb@chromium.org -tapted@chromium.org xiyuan@chromium.org
diff --git a/ui/app_list/search_box_model.cc b/ui/app_list/search_box_model.cc index 877d677..790d9fab 100644 --- a/ui/app_list/search_box_model.cc +++ b/ui/app_list/search_box_model.cc
@@ -81,6 +81,16 @@ observer.Update(); } +void SearchBoxModel::SetWallpaperProminentColors( + const std::vector<SkColor>& colors) { + if (wallpaper_prominent_colors_ == colors) + return; + + wallpaper_prominent_colors_ = colors; + for (auto& observer : observers_) + observer.WallpaperProminentColorsChanged(); +} + void SearchBoxModel::AddObserver(SearchBoxModelObserver* observer) { observers_.AddObserver(observer); }
diff --git a/ui/app_list/search_box_model.h b/ui/app_list/search_box_model.h index fe53744..36b27781 100644 --- a/ui/app_list/search_box_model.h +++ b/ui/app_list/search_box_model.h
@@ -74,6 +74,12 @@ const base::string16& text() const { return text_; } bool is_voice_query() const { return is_voice_query_; } + // Sets/gets the wallpaper prominent colors. + void SetWallpaperProminentColors(const std::vector<SkColor>& colors); + const std::vector<SkColor>& wallpaper_prominent_colors() const { + return wallpaper_prominent_colors_; + } + void AddObserver(SearchBoxModelObserver* observer); void RemoveObserver(SearchBoxModelObserver* observer); @@ -84,6 +90,7 @@ gfx::SelectionModel selection_model_; base::string16 text_; bool is_voice_query_ = false; + std::vector<SkColor> wallpaper_prominent_colors_; base::ObserverList<SearchBoxModelObserver> observers_;
diff --git a/ui/app_list/search_box_model_observer.h b/ui/app_list/search_box_model_observer.h index 9dfd2e8..090f87a 100644 --- a/ui/app_list/search_box_model_observer.h +++ b/ui/app_list/search_box_model_observer.h
@@ -24,6 +24,9 @@ // Invoked when text or voice search flag is changed. virtual void Update() = 0; + // Invoked when wallpaper prominent colors are changed. + virtual void WallpaperProminentColorsChanged() = 0; + protected: virtual ~SearchBoxModelObserver() {} };
diff --git a/ui/app_list/views/search_box_view.cc b/ui/app_list/views/search_box_view.cc index 48a22b3..45f30f1 100644 --- a/ui/app_list/views/search_box_view.cc +++ b/ui/app_list/views/search_box_view.cc
@@ -9,6 +9,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "build/build_config.h" +#include "components/wallpaper/wallpaper_color_profile.h" #include "ui/app_list/app_list_constants.h" #include "ui/app_list/app_list_features.h" #include "ui/app_list/app_list_model.h" @@ -26,6 +27,7 @@ #include "ui/base/resource/resource_bundle.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" +#include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/shadow_value.h" @@ -40,6 +42,8 @@ #include "ui/views/shadow_border.h" #include "ui/views/widget/widget.h" +using wallpaper::ColorProfileType; + namespace app_list { namespace { @@ -62,14 +66,17 @@ constexpr SkColor kDefaultSearchboxColor = SkColorSetARGBMacro(0xDE, 0x00, 0x00, 0x00); +constexpr int kLightVibrantBlendAlpha = 0xB3; + // A background that paints a solid white rounded rect with a thin grey border. class SearchBoxBackground : public views::Background { public: - SearchBoxBackground() + explicit SearchBoxBackground(SkColor color) : background_border_corner_radius_( features::IsFullscreenAppListEnabled() ? kBackgroundBorderCornerRadiusFullscreen - : kBackgroundBorderCornerRadius) {} + : kBackgroundBorderCornerRadius), + color_(color) {} ~SearchBoxBackground() override {} private: @@ -79,11 +86,12 @@ cc::PaintFlags flags; flags.setAntiAlias(true); - flags.setColor(kSearchBoxBackgroundDefault); + flags.setColor(color_); canvas->DrawRoundRect(bounds, background_border_corner_radius_, flags); } const int background_border_corner_radius_; + const SkColor color_; DISALLOW_COPY_AND_ASSIGN(SearchBoxBackground); }; @@ -156,7 +164,8 @@ AddChildView(content_container_); SetShadow(GetShadowForZHeight(2)); - content_container_->SetBackground(base::MakeUnique<SearchBoxBackground>()); + content_container_->SetBackground( + base::MakeUnique<SearchBoxBackground>(kSearchBoxBackgroundDefault)); views::BoxLayout* layout = new views::BoxLayout( views::BoxLayout::kHorizontal, gfx::Insets(0, kPadding), @@ -216,6 +225,7 @@ model_->search_box()->AddObserver(this); SpeechRecognitionButtonPropChanged(); HintTextChanged(); + WallpaperProminentColorsChanged(); } bool SearchBoxView::HasSearch() const { @@ -498,6 +508,46 @@ NotifyQueryChanged(); } +void SearchBoxView::WallpaperProminentColorsChanged() { + if (!is_fullscreen_app_list_enabled_) + return; + + const std::vector<SkColor> prominent_colors = + model_->search_box()->wallpaper_prominent_colors(); + if (prominent_colors.empty()) + return; + + DCHECK_EQ(static_cast<size_t>(ColorProfileType::NUM_OF_COLOR_PROFILES), + prominent_colors.size()); + const SkColor dark_muted = + prominent_colors[static_cast<int>(ColorProfileType::DARK_MUTED)]; + const bool dark_muted_available = SK_ColorTRANSPARENT != dark_muted; + google_icon_->SetImage(gfx::CreateVectorIcon( + kIcGoogleBlackIcon, kGoogleIconSize, + dark_muted_available ? dark_muted : kDefaultSearchboxColor)); + speech_button_->SetImage( + views::Button::STATE_NORMAL, + gfx::CreateVectorIcon( + kIcMicBlackIcon, kMicIconSize, + dark_muted_available ? dark_muted : kDefaultSearchboxColor)); + search_box_->set_placeholder_text_color( + dark_muted_available ? dark_muted : kDefaultSearchboxColor); + + const SkColor light_vibrant = + prominent_colors[static_cast<int>(ColorProfileType::LIGHT_VIBRANT)]; + const SkColor light_vibrant_mixed = color_utils::AlphaBlend( + SK_ColorWHITE, light_vibrant, kLightVibrantBlendAlpha); + const bool light_vibrant_available = SK_ColorTRANSPARENT != light_vibrant; + content_container_->SetBackground(base::MakeUnique<SearchBoxBackground>( + light_vibrant_available ? light_vibrant_mixed + : kSearchBoxBackgroundDefault)); + search_box_->SetBackgroundColor(light_vibrant_available + ? light_vibrant_mixed + : kSearchBoxBackgroundDefault); + + SchedulePaint(); +} + void SearchBoxView::OnSpeechRecognitionStateChanged( SpeechRecognitionState new_state) { SpeechRecognitionButtonPropChanged();
diff --git a/ui/app_list/views/search_box_view.h b/ui/app_list/views/search_box_view.h index d2cee93..a8e8486 100644 --- a/ui/app_list/views/search_box_view.h +++ b/ui/app_list/views/search_box_view.h
@@ -110,6 +110,7 @@ void HintTextChanged() override; void SelectionModelChanged() override; void Update() override; + void WallpaperProminentColorsChanged() override; // Overridden from SpeechUIModelObserver: void OnSpeechRecognitionStateChanged(
diff --git a/ui/arc/notification/arc_notification_surface_impl.cc b/ui/arc/notification/arc_notification_surface_impl.cc index 7a766c16..03d6e7bf 100644 --- a/ui/arc/notification/arc_notification_surface_impl.cc +++ b/ui/arc/notification/arc_notification_surface_impl.cc
@@ -20,7 +20,7 @@ } gfx::Size ArcNotificationSurfaceImpl::GetSize() const { - return surface_->GetSize(); + return surface_->GetContentSize(); } void ArcNotificationSurfaceImpl::Attach(
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn index 710731ee..4441ecb 100644 --- a/ui/base/BUILD.gn +++ b/ui/base/BUILD.gn
@@ -6,6 +6,7 @@ import("//build/config/compiler/compiler.gni") import("//build/config/sanitizers/sanitizers.gni") import("//build/config/ui.gni") +import("//build/util/branding.gni") import("//testing/test.gni") import("//ui/base/ui_features.gni") import("//ui/ozone/ozone.gni") @@ -1014,6 +1015,7 @@ "//ui/resources:ui_test_pak_bundle_data", ] info_plist = "test/framework-Info.plist" + extra_substitutions = [ "CHROMIUM_BUNDLE_ID=$chrome_mac_bundle_id" ] output_name = "ui_unittests Framework" } }
diff --git a/ui/base/test/framework-Info.plist b/ui/base/test/framework-Info.plist index f3b7fc725b..3d749a5 100644 --- a/ui/base/test/framework-Info.plist +++ b/ui/base/test/framework-Info.plist
@@ -7,7 +7,7 @@ <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> <key>CFBundleIdentifier</key> - <string>${CHROMIUM_BUNDLE_ID}.framework</string> + <string>${CHROMIUM_BUNDLE_ID}.ui_unittests.framework</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundlePackageType</key>
diff --git a/ui/display/BUILD.gn b/ui/display/BUILD.gn index 4d1103ef..0d7b80d 100644 --- a/ui/display/BUILD.gn +++ b/ui/display/BUILD.gn
@@ -36,6 +36,8 @@ "screen_aura.cc", "screen_base.cc", "screen_base.h", + "win/color_profile_reader.cc", + "win/color_profile_reader.h", "win/display_info.cc", "win/display_info.h", "win/dpi.cc",
diff --git a/ui/display/win/color_profile_reader.cc b/ui/display/win/color_profile_reader.cc new file mode 100644 index 0000000..d1220cfd --- /dev/null +++ b/ui/display/win/color_profile_reader.cc
@@ -0,0 +1,131 @@ +// 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 "ui/display/win/color_profile_reader.h" + +#include <stddef.h> +#include <windows.h> + +#include "base/files/file_util.h" +#include "base/task_scheduler/post_task.h" +#include "base/threading/sequenced_worker_pool.h" +#include "ui/display/win/display_info.h" +#include "ui/gfx/icc_profile.h" + +namespace display { +namespace win { +namespace { + +BOOL CALLBACK EnumMonitorCallback(HMONITOR monitor, + HDC input_hdc, + LPRECT rect, + LPARAM data) { + base::string16 device_name; + MONITORINFOEX monitor_info; + ::ZeroMemory(&monitor_info, sizeof(monitor_info)); + monitor_info.cbSize = sizeof(monitor_info); + ::GetMonitorInfo(monitor, &monitor_info); + device_name = base::string16(monitor_info.szDevice); + + base::string16 profile_path; + HDC hdc = ::CreateDC(monitor_info.szDevice, NULL, NULL, NULL); + if (hdc) { + DWORD path_length = MAX_PATH; + WCHAR path[MAX_PATH + 1]; + BOOL result = ::GetICMProfile(hdc, &path_length, path); + ::DeleteDC(hdc); + if (result) + profile_path = base::string16(path); + } + + std::map<base::string16, base::string16>* device_to_path_map = + reinterpret_cast<std::map<base::string16, base::string16>*>(data); + (*device_to_path_map)[device_name] = profile_path; + return TRUE; +} + +} // namespace + +ColorProfileReader::ColorProfileReader(Client* client) + : client_(client), weak_factory_(this) {} + +ColorProfileReader::~ColorProfileReader() {} + +void ColorProfileReader::UpdateIfNeeded() { + if (update_in_flight_) + return; + + DeviceToPathMap new_device_to_path_map = BuildDeviceToPathMap(); + if (device_to_path_map_ == new_device_to_path_map) + return; + + if (!base::SequencedWorkerPool::IsEnabled()) + return; + + update_in_flight_ = true; + base::PostTaskWithTraitsAndReplyWithResult( + FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, + base::Bind(&ColorProfileReader::ReadProfilesOnBackgroundThread, + new_device_to_path_map), + base::Bind(&ColorProfileReader::ReadProfilesCompleted, + weak_factory_.GetWeakPtr())); +} + +// static +ColorProfileReader::DeviceToPathMap ColorProfileReader::BuildDeviceToPathMap() { + DeviceToPathMap device_to_path_map; + EnumDisplayMonitors(nullptr, nullptr, EnumMonitorCallback, + reinterpret_cast<LPARAM>(&device_to_path_map)); + return device_to_path_map; +} + +// static +ColorProfileReader::DeviceToDataMap +ColorProfileReader::ReadProfilesOnBackgroundThread( + DeviceToPathMap new_device_to_path_map) { + DeviceToDataMap new_device_to_data_map; + for (auto entry : new_device_to_path_map) { + const base::string16& device_name = entry.first; + const base::string16& profile_path = entry.second; + std::string profile_data; + base::ReadFileToString(base::FilePath(profile_path), &profile_data); + new_device_to_data_map[device_name] = profile_data; + } + return new_device_to_data_map; +} + +void ColorProfileReader::ReadProfilesCompleted( + DeviceToDataMap device_to_data_map) { + DCHECK(update_in_flight_); + update_in_flight_ = false; + + display_id_to_color_space_map_.clear(); + for (auto entry : device_to_data_map) { + const base::string16& device_name = entry.first; + const std::string& profile_data = entry.second; + int64_t display_id = + DisplayInfo::DeviceIdFromDeviceName(device_name.c_str()); + + if (profile_data.empty()) { + display_id_to_color_space_map_[display_id] = default_color_space_; + } else { + display_id_to_color_space_map_[display_id] = + gfx::ICCProfile::FromData(profile_data.data(), profile_data.size()) + .GetColorSpace(); + } + } + + client_->OnColorProfilesChanged(); +} + +const gfx::ColorSpace& ColorProfileReader::GetDisplayColorSpace( + int64_t display_id) const { + auto found = display_id_to_color_space_map_.find(display_id); + if (found == display_id_to_color_space_map_.end()) + return default_color_space_; + return found->second; +} + +} // namespace win +} // namespace display
diff --git a/ui/display/win/color_profile_reader.h b/ui/display/win/color_profile_reader.h new file mode 100644 index 0000000..0d1e2b4 --- /dev/null +++ b/ui/display/win/color_profile_reader.h
@@ -0,0 +1,70 @@ +// 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 UI_DISPLAY_WIN_COLOR_PROFILE_READER_H_ +#define UI_DISPLAY_WIN_COLOR_PROFILE_READER_H_ + +#include "base/callback.h" +#include "base/memory/weak_ptr.h" +#include "base/strings/string16.h" +#include "ui/display/display_export.h" +#include "ui/gfx/color_space.h" + +#include <map> +#include <string> + +namespace display { +namespace win { + +// Monitor ICC profiles are stored in the filesystem, and a blocking read from +// file is required to read them. This is expensive and shouldn't be done on the +// main thread, so this class manages asynchronously doing these readings and +// calling back into its client when the profiles are noticed to have changed. +class DISPLAY_EXPORT ColorProfileReader { + public: + class Client { + public: + virtual void OnColorProfilesChanged() = 0; + }; + + ColorProfileReader(Client* client); + ~ColorProfileReader(); + + // Check to see if the screen profile filenames have changed. If so, spawn a + // task to update them. When the task has completed, this will call the + // client's OnColorProfileReaderChanged on the main thread. + void UpdateIfNeeded(); + + // Look up the color space for a given device name. If the device's color + // profile has not yet been read, this will return sRGB (which is what the + // file on disk will say most of the time). + const gfx::ColorSpace& GetDisplayColorSpace(int64_t id) const; + + private: + typedef std::map<base::string16, base::string16> DeviceToPathMap; + typedef std::map<base::string16, std::string> DeviceToDataMap; + + // Enumerate displays and return a map to their ICC profile path. + static DeviceToPathMap BuildDeviceToPathMap(); + + // Do the actual reading from the filesystem. This needs to be run off of the + // main thread. + static DeviceToDataMap ReadProfilesOnBackgroundThread( + DeviceToPathMap new_device_to_path_map); + + // Called on the main thread when the read has completed. + void ReadProfilesCompleted(DeviceToDataMap device_to_data_map); + + Client* const client_ = nullptr; + bool update_in_flight_ = false; + DeviceToPathMap device_to_path_map_; + std::map<int64_t, gfx::ColorSpace> display_id_to_color_space_map_; + const gfx::ColorSpace default_color_space_ = gfx::ColorSpace::CreateSRGB(); + base::WeakPtrFactory<ColorProfileReader> weak_factory_; +}; + +} // namespace win +} // namespace display + +#endif // UI_DISPLAY_WIN_COLOR_PROFILE_READER_H_
diff --git a/ui/display/win/screen_win.cc b/ui/display/win/screen_win.cc index f585989..8e121b0 100644 --- a/ui/display/win/screen_win.cc +++ b/ui/display/win/screen_win.cc
@@ -211,10 +211,14 @@ } // namespace -ScreenWin::ScreenWin() { +ScreenWin::ScreenWin() : ScreenWin(true) {} + +ScreenWin::ScreenWin(bool initialize) + : color_profile_reader_(new ColorProfileReader(this)) { DCHECK(!g_screen_win_instance); g_screen_win_instance = this; - Initialize(); + if (initialize) + Initialize(); } ScreenWin::~ScreenWin() { @@ -457,6 +461,7 @@ } void ScreenWin::Initialize() { + color_profile_reader_->UpdateIfNeeded(); singleton_hwnd_observer_.reset( new gfx::SingletonHwndObserver( base::Bind(&ScreenWin::OnWndProc, base::Unretained(this)))); @@ -499,11 +504,16 @@ !(message == WM_SETTINGCHANGE && wparam == SPI_SETWORKAREA)) return; + color_profile_reader_->UpdateIfNeeded(); std::vector<Display> old_displays = std::move(displays_); UpdateFromDisplayInfos(GetDisplayInfosFromSystem()); change_notifier_.NotifyDisplaysChanged(old_displays, displays_); } +void ScreenWin::OnColorProfilesChanged() { + // TODO(ccameron): Re-build the display list here. +} + ScreenWinDisplay ScreenWin::GetScreenWinDisplayNearestHWND(HWND hwnd) const { return GetScreenWinDisplay(MonitorInfoFromWindow(hwnd,
diff --git a/ui/display/win/screen_win.h b/ui/display/win/screen_win.h index eed87d9e..d6a3497 100644 --- a/ui/display/win/screen_win.h +++ b/ui/display/win/screen_win.h
@@ -14,6 +14,7 @@ #include "ui/display/display_change_notifier.h" #include "ui/display/display_export.h" #include "ui/display/screen.h" +#include "ui/display/win/color_profile_reader.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/win/singleton_hwnd_observer.h" @@ -30,7 +31,8 @@ class DisplayInfo; class ScreenWinDisplay; -class DISPLAY_EXPORT ScreenWin : public Screen { +class DISPLAY_EXPORT ScreenWin : public Screen, + public ColorProfileReader::Client { public: ScreenWin(); ~ScreenWin() override; @@ -116,6 +118,8 @@ virtual gfx::NativeWindow GetNativeWindowFromHWND(HWND hwnd) const; protected: + ScreenWin(bool initialize); + // Screen: gfx::Point GetCursorScreenPoint() override; bool IsWindowUnderCursor(gfx::NativeWindow window) override; @@ -133,10 +137,12 @@ gfx::Rect DIPToScreenRectInWindow( gfx::NativeView view, const gfx::Rect& dip_rect) const override; + // ColorProfileReader::Client: + void OnColorProfilesChanged() override; + void UpdateFromDisplayInfos(const std::vector<DisplayInfo>& display_infos); // Virtual to support mocking by unit tests. - virtual void Initialize(); virtual MONITORINFOEX MonitorInfoFromScreenPoint( const gfx::Point& screen_point) const; virtual MONITORINFOEX MonitorInfoFromScreenRect(const gfx::Rect& screen_rect) @@ -147,6 +153,7 @@ virtual int GetSystemMetrics(int metric) const; private: + void Initialize(); void OnWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); // Returns the ScreenWinDisplay closest to or enclosing |hwnd|. @@ -193,6 +200,9 @@ // This must be updated anytime |screen_win_displays_| is updated. std::vector<Display> displays_; + // A helper to read color profiles from the filesystem. + std::unique_ptr<ColorProfileReader> color_profile_reader_; + DISALLOW_COPY_AND_ASSIGN(ScreenWin); };
diff --git a/ui/display/win/screen_win_unittest.cc b/ui/display/win/screen_win_unittest.cc index c59dd60d..58f1b602 100644 --- a/ui/display/win/screen_win_unittest.cc +++ b/ui/display/win/screen_win_unittest.cc
@@ -35,8 +35,7 @@ TestScreenWin(const std::vector<DisplayInfo>& display_infos, const std::vector<MONITORINFOEX>& monitor_infos, const std::unordered_map<HWND, gfx::Rect>& hwnd_map) - : monitor_infos_(monitor_infos), - hwnd_map_(hwnd_map) { + : ScreenWin(false), monitor_infos_(monitor_infos), hwnd_map_(hwnd_map) { UpdateFromDisplayInfos(display_infos); } @@ -57,8 +56,6 @@ } private: - void Initialize() override {} - // Finding the corresponding monitor from a point is generally handled by // Windows's MonitorFromPoint. This mocked function requires that the provided // point is contained entirely in the monitor.
diff --git a/ui/events/blink/blink_event_util.cc b/ui/events/blink/blink_event_util.cc index 1c2c1312..c380b89 100644 --- a/ui/events/blink/blink_event_util.cc +++ b/ui/events/blink/blink_event_util.cc
@@ -804,8 +804,6 @@ float x = (mouse_event->PositionInWidget().x + delta.x()) * scale; float y = (mouse_event->PositionInWidget().y + delta.y()) * scale; mouse_event->SetPositionInWidget(x, y); - mouse_event->movement_x *= scale; - mouse_event->movement_y *= scale; } else if (blink::WebInputEvent::IsTouchEventType(event.GetType())) { blink::WebTouchEvent* touch_event = new blink::WebTouchEvent; scaled_event.reset(touch_event);
diff --git a/ui/events/blink/blink_event_util_unittest.cc b/ui/events/blink/blink_event_util_unittest.cc index 0f89414..36c8082 100644 --- a/ui/events/blink/blink_event_util_unittest.cc +++ b/ui/events/blink/blink_event_util_unittest.cc
@@ -201,4 +201,19 @@ EXPECT_FALSE(CanCoalesce(event_to_be_coalesced, coalesced_event)); } +TEST(BlinkEventUtilTest, WebMouseMoveEventMovementNotChanged) { + blink::WebMouseEvent event(blink::WebInputEvent::kMouseMove, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::kTimeStampForTesting); + event.movement_x = 1; + event.movement_y = 1; + std::unique_ptr<blink::WebInputEvent> webEvent = + ScaleWebInputEvent(event, 2.f); + EXPECT_TRUE(webEvent); + blink::WebMouseEvent* mouseEvent = + static_cast<blink::WebMouseEvent*>(webEvent.get()); + EXPECT_EQ(1, mouseEvent->movement_x); + EXPECT_EQ(1, mouseEvent->movement_y); +} + } // namespace ui
diff --git a/ui/file_manager/file_manager/common/js/util.js b/ui/file_manager/file_manager/common/js/util.js index a9501b0..c002ef1 100644 --- a/ui/file_manager/file_manager/common/js/util.js +++ b/ui/file_manager/file_manager/common/js/util.js
@@ -735,28 +735,6 @@ }; /** - * Compares two entry arrays. - * @param {Array<!Entry>} entries1 The entry array to be compared. - * @param {Array<!Entry>} entries2 The entry array to be compared. - * @return {boolean} True if the both arrays contain same files or directories - * in the same order. Returns true if both arrays are null. - */ -util.isSameEntries = function(entries1, entries2) { - if (!entries1 && !entries2) - return true; - if (!entries1 || !entries2) - return false; - if (entries1.length !== entries2.length) - return false; - for (var i = 0; i < entries1.length; i++) { - if (!util.isSameEntry(entries1[i], entries2[i])) { - return false; - } - } - return true; -}; - -/** * Compares two file systems. * @param {FileSystem} fileSystem1 The file system to be compared. * @param {FileSystem} fileSystem2 The file system to be compared.
diff --git a/ui/file_manager/file_manager/foreground/elements/files_metadata_box.html b/ui/file_manager/file_manager/foreground/elements/files_metadata_box.html index 8656094..f0a3c467 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_metadata_box.html +++ b/ui/file_manager/file_manager/foreground/elements/files_metadata_box.html
@@ -7,39 +7,39 @@ <link rel="import" href="files_metadata_entry.html"> <dom-module id="files-metadata-box"> - <style> - div { - margin: 0; - padding: 0; - } - - div[hidden] { - display: none; - } - - #box { - display: block; - margin: 0; - overflow: auto; - padding: 0; - width: 320px; - } - - .category { - color: #E6E6E6; - font-size: 108%; - font-weight: 500; - margin: 12px 32px; - vertical-align: bottom; - } - - hr { - border-color: white; - margin-top: 31px; - opacity: 0.24; - } - </style> <template> + <style> + div { + margin: 0; + padding: 0; + } + + div[hidden] { + display: none; + } + + #box { + display: block; + margin: 0; + overflow: auto; + padding: 0; + width: 320px; + } + + .category { + color: #E6E6E6; + font-size: 108%; + font-weight: 500; + margin: 12px 32px; + vertical-align: bottom; + } + + hr { + border-color: white; + margin-top: 31px; + opacity: 0.24; + } + </style> <div id="box"> <div class="category" i18n-content="METADATA_BOX_GENERAL_INFO"></div> <files-metadata-entry i18n-values="key:METADATA_BOX_FILE_SIZE" value="[[size]]" loading="[[isSizeLoading]]"></files-metadata-entry>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_metadata_entry.html b/ui/file_manager/file_manager/foreground/elements/files_metadata_entry.html index e6b2bc22..d97b9a9 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_metadata_entry.html +++ b/ui/file_manager/file_manager/foreground/elements/files_metadata_entry.html
@@ -6,69 +6,69 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <dom-module id="files-metadata-entry"> - <style> - div { - margin: 0; - } - - #box { - display: flex; - margin: 12px 0; - min-height: 14px; - width: 320px; - } - - #box[hidden] { - display: none; - } - - #padding { - width: 32px; - } - - #key { - -webkit-margin-end: 32px; - color: white; - font-weight: 500; - overflow-wrap: break-word; - vertical-align: bottom; - width: 96px; - } - - #value { - color: white; - opacity: 0.8; - overflow-wrap: break-word; - vertical-align: bottom; - width: 128px; - } - - #value[loading] { - font-size: 30px; - } - - #value[loading]:after { - animation: ellipsis steps(4,end) 900ms infinite; - content: "\2026"; /* ascii code for the ellipsis character */ - display: inline-block; - overflow: hidden; - vertical-align: bottom; - width: 0px; - } - - @keyframes ellipsis { - to { - width: 1.25em; - } - } - - @keyframes ellipsis { - to { - width: 1.25em; - } - } - </style> <template> + <style> + div { + margin: 0; + } + + #box { + display: flex; + margin: 12px 0; + min-height: 14px; + width: 320px; + } + + #box[hidden] { + display: none; + } + + #padding { + width: 32px; + } + + #key { + -webkit-margin-end: 32px; + color: white; + font-weight: 500; + overflow-wrap: break-word; + vertical-align: bottom; + width: 96px; + } + + #value { + color: white; + opacity: 0.8; + overflow-wrap: break-word; + vertical-align: bottom; + width: 128px; + } + + #value[loading] { + font-size: 30px; + } + + #value[loading]:after { + animation: ellipsis steps(4,end) 900ms infinite; + content: "\2026"; /* ascii code for the ellipsis character */ + display: inline-block; + overflow: hidden; + vertical-align: bottom; + width: 0px; + } + + @keyframes ellipsis { + to { + width: 1.25em; + } + } + + @keyframes ellipsis { + to { + width: 1.25em; + } + } + </style> <div id="box" hidden="[[!value]]"> <div id="padding"></div> <div id="key">[[key]]</div>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_ripple.html b/ui/file_manager/file_manager/foreground/elements/files_ripple.html index 9e23b39f..6f2031d8 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_ripple.html +++ b/ui/file_manager/file_manager/foreground/elements/files_ripple.html
@@ -6,33 +6,33 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <dom-module id="files-ripple"> - <style> - :host { - align-items: center; - display: flex; - height: 200%; - left: -50%; - pointer-events: none; - position: absolute; - top: -50%; - width: 200%; - } - - .ripple { - background-color: white; - border-radius: 50%; - height: 50%; - margin: 0 auto; - opacity: 0; - width: 50%; - @apply(--files-ripple); - } - - :host([pressed]) .ripple { - opacity: 0.2; - } - </style> <template> + <style> + :host { + align-items: center; + display: flex; + height: 200%; + left: -50%; + pointer-events: none; + position: absolute; + top: -50%; + width: 200%; + } + + .ripple { + background-color: white; + border-radius: 50%; + height: 50%; + margin: 0 auto; + opacity: 0; + width: 50%; + @apply(--files-ripple); + } + + :host([pressed]) .ripple { + opacity: 0.2; + } + </style> <div id="ripple" class="ripple"></div> </template> </dom-module>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_safe_media.html b/ui/file_manager/file_manager/foreground/elements/files_safe_media.html index 29a6528..0d0f4710 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_safe_media.html +++ b/ui/file_manager/file_manager/foreground/elements/files_safe_media.html
@@ -4,21 +4,21 @@ --> <dom-module id="files-safe-media"> - <style> - #content { - height: 100%; - width: 100%; - } - #content.audio { - height: 32px; - } - webview { - display: inline-block; - height: 100%; - width: 100%; - } - </style> <template> + <style> + #content { + height: 100%; + width: 100%; + } + #content.audio { + height: 32px; + } + webview { + display: inline-block; + height: 100%; + width: 100%; + } + </style> <div id="content" class$="[[type]]"></div> </template> </dom-module>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_toast.html b/ui/file_manager/file_manager/foreground/elements/files_toast.html index 4042e4f..1457448 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_toast.html +++ b/ui/file_manager/file_manager/foreground/elements/files_toast.html
@@ -6,41 +6,41 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <dom-module id="files-toast"> - <style> - .container { - background: rgb(50, 50, 50); - bottom: 16px; - display: flex; - min-width: 360px; - padding: 20px 24px; - position: absolute; - } - - .container[hidden] { - display: none; - } - - :host-context(html[dir='ltr']) .container { - right: 16px; - } - - :host-context(html[dir='rtl']) .container { - left: 16px; - } - - .text { - color: white; - flex-grow: 1; - } - - .action { - -webkit-margin-start: 8px; - color: rgb(97, 203, 255); - cursor: pointer; - font-weight: bold; - } - </style> <template> + <style> + .container { + background: rgb(50, 50, 50); + bottom: 16px; + display: flex; + min-width: 360px; + padding: 20px 24px; + position: absolute; + } + + .container[hidden] { + display: none; + } + + :host-context(html[dir='ltr']) .container { + right: 16px; + } + + :host-context(html[dir='rtl']) .container { + left: 16px; + } + + .text { + color: white; + flex-grow: 1; + } + + .action { + -webkit-margin-start: 8px; + color: rgb(97, 203, 255); + cursor: pointer; + font-weight: bold; + } + </style> <div class="container" id="container" hidden> <div class="text" id="text"></div> <div class="action" id="action" on-tap="onActionTapped_"></div>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_toggle_ripple.html b/ui/file_manager/file_manager/foreground/elements/files_toggle_ripple.html index 9f8ab18..1ee57d5 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_toggle_ripple.html +++ b/ui/file_manager/file_manager/foreground/elements/files_toggle_ripple.html
@@ -6,43 +6,43 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <dom-module id="files-toggle-ripple"> - <style> - :host { - display: block; - height: 100%; - position: relative; - width: 100%; - } - - .ripple-container { - align-items: center; - display: flex; - height: 200%; - left: -50%; - pointer-events: none; - position: absolute; - top: -50%; - width: 200%; - } - - .ripple { - background-color: white; - height: 0; - margin: 0 auto; - opacity: 0; - width: 0; - @apply(--files-toggle-ripple); - } - - .ripple.activated { - border-radius: 2px; - height: 50%; - opacity: 0.2; - width: 50%; - @apply(--files-toggle-ripple-activated); - } - </style> <template> + <style> + :host { + display: block; + height: 100%; + position: relative; + width: 100%; + } + + .ripple-container { + align-items: center; + display: flex; + height: 200%; + left: -50%; + pointer-events: none; + position: absolute; + top: -50%; + width: 200%; + } + + .ripple { + background-color: white; + height: 0; + margin: 0 auto; + opacity: 0; + width: 0; + @apply(--files-toggle-ripple); + } + + .ripple.activated { + border-radius: 2px; + height: 50%; + opacity: 0.2; + width: 50%; + @apply(--files-toggle-ripple-activated); + } + </style> <div class="ripple-container"> <div class="ripple" id="ripple"></div> </div>
diff --git a/ui/file_manager/file_manager/foreground/elements/files_tooltip.html b/ui/file_manager/file_manager/foreground/elements/files_tooltip.html index 7126931..93f9bce 100644 --- a/ui/file_manager/file_manager/foreground/elements/files_tooltip.html +++ b/ui/file_manager/file_manager/foreground/elements/files_tooltip.html
@@ -6,31 +6,31 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <dom-module id="files-tooltip"> - <style> - :host { - opacity: 0; - padding: 4px 6px 0; - pointer-events: none; - position: absolute; - transition: opacity 300ms; - z-index: 1000; - } - - :host([visible]) { - opacity: .9; - } - - :host > #label { - background-color: #323232; - border-radius: 2px; - color: white; - font-size: 12px; - line-height: 28px; - padding: 0 14px; - white-space: nowrap; - } - </style> <template> + <style> + :host { + opacity: 0; + padding: 4px 6px 0; + pointer-events: none; + position: absolute; + transition: opacity 300ms; + z-index: 1000; + } + + :host([visible]) { + opacity: .9; + } + + :host > #label { + background-color: #323232; + border-radius: 2px; + color: white; + font-size: 12px; + line-height: 28px; + padding: 0 14px; + white-space: nowrap; + } + </style> <div id="label"></div> </template> </dom-module>
diff --git a/ui/file_manager/file_manager/foreground/js/file_tasks.js b/ui/file_manager/file_manager/foreground/js/file_tasks.js index 3fc916d..d40eb336 100644 --- a/ui/file_manager/file_manager/foreground/js/file_tasks.js +++ b/ui/file_manager/file_manager/foreground/js/file_tasks.js
@@ -68,15 +68,6 @@ this.defaultTask_ = defaultTask; }; -FileTasks.prototype = { - /** - * @return {!Array<!Entry>} - */ - get entries() { - return this.entries_; - } -}; - /** * The app ID of the video player app. * @const
diff --git a/ui/file_manager/file_manager/foreground/js/task_controller.js b/ui/file_manager/file_manager/foreground/js/task_controller.js index c7457d1..a703d14c 100644 --- a/ui/file_manager/file_manager/foreground/js/task_controller.js +++ b/ui/file_manager/file_manager/foreground/js/task_controller.js
@@ -90,11 +90,6 @@ */ this.tasks_ = null; - /** - * @private {!Array<!Entry>} - */ - this.lastSelectedEntries_ = []; - ui.taskMenuButton.addEventListener( 'select', this.onTaskItemClicked_.bind(this)); this.selectionHandler_.addEventListener( @@ -267,23 +262,20 @@ * @private */ TaskController.prototype.onSelectionChanged_ = function() { + this.tasks_ = null; var selection = this.selectionHandler_.selection; // Caller of update context menu task items. // FileSelectionHandler.EventType.CHANGE if (this.dialogType_ === DialogType.FULL_PAGE && (selection.directoryCount > 0 || selection.fileCount > 0)) { - // Compare entries while ignoring changes inside directories. - if (!util.isSameEntries(this.lastSelectedEntries_, selection.entries)) { - // Show disabled items for position calculation of the menu. They will be - // overridden in this.updateTasks_(). - this.updateContextMenuTaskItems_( - [TaskController.createTemporaryDisabledTaskItem_()]); - } + // Show disabled items for position calculation of the menu. They will be + // overridden in this.updateFileSelectionAsync(). + this.updateContextMenuTaskItems_( + [TaskController.createTemporaryDisabledTaskItem_()]); } else { // Update context menu. this.updateContextMenuTaskItems_([]); } - this.lastSelectedEntries_ = selection.entries; }; /** @@ -294,36 +286,15 @@ var selection = this.selectionHandler_.selection; if (this.dialogType_ === DialogType.FULL_PAGE && (selection.directoryCount > 0 || selection.fileCount > 0)) { - var previousFileTasksInvalidatePromise = new Promise(function(resolve) { - if (this.tasks_) { - this.getFileTasks() - .then(function(tasks) { - if (!util.isSameEntries(tasks.entries, selection.entries)) { - this.tasks_ = null; - } - resolve(); - }.bind(this)) - .catch(function(error) { - if (error) - console.log(error.stack || error); - this.tasks_ = null; - resolve(); - }.bind(this)); - } else { - resolve(); - } - }.bind(this)); - previousFileTasksInvalidatePromise.then(function() { - this.getFileTasks() - .then(function(tasks) { - tasks.display(this.ui_.taskMenuButton); - this.updateContextMenuTaskItems_(tasks.getTaskItems()); - }.bind(this)) - .catch(function(error) { - if (error) - console.error(error.stack || error); - }); - }.bind(this)); + this.getFileTasks() + .then(function(tasks) { + tasks.display(this.ui_.taskMenuButton); + this.updateContextMenuTaskItems_(tasks.getTaskItems()); + }.bind(this)) + .catch(function(error) { + if (error) + console.error(error.stack || error); + }); } else { this.ui_.taskMenuButton.hidden = true; } @@ -338,21 +309,19 @@ return this.tasks_; var selection = this.selectionHandler_.selection; - return this.tasks_ = - selection.computeAdditional(this.metadataModel_).then(function() { - if (this.selectionHandler_.selection !== selection) - return Promise.reject(); - return FileTasks - .create( - this.volumeManager_, this.metadataModel_, - this.directoryModel_, this.ui_, selection.entries, - assert(selection.mimeTypes)) - .then(function(tasks) { - if (this.selectionHandler_.selection !== selection) - return Promise.reject(); - return tasks; - }.bind(this)); - }.bind(this)); + return selection.computeAdditional(this.metadataModel_).then( + function() { + if (this.selectionHandler_.selection !== selection) + return Promise.reject(); + return FileTasks.create( + this.volumeManager_, this.metadataModel_, this.directoryModel_, + this.ui_, selection.entries, assert(selection.mimeTypes)). + then(function(tasks) { + if (this.selectionHandler_.selection !== selection) + return Promise.reject(); + return tasks; + }.bind(this)); + }.bind(this)); }; /**
diff --git a/ui/file_manager/video_player/js/background.js b/ui/file_manager/video_player/js/background.js index 3df0cdb1..37e50707 100644 --- a/ui/file_manager/video_player/js/background.js +++ b/ui/file_manager/video_player/js/background.js
@@ -79,6 +79,10 @@ }.wrap()).then(function(videoPlayer) { var appWindow = videoPlayer.rawAppWindow; + appWindow.onClosed.addListener(function() { + chrome.power.releaseKeepAwake(); + }); + if (chrome.test) appWindow.contentWindow.loadMockCastExtensionForTest = true;
diff --git a/ui/gfx/render_text.cc b/ui/gfx/render_text.cc index dfac164..ebae2fb 100644 --- a/ui/gfx/render_text.cc +++ b/ui/gfx/render_text.cc
@@ -54,12 +54,13 @@ // Default color used for drawing selection background. const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY; -// Fraction of the text size to lower a strike through below the baseline. -const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21); +// Fraction of the text size to raise the center of a strike-through line above +// the baseline. +const SkScalar kStrikeThroughOffset = (SK_Scalar1 * 65 / 252); // Fraction of the text size to lower an underline below the baseline. const SkScalar kUnderlineOffset = (SK_Scalar1 / 9); -// Fraction of the text size to use for a strike through or under-line. -const SkScalar kLineThickness = (SK_Scalar1 / 18); +// Default fraction of the text size to use for a strike-through or underline. +const SkScalar kLineThicknessFactor = (SK_Scalar1 / 18); // Invalid value of baseline. Assigning this value to |baseline_| causes // re-calculation of baseline. @@ -188,15 +189,8 @@ namespace internal { -// Value of |underline_thickness_| that indicates that underline metrics have -// not been set explicitly. -const SkScalar kUnderlineMetricsNotSet = -1.0f; - SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas) - : canvas_(canvas), - canvas_skia_(canvas->sk_canvas()), - underline_thickness_(kUnderlineMetricsNotSet), - underline_position_(0.0f) { + : canvas_(canvas), canvas_skia_(canvas->sk_canvas()) { DCHECK(canvas_skia_); flags_.setTextEncoding(cc::PaintFlags::kGlyphID_TextEncoding); flags_.setStyle(cc::PaintFlags::kFill_Style); @@ -234,12 +228,6 @@ flags_.setShader(std::move(shader)); } -void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness, - SkScalar position) { - underline_thickness_ = thickness; - underline_position_ = position; -} - void SkiaTextRenderer::DrawPosText(const SkPoint* pos, const uint16_t* glyphs, size_t glyph_count) { @@ -247,37 +235,25 @@ canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], flags_); } -void SkiaTextRenderer::DrawDecorations(int x, - int y, - int width, - bool underline, - bool strike) { - if (underline) - DrawUnderline(x, y, width); - if (strike) - DrawStrike(x, y, width); -} - void SkiaTextRenderer::DrawUnderline(int x, int y, int width) { SkScalar x_scalar = SkIntToScalar(x); + const SkScalar text_size = flags_.getTextSize(); SkRect r = SkRect::MakeLTRB( - x_scalar, y + underline_position_, x_scalar + width, - y + underline_position_ + underline_thickness_); - if (underline_thickness_ == kUnderlineMetricsNotSet) { - const SkScalar text_size = flags_.getTextSize(); - r.fTop = text_size * kUnderlineOffset + y; - r.fBottom = r.fTop + text_size * kLineThickness; - } + x_scalar, y + text_size * kUnderlineOffset, x_scalar + width, + y + (text_size * (kUnderlineOffset + kLineThicknessFactor))); canvas_skia_->drawRect(r, flags_); } -void SkiaTextRenderer::DrawStrike(int x, int y, int width) const { +void SkiaTextRenderer::DrawStrike(int x, + int y, + int width, + SkScalar thickness_factor) { const SkScalar text_size = flags_.getTextSize(); - const SkScalar height = text_size * kLineThickness; - const SkScalar offset = text_size * kStrikeThroughOffset + y; + const SkScalar height = text_size * thickness_factor; + const SkScalar top = y - text_size * kStrikeThroughOffset - height / 2; SkScalar x_scalar = SkIntToScalar(x); const SkRect r = - SkRect::MakeLTRB(x_scalar, offset, x_scalar + width, offset + height); + SkRect::MakeLTRB(x_scalar, top, x_scalar + width, top + height); canvas_skia_->drawRect(r, flags_); } @@ -1006,7 +982,8 @@ subpixel_rendering_suppressed_(false), clip_to_display_rect_(true), baseline_(kInvalidBaseline), - cached_bounds_and_offset_valid_(false) {} + cached_bounds_and_offset_valid_(false), + strike_thickness_factor_(kLineThicknessFactor) {} SelectionModel RenderText::GetAdjacentSelectionModel( const SelectionModel& current,
diff --git a/ui/gfx/render_text.h b/ui/gfx/render_text.h index 508f50ce..d912882 100644 --- a/ui/gfx/render_text.h +++ b/ui/gfx/render_text.h
@@ -63,24 +63,12 @@ void SetTextSize(SkScalar size); void SetForegroundColor(SkColor foreground); void SetShader(std::unique_ptr<cc::PaintShader> shader); - // Sets underline metrics to use if the text will be drawn with an underline. - // If not set, default values based on the size of the text will be used. The - // two metrics must be set together. - void SetUnderlineMetrics(SkScalar thickness, SkScalar position); void DrawSelection(const std::vector<Rect>& selection, SkColor color); virtual void DrawPosText(const SkPoint* pos, const uint16_t* glyphs, size_t glyph_count); - // Draw underline and strike-through text decorations. - // Based on |SkCanvas::DrawTextDecorations()| and constants from: - // third_party/skia/src/core/SkTextFormatParams.h - virtual void DrawDecorations(int x, - int y, - int width, - bool underline, - bool strike); void DrawUnderline(int x, int y, int width); - void DrawStrike(int x, int y, int width) const; + void DrawStrike(int x, int y, int width, SkScalar thickness_factor); private: friend class test::RenderTextTestApi; @@ -88,8 +76,6 @@ Canvas* canvas_; cc::PaintCanvas* canvas_skia_; cc::PaintFlags flags_; - SkScalar underline_thickness_; - SkScalar underline_position_; DISALLOW_COPY_AND_ASSIGN(SkiaTextRenderer); }; @@ -500,6 +486,8 @@ // Retrieves the text in the given |range|. base::string16 GetTextFromRange(const Range& range) const; + void set_strike_thickness_factor(SkScalar f) { strike_thickness_factor_ = f; } + protected: RenderText(); @@ -513,6 +501,7 @@ const BreakList<BaselineStyle>& baselines() const { return baselines_; } const BreakList<Font::Weight>& weights() const { return weights_; } const std::vector<BreakList<bool> >& styles() const { return styles_; } + SkScalar strike_thickness_factor() const { return strike_thickness_factor_; } const std::vector<internal::Line>& lines() const { return lines_; } void set_lines(std::vector<internal::Line>* lines) { lines_.swap(*lines); } @@ -835,6 +824,9 @@ // OnLayoutTextAttributeChanged and OnDisplayTextAttributeChanged calls. std::vector<internal::Line> lines_; + // The ratio of strike-through line thickness to text height. + SkScalar strike_thickness_factor_; + DISALLOW_COPY_AND_ASSIGN(RenderText); };
diff --git a/ui/gfx/render_text_harfbuzz.cc b/ui/gfx/render_text_harfbuzz.cc index 97dcfec..2f028621 100644 --- a/ui/gfx/render_text_harfbuzz.cc +++ b/ui/gfx/render_text_harfbuzz.cc
@@ -1316,8 +1316,11 @@ ? (SkFloatToScalar(segment.width()) + preceding_segment_widths + SkIntToScalar(origin.x())) : positions[colored_glyphs.end() - glyphs_range.start()].x()); - renderer->DrawDecorations(start_x, origin.y(), end_x - start_x, - run.underline, run.strike); + if (run.underline) + renderer->DrawUnderline(start_x, origin.y(), end_x - start_x); + if (run.strike) + renderer->DrawStrike(start_x, origin.y(), end_x - start_x, + strike_thickness_factor()); } preceding_segment_widths += SkFloatToScalar(segment.width()); }
diff --git a/ui/gfx/render_text_mac.mm b/ui/gfx/render_text_mac.mm index 6705817..2618450 100644 --- a/ui/gfx/render_text_mac.mm +++ b/ui/gfx/render_text_mac.mm
@@ -259,8 +259,11 @@ renderer->DrawPosText(&run.glyph_positions[0], &run.glyphs[0], run.glyphs.size()); - renderer->DrawDecorations(run.origin.x(), run.origin.y(), run.width, - run.underline, run.strike); + if (run.underline) + renderer->DrawUnderline(run.origin.x(), run.origin.y(), run.width); + if (run.strike) + renderer->DrawStrike(run.origin.x(), run.origin.y(), run.width, + strike_thickness_factor()); } }
diff --git a/ui/gfx/render_text_unittest.cc b/ui/gfx/render_text_unittest.cc index 7081122..ad7e8b2 100644 --- a/ui/gfx/render_text_unittest.cc +++ b/ui/gfx/render_text_unittest.cc
@@ -336,16 +336,6 @@ SkColor color; }; - struct DecorationLog { - DecorationLog(int x, int y, int width, bool underline, bool strike) - : x(x), y(y), width(width), underline(underline), strike(strike) {} - int x; - int y; - int width; - bool underline; - bool strike; - }; - explicit TestSkiaTextRenderer(Canvas* canvas) : internal::SkiaTextRenderer(canvas) {} ~TestSkiaTextRenderer() override {} @@ -355,11 +345,6 @@ text_log_.clear(); } - void GetDecorationLogAndReset(std::vector<DecorationLog>* decoration_log) { - decoration_log_.swap(*decoration_log); - decoration_log_.clear(); - } - private: // internal::SkiaTextRenderer: void DrawPosText(const SkPoint* pos, @@ -381,17 +366,7 @@ internal::SkiaTextRenderer::DrawPosText(pos, glyphs, glyph_count); } - void DrawDecorations(int x, - int y, - int width, - bool underline, - bool strike) override { - decoration_log_.push_back(DecorationLog(x, y, width, underline, strike)); - internal::SkiaTextRenderer::DrawDecorations(x, y, width, underline, strike); - } - std::vector<TextLog> text_log_; - std::vector<DecorationLog> decoration_log_; DISALLOW_COPY_AND_ASSIGN(TestSkiaTextRenderer); };
diff --git a/ui/login/account_picker/md_user_pod_row.js b/ui/login/account_picker/md_user_pod_row.js index c3931221..30448fb8 100644 --- a/ui/login/account_picker/md_user_pod_row.js +++ b/ui/login/account_picker/md_user_pod_row.js
@@ -1780,11 +1780,14 @@ // Show extra statistics information for desktop users this.querySelector( '.action-box-remove-non-owner-user-warning-text').hidden = true; - this.RemoveWarningDialogSetMessage_(true, false); + this.RemoveWarningDialogSetMessage_(); // set a global handler for the callback window.updateRemoveWarningDialog = this.updateRemoveWarningDialog_.bind(this); - chrome.send('removeUserWarningLoadStats', [this.user.profilePath]); + var is_synced_user = this.user.emailAddress !== ""; + if (!is_synced_user) { + chrome.send('removeUserWarningLoadStats', [this.user.profilePath]); + } } chrome.send('logRemoveUserWarningShown'); }, @@ -1800,78 +1803,23 @@ var stats_elements = this.statsMapElements; // Update individual statistics - var hasErrors = false; for (var key in profileStats) { if (stats_elements.hasOwnProperty(key)) { - if (profileStats[key].success) { - this.user.statistics[key] = profileStats[key]; - } else if (!this.user.statistics[key].success) { - hasErrors = true; - stats_elements[key].textContent = ''; - } + stats_elements[key].textContent = profileStats[key].count; } } - - this.RemoveWarningDialogSetMessage_(false, hasErrors); }, /** * Set the new message in the dialog. - * @param {boolean} Whether this is the first output, that requires setting - * a in-progress message. - * @param {boolean} Whether any actual query to the statistics have failed. - * Should be true only if there is an error and the corresponding statistic - * is also unavailable in ProfileAttributesStorage. */ - RemoveWarningDialogSetMessage_: function(isInitial, hasErrors) { - var stats_elements = this.statsMapElements; - var total_count = 0; - var num_stats_loaded = 0; - for (var key in stats_elements) { - if (this.user.statistics[key].success) { - var count = this.user.statistics[key].count; - stats_elements[key].textContent = count; - total_count += count; - num_stats_loaded++; - } - } - + RemoveWarningDialogSetMessage_: function() { var is_synced_user = this.user.emailAddress !== ""; - // Write total number if all statistics are loaded. - if (num_stats_loaded === Object.keys(stats_elements).length) { - if (!total_count) { - var message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncNoStats' : - 'removeUserWarningTextNonSyncNoStats'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message); - } else { - window.updateRemoveWarningDialogSetMessage = - this.updateRemoveWarningDialogSetMessage_.bind(this); - chrome.send('getRemoveWarningDialogMessage',[{ - profilePath: this.user.profilePath, - isSyncedUser: is_synced_user, - hasErrors: hasErrors, - totalCount: total_count - }]); - } - } else if (isInitial) { - if (!this.user.isProfileLoaded) { - message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncNoStats' : - 'removeUserWarningTextNonSyncNoStats'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message); - } else { - message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncCalculating' : - 'removeUserWarningTextNonSyncCalculating'); - substitute = loadTimeData.getString( - 'removeUserWarningTextCalculating'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message, substitute); - } - } + message = loadTimeData.getString( + is_synced_user ? 'removeUserWarningTextSync' : + 'removeUserWarningTextNonSync'); + this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, + message); }, /**
diff --git a/ui/login/account_picker/user_pod_row.js b/ui/login/account_picker/user_pod_row.js index 9ef5e41..1aef5de 100644 --- a/ui/login/account_picker/user_pod_row.js +++ b/ui/login/account_picker/user_pod_row.js
@@ -1715,11 +1715,14 @@ // Show extra statistics information for desktop users this.querySelector( '.action-box-remove-non-owner-user-warning-text').hidden = true; - this.RemoveWarningDialogSetMessage_(true, false); + this.RemoveWarningDialogSetMessage_(); // set a global handler for the callback window.updateRemoveWarningDialog = this.updateRemoveWarningDialog_.bind(this); - chrome.send('removeUserWarningLoadStats', [this.user.profilePath]); + var is_synced_user = this.user.emailAddress !== ""; + if (!is_synced_user) { + chrome.send('removeUserWarningLoadStats', [this.user.profilePath]); + } } chrome.send('logRemoveUserWarningShown'); }, @@ -1735,78 +1738,23 @@ var stats_elements = this.statsMapElements; // Update individual statistics - var hasErrors = false; for (var key in profileStats) { if (stats_elements.hasOwnProperty(key)) { - if (profileStats[key].success) { - this.user.statistics[key] = profileStats[key]; - } else if (!this.user.statistics[key].success) { - hasErrors = true; - stats_elements[key].textContent = ''; - } + stats_elements[key].textContent = profileStats[key].count; } } - - this.RemoveWarningDialogSetMessage_(false, hasErrors); }, /** * Set the new message in the dialog. - * @param {boolean} Whether this is the first output, that requires setting - * a in-progress message. - * @param {boolean} Whether any actual query to the statistics have failed. - * Should be true only if there is an error and the corresponding statistic - * is also unavailable in ProfileAttributesStorage. */ - RemoveWarningDialogSetMessage_: function(isInitial, hasErrors) { - var stats_elements = this.statsMapElements; - var total_count = 0; - var num_stats_loaded = 0; - for (var key in stats_elements) { - if (this.user.statistics[key].success) { - var count = this.user.statistics[key].count; - stats_elements[key].textContent = count; - total_count += count; - num_stats_loaded++; - } - } - + RemoveWarningDialogSetMessage_: function() { var is_synced_user = this.user.emailAddress !== ""; - // Write total number if all statistics are loaded. - if (num_stats_loaded === Object.keys(stats_elements).length) { - if (!total_count) { - var message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncNoStats' : - 'removeUserWarningTextNonSyncNoStats'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message); - } else { - window.updateRemoveWarningDialogSetMessage = - this.updateRemoveWarningDialogSetMessage_.bind(this); - chrome.send('getRemoveWarningDialogMessage',[{ - profilePath: this.user.profilePath, - isSyncedUser: is_synced_user, - hasErrors: hasErrors, - totalCount: total_count - }]); - } - } else if (isInitial) { - if (!this.user.isProfileLoaded) { - message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncNoStats' : - 'removeUserWarningTextNonSyncNoStats'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message); - } else { - message = loadTimeData.getString( - is_synced_user ? 'removeUserWarningTextSyncCalculating' : - 'removeUserWarningTextNonSyncCalculating'); - substitute = loadTimeData.getString( - 'removeUserWarningTextCalculating'); - this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, - message, substitute); - } - } + message = loadTimeData.getString( + is_synced_user ? 'removeUserWarningTextSync' : + 'removeUserWarningTextNonSync'); + this.updateRemoveWarningDialogSetMessage_(this.user.profilePath, + message); }, /**
diff --git a/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc b/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc index 290915b2..b0898a6 100644 --- a/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc +++ b/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc
@@ -76,7 +76,7 @@ } // namespace -TEST_F(AXSystemCaretWinTest, TestOnCaretBoundsChangeInTextField) { +TEST_F(AXSystemCaretWinTest, DISABLED_TestOnCaretBoundsChangeInTextField) { TextfieldTestApi textfield_test_api(textfield_); base::win::ScopedComPtr<IAccessible> caret_accessible; gfx::NativeWindow native_window = widget_->GetNativeWindow(); @@ -107,7 +107,7 @@ EXPECT_EQ(1, width); } -TEST_F(AXSystemCaretWinTest, TestOnInputTypeChangeInTextField) { +TEST_F(AXSystemCaretWinTest, DISABLED_TestOnInputTypeChangeInTextField) { base::win::ScopedComPtr<IAccessible> caret_accessible; gfx::NativeWindow native_window = widget_->GetNativeWindow(); ASSERT_NE(nullptr, native_window);
diff --git a/ui/views/cocoa/bridged_content_view.mm b/ui/views/cocoa/bridged_content_view.mm index 46e34d8..e300b7e 100644 --- a/ui/views/cocoa/bridged_content_view.mm +++ b/ui/views/cocoa/bridged_content_view.mm
@@ -530,6 +530,8 @@ ui::EF_NONE); [self handleKeyEvent:&charEvent]; hasUnhandledKeyDownEvent_ = NO; + if (charEvent.handled()) + return; } // Forward the |text| to |textInputClient_| if no menu is active.
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index 5edb560..ac2599a 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -970,6 +970,7 @@ bounds.Inset(gfx::Insets(0, kTextPadding, 0, kTextPadding)); GetRenderText()->SetDisplayRect(bounds); OnCaretBoundsChanged(); + UpdateCursorViewPosition(); } bool Textfield::GetNeedsNotificationWhenVisibleBoundsChange() const { @@ -2115,8 +2116,8 @@ void Textfield::OnCursorBlinkTimerFired() { DCHECK(ShouldBlinkCursor()); - cursor_view_.SetVisible(!cursor_view_.visible()); UpdateCursorViewPosition(); + cursor_view_.SetVisible(!cursor_view_.visible()); } } // namespace views
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 9d44b48..7b49cf5 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -182,7 +182,7 @@ dispatch_details = DispatchKeyEventPostIME(key); } - if (dispatch_details.dispatcher_destroyed) + if (key->handled() || dispatch_details.dispatcher_destroyed) return dispatch_details; ui::TextInputClient* client = GetTextInputClient(); @@ -348,6 +348,29 @@ std::unique_ptr<views::Textfield> target_; }; +// Class that focuses a textfield when it sees a KeyDown event. +class TextfieldFocuser : public views::View { + public: + explicit TextfieldFocuser(views::Textfield* textfield) + : textfield_(textfield) { + SetFocusBehavior(FocusBehavior::ALWAYS); + } + + void set_consume(bool consume) { consume_ = consume; } + + // View: + bool OnKeyPressed(const ui::KeyEvent& event) override { + textfield_->RequestFocus(); + return consume_; + } + + private: + bool consume_ = true; + views::Textfield* textfield_; + + DISALLOW_COPY_AND_ASSIGN(TextfieldFocuser); +}; + base::string16 GetClipboardText(ui::ClipboardType type) { base::string16 text; ui::Clipboard::GetForCurrentThread()->ReadText(type, &text); @@ -3168,4 +3191,57 @@ EXPECT_TRUE(test_api_->IsCursorVisible()); } +// Check if the text cursor is always at the end of the textfield after the +// text overflows from the textfield. If the textfield size changes, check if +// the text cursor's location is updated accordingly. +TEST_F(TextfieldTest, TextfieldBoundsChangeTest) { + InitTextfield(); + gfx::Size new_size = gfx::Size(30, 100); + textfield_->SetSize(new_size); + + // Insert chars in |textfield_| to make it overflow. + SendKeyEvent('a'); + SendKeyEvent('a'); + SendKeyEvent('a'); + SendKeyEvent('a'); + SendKeyEvent('a'); + SendKeyEvent('a'); + SendKeyEvent('a'); + + // Check if the cursor continues pointing to the end of the textfield. + int prev_x = GetCursorBounds().x(); + SendKeyEvent('a'); + EXPECT_EQ(prev_x, GetCursorBounds().x()); + + // Increase the textfield size and check if the cursor moves to the new end. + textfield_->SetSize(gfx::Size(40, 100)); + EXPECT_LT(prev_x, GetCursorBounds().x()); + + prev_x = GetCursorBounds().x(); + // Decrease the textfield size and check if the cursor moves to the new end. + textfield_->SetSize(gfx::Size(30, 100)); + EXPECT_GT(prev_x, GetCursorBounds().x()); +} + +// Verify that if a textfield gains focus during key dispatch that an edit +// command only results when the event is not consumed. +TEST_F(TextfieldTest, SwitchFocusInKeyDown) { + InitTextfield(); + TextfieldFocuser* focuser = new TextfieldFocuser(textfield_); + widget_->GetContentsView()->AddChildView(focuser); + + focuser->RequestFocus(); + EXPECT_EQ(focuser, GetFocusedView()); + SendKeyPress(ui::VKEY_SPACE, 0); + EXPECT_EQ(textfield_, GetFocusedView()); + EXPECT_EQ(base::string16(), textfield_->text()); + + focuser->set_consume(false); + focuser->RequestFocus(); + EXPECT_EQ(focuser, GetFocusedView()); + SendKeyPress(ui::VKEY_SPACE, 0); + EXPECT_EQ(textfield_, GetFocusedView()); + EXPECT_EQ(base::ASCIIToUTF16(" "), textfield_->text()); +} + } // namespace views
diff --git a/ui/views/mus/aura_init.cc b/ui/views/mus/aura_init.cc index f53872d..ec0bb006 100644 --- a/ui/views/mus/aura_init.cc +++ b/ui/views/mus/aura_init.cc
@@ -52,40 +52,9 @@ } // namespace -AuraInit::AuraInit(service_manager::Connector* connector, - const service_manager::Identity& identity, - const std::string& resource_file, - const std::string& resource_file_200, - scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, - Mode mode) - : resource_file_(resource_file), - resource_file_200_(resource_file_200), - env_(aura::Env::CreateInstance( - (mode == Mode::AURA_MUS || mode == Mode::AURA_MUS_WINDOW_MANAGER) - ? aura::Env::Mode::MUS - : aura::Env::Mode::LOCAL)) { +AuraInit::AuraInit() { if (!ViewsDelegate::GetInstance()) views_delegate_ = base::MakeUnique<MusViewsDelegate>(); - if (mode == Mode::AURA_MUS) { - mus_client_ = - base::WrapUnique(new MusClient(connector, identity, io_task_runner)); - } - ui::MaterialDesignController::Initialize(); - if (!InitializeResources(connector)) - return; - -// Initialize the skia font code to go ask fontconfig underneath. -#if defined(OS_LINUX) - font_loader_ = sk_make_sp<font_service::FontLoader>(connector); - SkFontConfigInterface::SetGlobal(font_loader_.get()); -#endif - - // There is a bunch of static state in gfx::Font, by running this now, - // before any other apps load, we ensure all the state is set up. - gfx::Font(); - - ui::InitializeInputMethodForTesting(); - initialized_ = true; } AuraInit::~AuraInit() { @@ -100,15 +69,65 @@ #endif } -bool AuraInit::InitializeResources(service_manager::Connector* connector) { +std::unique_ptr<AuraInit> AuraInit::Create( + service_manager::Connector* connector, + const service_manager::Identity& identity, + const std::string& resource_file, + const std::string& resource_file_200, + scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, + Mode mode) { + std::unique_ptr<AuraInit> aura_init = base::WrapUnique(new AuraInit()); + if (!aura_init->Init(connector, identity, resource_file, resource_file_200, + io_task_runner, mode)) { + aura_init.reset(); + } + return aura_init; +} + +bool AuraInit::Init(service_manager::Connector* connector, + const service_manager::Identity& identity, + const std::string& resource_file, + const std::string& resource_file_200, + scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, + Mode mode) { + env_ = aura::Env::CreateInstance( + (mode == Mode::AURA_MUS || mode == Mode::AURA_MUS_WINDOW_MANAGER) + ? aura::Env::Mode::MUS + : aura::Env::Mode::LOCAL); + + if (mode == Mode::AURA_MUS) { + mus_client_ = + base::WrapUnique(new MusClient(connector, identity, io_task_runner)); + } + ui::MaterialDesignController::Initialize(); + if (!InitializeResources(connector, resource_file, resource_file_200)) + return false; + +// Initialize the skia font code to go ask fontconfig underneath. +#if defined(OS_LINUX) + font_loader_ = sk_make_sp<font_service::FontLoader>(connector); + SkFontConfigInterface::SetGlobal(font_loader_.get()); +#endif + + // There is a bunch of static state in gfx::Font, by running this now, + // before any other apps load, we ensure all the state is set up. + gfx::Font(); + + ui::InitializeInputMethodForTesting(); + return true; +} + +bool AuraInit::InitializeResources(service_manager::Connector* connector, + const std::string& resource_file, + const std::string& resource_file_200) { // Resources may have already been initialized (e.g. when 'chrome --mash' is // used to launch the current app). if (ui::ResourceBundle::HasSharedInstance()) return false; - std::set<std::string> resource_paths({resource_file_}); - if (!resource_file_200_.empty()) - resource_paths.insert(resource_file_200_); + std::set<std::string> resource_paths({resource_file}); + if (!resource_file_200.empty()) + resource_paths.insert(resource_file_200); catalog::ResourceLoader loader; filesystem::mojom::DirectoryPtr directory; @@ -123,15 +142,15 @@ if (!loader.OpenFiles(std::move(directory), resource_paths)) return false; ui::RegisterPathProvider(); - base::File pak_file = loader.TakeFile(resource_file_); + base::File pak_file = loader.TakeFile(resource_file); base::File pak_file_2 = pak_file.Duplicate(); ui::ResourceBundle::InitSharedInstanceWithPakFileRegion( std::move(pak_file), base::MemoryMappedFile::Region::kWholeFile); ui::ResourceBundle::GetSharedInstance().AddDataPackFromFile( std::move(pak_file_2), ui::SCALE_FACTOR_100P); - if (!resource_file_200_.empty()) + if (!resource_file_200.empty()) ui::ResourceBundle::GetSharedInstance().AddDataPackFromFile( - loader.TakeFile(resource_file_200_), ui::SCALE_FACTOR_200P); + loader.TakeFile(resource_file_200), ui::SCALE_FACTOR_200P); return true; }
diff --git a/ui/views/mus/aura_init.h b/ui/views/mus/aura_init.h index 15deb095..2ba6fd2 100644 --- a/ui/views/mus/aura_init.h +++ b/ui/views/mus/aura_init.h
@@ -51,42 +51,51 @@ UI }; + ~AuraInit(); + + // Returns an AuraInit if initialization can be completed successfully, + // otherwise a nullptr is returned. If initialization fails then Aura is in an + // unusable state, and calling services should shutdown. // |resource_file| is the file to load strings and 1x icons from. // |resource_file_200| can be an empty string, otherwise it is the file to // load 2x icons from. - AuraInit(service_manager::Connector* connector, - const service_manager::Identity& identity, - const std::string& resource_file, - const std::string& resource_file_200 = std::string(), - scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = nullptr, - Mode mode = Mode::UI); - ~AuraInit(); + static std::unique_ptr<AuraInit> Create( + service_manager::Connector* connector, + const service_manager::Identity& identity, + const std::string& resource_file, + const std::string& resource_file_200 = std::string(), + scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = nullptr, + Mode mode = Mode::UI); // Only valid if Mode::AURA_MUS was passed to constructor. MusClient* mus_client() { return mus_client_.get(); } + private: + AuraInit(); + // Returns true if AuraInit was able to successfully complete initialization. // If this returns false, then Aura is in an unusable state, and calling // services should shutdown. - bool initialized() { return initialized_; } + bool Init( + service_manager::Connector* connector, + const service_manager::Identity& identity, + const std::string& resource_file, + const std::string& resource_file_200 = std::string(), + scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = nullptr, + Mode mode = Mode::UI); - private: - bool InitializeResources(service_manager::Connector* connector); + bool InitializeResources(service_manager::Connector* connector, + const std::string& resource_file, + const std::string& resource_file_200); #if defined(OS_LINUX) sk_sp<font_service::FontLoader> font_loader_; #endif - const std::string resource_file_; - const std::string resource_file_200_; - std::unique_ptr<aura::Env> env_; std::unique_ptr<MusClient> mus_client_; std::unique_ptr<ViewsDelegate> views_delegate_; - // Whether or not initialization succeeds. - bool initialized_ = false; - DISALLOW_COPY_AND_ASSIGN(AuraInit); };
diff --git a/ui/views/widget/native_widget_mac_accessibility_unittest.mm b/ui/views/widget/native_widget_mac_accessibility_unittest.mm index 7988061f..f3acd06 100644 --- a/ui/views/widget/native_widget_mac_accessibility_unittest.mm +++ b/ui/views/widget/native_widget_mac_accessibility_unittest.mm
@@ -173,7 +173,8 @@ // The following is also "not implemented", but the informal protocol category // provides a default implementation. - EXPECT_EQ(NSNotFound, [ax_node accessibilityIndexOfChild:nil]); + EXPECT_EQ(NSNotFound, static_cast<NSInteger>( + [ax_node accessibilityIndexOfChild:ax_node])); // The only usually available array attribute is AXChildren, so go up a level // to the Widget to test that a bit. The default implementation just gets the @@ -214,7 +215,8 @@ forParameter:range]); // Test the attributes with default implementations provided. - EXPECT_EQ(NSNotFound, [ax_node accessibilityIndexOfChild:nil]); + EXPECT_EQ(NSNotFound, static_cast<NSInteger>( + [ax_node accessibilityIndexOfChild:ax_node])); // The Widget is currently still around, but the child should be gone. EXPECT_EQ(0u, [ax_parent accessibilityArrayAttributeCount:kChildren]);
diff --git a/ui/webui/resources/cr_elements/policy/cr_policy_indicator.html b/ui/webui/resources/cr_elements/policy/cr_policy_indicator.html index 223ab3a6..0bb09677 100644 --- a/ui/webui/resources/cr_elements/policy/cr_policy_indicator.html +++ b/ui/webui/resources/cr_elements/policy/cr_policy_indicator.html
@@ -7,16 +7,16 @@ <link rel="import" href="cr_policy_vars_css.html"> <dom-module id="cr-policy-indicator"> - <style include="cr-hidden-style"> - :host { - @apply(--cr-policy-indicator); - } - - paper-tooltip { - --paper-tooltip: var(--cr-policy-tooltip); - } - </style> <template> + <style include="cr-hidden-style"> + :host { + @apply(--cr-policy-indicator); + } + + paper-tooltip { + --paper-tooltip: var(--cr-policy-tooltip); + } + </style> <iron-icon id="indicator" tabindex="0" aria-label$="[[iconAriaLabel]]" aria-describedby="tooltip" hidden$="[[!indicatorVisible]]" icon="[[indicatorIcon]]"></iron-icon>
diff --git a/ui/webui/resources/cr_elements/policy/cr_policy_network_indicator.html b/ui/webui/resources/cr_elements/policy/cr_policy_network_indicator.html index c4b4d40a..70082b7 100644 --- a/ui/webui/resources/cr_elements/policy/cr_policy_network_indicator.html +++ b/ui/webui/resources/cr_elements/policy/cr_policy_network_indicator.html
@@ -8,16 +8,16 @@ <link rel="import" href="cr_policy_vars_css.html"> <dom-module id="cr-policy-network-indicator"> - <style include="cr-hidden-style"> - :host { - @apply(--cr-policy-indicator); - } - - paper-tooltip { - --paper-tooltip: var(--cr-policy-tooltip); - } - </style> <template> + <style include="cr-hidden-style"> + :host { + @apply(--cr-policy-indicator); + } + + paper-tooltip { + --paper-tooltip: var(--cr-policy-tooltip); + } + </style> <iron-icon id="indicator" tabindex="0" aria-describedby="tooltip" hidden$="[[!indicatorVisible]]" icon="[[indicatorIcon]]"> </iron-icon>
diff --git a/ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.html b/ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.html index 2c97372..dd33e67 100644 --- a/ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.html +++ b/ui/webui/resources/cr_elements/policy/cr_policy_pref_indicator.html
@@ -7,16 +7,16 @@ <link rel="import" href="cr_policy_vars_css.html"> <dom-module id="cr-policy-pref-indicator"> - <style include="cr-hidden-style"> - :host { - @apply(--cr-policy-indicator); - } - - paper-tooltip { - --paper-tooltip: var(--cr-policy-tooltip); - } - </style> <template> + <style include="cr-hidden-style"> + :host { + @apply(--cr-policy-indicator); + } + + paper-tooltip { + --paper-tooltip: var(--cr-policy-tooltip); + } + </style> <iron-icon id="indicator" tabindex="0" aria-label$="[[iconAriaLabel]]" aria-describedby="tooltip" hidden$="[[!indicatorVisible]]" icon="[[indicatorIcon]]"></iron-icon>