diff --git a/DEPS b/DEPS index 3fb0331..a46da3c 100644 --- a/DEPS +++ b/DEPS
@@ -145,11 +145,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': 'a00318f1ad000e71cb27b0adf74c695902f32220', + 'skia_revision': '80e7bd03d4736fb2d7591fb034f3bcc2d79dbf8b', # 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': '7ae4b7f34ab5489c36b8bd981b02765c41f0580f', + 'v8_revision': '69c9ca09df3a8bb7d8eac52325df0a2008b00cab', # 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. @@ -157,11 +157,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': 'e995d7fb23c5fa1bdd7d77c1b63d707259e65b31', + 'angle_revision': '868f5fa02353df97ae486d45af5afb08f495e489', # 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': '204a410c8c4061ffdf93587081680dab8c1437a3', + 'swiftshader_revision': 'f63c4e51101a33fbaeaaafba949830ad43f39055', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -276,11 +276,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'shaderc_revision': '747518d43f4b463cf0d6720fdf9968c55b2921fe', + 'shaderc_revision': '3101bd58464af111c74f4d98197fae1d29db928a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '351ea23830db3bfcf1e8abd7f9241739d69fc001', + 'dawn_revision': '56f3a7b90d37c6e2a3ce4ab230416656a2f562a9', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -809,7 +809,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'dcf3c07791fc67fd077424c88ecff62c7928a6b0', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '5dd6b1e0a5eff1b2fb269bac969beac5f461483f', 'condition': 'checkout_linux', }, @@ -1073,7 +1073,7 @@ }, 'src/third_party/libjpeg_turbo': - Var('chromium_git') + '/chromium/deps/libjpeg_turbo.git' + '@' + '14eba7addfdcf0699970fcbac225499858a167f2', + Var('chromium_git') + '/chromium/deps/libjpeg_turbo.git' + '@' + '81aef9014e059f9bf4838db49ba4fd47fd9d14ce', 'src/third_party/liblouis/src': { 'url': Var('chromium_git') + '/external/liblouis-github.git' + '@' + '97ce1c67fccbd3668291b7e63c06161c095d49f2', @@ -1207,7 +1207,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'c17e81c243e389a58aff81e9ef6a1e408b88519e', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'bf0e385cd6fb456a816419c50de2c3622be2c2ae', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1375,7 +1375,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'abaae129d9a0c6e1e092067e0b105475df43352e', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '84de3d95cf0e6f6c27002eb079b237490b6ffcc3', + Var('webrtc_git') + '/src.git' + '@' + '0c67c80ac3fd82352edaba1f014a3928727cf2b7', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1416,7 +1416,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@682bc0e14c7a8844337f2c9ea9ad6ce300c10bca', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@7e33a7e91b899e98146b9be23ad049a73935bcf0', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index fd51a2b..eec47087 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -580,8 +580,6 @@ "browser/js_java_interaction/js_java_configurator_host.h", "browser/memory_metrics_logger.cc", "browser/memory_metrics_logger.h", - "browser/net/android_stream_reader_url_request_job.cc", - "browser/net/android_stream_reader_url_request_job.h", "browser/net/aw_cookie_change_dispatcher_wrapper.cc", "browser/net/aw_cookie_change_dispatcher_wrapper.h", "browser/net/aw_cookie_store_wrapper.cc", @@ -592,16 +590,10 @@ "browser/net/aw_network_change_notifier.h", "browser/net/aw_network_change_notifier_factory.cc", "browser/net/aw_network_change_notifier_factory.h", - "browser/net/aw_network_delegate.cc", - "browser/net/aw_network_delegate.h", "browser/net/aw_proxy_config_monitor.cc", "browser/net/aw_proxy_config_monitor.h", - "browser/net/aw_request_interceptor.cc", - "browser/net/aw_request_interceptor.h", "browser/net/aw_url_request_context_getter.cc", "browser/net/aw_url_request_context_getter.h", - "browser/net/aw_url_request_job_factory.cc", - "browser/net/aw_url_request_job_factory.h", "browser/net/aw_web_resource_request.cc", "browser/net/aw_web_resource_request.h", "browser/net/aw_web_resource_response.cc", @@ -720,7 +712,7 @@ "//components/crash/core/common", "//components/download/public/common:public", "//components/embedder_support/android:web_contents_delegate", - "//components/google/core/browser", + "//components/google/core/common", "//components/heap_profiling", "//components/keyed_service/content", "//components/metrics",
diff --git a/android_webview/browser/android_protocol_handler.cc b/android_webview/browser/android_protocol_handler.cc index f26f8b3..69944450 100644 --- a/android_webview/browser/android_protocol_handler.cc +++ b/android_webview/browser/android_protocol_handler.cc
@@ -8,8 +8,6 @@ #include <utility> #include "android_webview/browser/input_stream.h" -#include "android_webview/browser/net/android_stream_reader_url_request_job.h" -#include "android_webview/browser/net/aw_url_request_job_factory.h" #include "android_webview/common/url_constants.h" #include "android_webview/native_jni/AndroidProtocolHandler_jni.h" #include "base/android/jni_android.h" @@ -25,7 +23,6 @@ #include "url/gurl.h" #include "url/url_constants.h" -using android_webview::AndroidStreamReaderURLRequestJob; using android_webview::InputStream; using android_webview::InputStream; using base::android::AttachCurrentThread; @@ -39,42 +36,6 @@ const void* const kPreviouslyFailedKey = &kPreviouslyFailedKey; -void MarkRequestAsFailed(net::URLRequest* request) { - request->SetUserData(kPreviouslyFailedKey, - std::make_unique<base::SupportsUserData::Data>()); -} - -bool HasRequestPreviouslyFailed(net::URLRequest* request) { - return request->GetUserData(kPreviouslyFailedKey) != NULL; -} - -class AndroidStreamReaderURLRequestJobDelegateImpl - : public AndroidStreamReaderURLRequestJob::Delegate { - public: - AndroidStreamReaderURLRequestJobDelegateImpl(); - - std::unique_ptr<InputStream> OpenInputStream(JNIEnv* env, - const GURL& url) override; - - void OnInputStreamOpenFailed(net::URLRequest* request, - bool* restart) override; - - bool GetMimeType(JNIEnv* env, - net::URLRequest* request, - InputStream* stream, - std::string* mime_type) override; - - bool GetCharset(JNIEnv* env, - net::URLRequest* request, - InputStream* stream, - std::string* charset) override; - - void AppendResponseHeaders(JNIEnv* env, - net::HttpResponseHeaders* headers) override; - - ~AndroidStreamReaderURLRequestJobDelegateImpl() override; -}; - class AndroidRequestInterceptorBase : public net::URLRequestInterceptor { public: net::URLRequestJob* MaybeInterceptRequest( @@ -97,81 +58,13 @@ bool ShouldHandleRequest(const net::URLRequest* request) const override; }; -// AndroidStreamReaderURLRequestJobDelegateImpl ------------------------------- - -AndroidStreamReaderURLRequestJobDelegateImpl:: - AndroidStreamReaderURLRequestJobDelegateImpl() {} - -AndroidStreamReaderURLRequestJobDelegateImpl:: - ~AndroidStreamReaderURLRequestJobDelegateImpl() {} - -std::unique_ptr<InputStream> -AndroidStreamReaderURLRequestJobDelegateImpl::OpenInputStream(JNIEnv* env, - const GURL& url) { - return android_webview::CreateInputStream(env, url); -} - -void AndroidStreamReaderURLRequestJobDelegateImpl::OnInputStreamOpenFailed( - net::URLRequest* request, - bool* restart) { - DCHECK(!HasRequestPreviouslyFailed(request)); - MarkRequestAsFailed(request); - *restart = true; -} - -bool AndroidStreamReaderURLRequestJobDelegateImpl::GetMimeType( - JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* mime_type) { - DCHECK(env); - DCHECK(request); - DCHECK(mime_type); - - return GetInputStreamMimeType(env, request->url(), stream, mime_type); -} - -bool AndroidStreamReaderURLRequestJobDelegateImpl::GetCharset( - JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* charset) { - // TODO: We should probably be getting this from the managed side. - return false; -} - -void AndroidStreamReaderURLRequestJobDelegateImpl::AppendResponseHeaders( - JNIEnv* env, - net::HttpResponseHeaders* headers) { - // no-op -} - // AndroidRequestInterceptorBase ---------------------------------------------- net::URLRequestJob* AndroidRequestInterceptorBase::MaybeInterceptRequest( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { - if (!ShouldHandleRequest(request)) - return NULL; - - // For WebViewClassic compatibility this job can only accept URLs that can be - // opened. URLs that cannot be opened should be resolved by the next handler. - // - // If a request is initially handled here but the job fails due to it being - // unable to open the InputStream for that request the request is marked as - // previously failed and restarted. - // Restarting a request involves creating a new job for that request. This - // handler will ignore requests know to have previously failed to 1) prevent - // an infinite loop, 2) ensure that the next handler in line gets the - // opportunity to create a job for the request. - if (HasRequestPreviouslyFailed(request)) - return NULL; - - std::unique_ptr<AndroidStreamReaderURLRequestJobDelegateImpl> reader_delegate( - new AndroidStreamReaderURLRequestJobDelegateImpl()); - - return new AndroidStreamReaderURLRequestJob(request, network_delegate, - std::move(reader_delegate)); + NOTREACHED(); + return nullptr; } // AssetFileRequestInterceptor ------------------------------------------------
diff --git a/android_webview/browser/aw_browser_context.cc b/android_webview/browser/aw_browser_context.cc index ed4a615e..7f9382e8 100644 --- a/android_webview/browser/aw_browser_context.cc +++ b/android_webview/browser/aw_browser_context.cc
@@ -239,8 +239,9 @@ CreateUserPrefService(); scoped_refptr<base::SequencedTaskRunner> db_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); visitedlink_master_.reset( new visitedlink::VisitedLinkMaster(this, this, false));
diff --git a/android_webview/browser/aw_browser_process.cc b/android_webview/browser/aw_browser_process.cc index f9d62d36..2bfeaae 100644 --- a/android_webview/browser/aw_browser_process.cc +++ b/android_webview/browser/aw_browser_process.cc
@@ -88,10 +88,10 @@ void AwBrowserProcess::CreateSafeBrowsingWhitelistManager() { scoped_refptr<base::SequencedTaskRunner> background_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}); scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}); safe_browsing_whitelist_manager_ = std::make_unique<AwSafeBrowsingWhitelistManager>(background_task_runner, io_task_runner); @@ -171,7 +171,7 @@ std::unique_ptr<net::ProxyConfigServiceAndroid> CreateProxyConfigService() { std::unique_ptr<net::ProxyConfigServiceAndroid> config_service_android = std::make_unique<net::ProxyConfigServiceAndroid>( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({BrowserThread::IO}), base::ThreadTaskRunnerHandle::Get()); config_service_android->set_exclude_pac_url(true);
diff --git a/android_webview/browser/aw_browser_terminator.cc b/android_webview/browser/aw_browser_terminator.cc index d1d6ca7..31591d8b 100644 --- a/android_webview/browser/aw_browser_terminator.cc +++ b/android_webview/browser/aw_browser_terminator.cc
@@ -128,10 +128,10 @@ std::vector<ScopedJavaGlobalRef<jobject>> java_web_contents; GetJavaWebContentsForRenderProcess(rph, &java_web_contents); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::HIGHEST}, - base::BindOnce(OnRenderProcessGone, java_web_contents, info.pid, - info.is_crashed())); + base::PostTask(FROM_HERE, + {content::BrowserThread::UI, base::TaskPriority::HIGHEST}, + base::BindOnce(OnRenderProcessGone, java_web_contents, + info.pid, info.is_crashed())); } } // namespace android_webview
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index c4aae1e1..a63cb61 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -775,12 +775,12 @@ base::BindRepeating( &AwContentBrowserClient::GetSafeBrowsingUrlCheckerDelegate, base::Unretained(this))), - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); + base::CreateSingleThreadTaskRunner({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_SPELLCHECK) registry->AddInterface( base::BindRepeating(&SpellCheckHostImpl::Create), - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})); + base::CreateSingleThreadTaskRunner({BrowserThread::UI})); #endif } @@ -971,7 +971,7 @@ 0 /* process_id */, std::move(request), nullptr, true /* intercept_only */); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( [](network::mojom::URLLoaderFactoryRequest request) { @@ -1039,11 +1039,10 @@ int process_id = is_navigation ? 0 : render_process_id; // Android WebView has one non off-the-record browser context. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&AwProxyingURLLoaderFactory::CreateProxy, process_id, - std::move(proxied_receiver), - std::move(target_factory_info))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&AwProxyingURLLoaderFactory::CreateProxy, + process_id, std::move(proxied_receiver), + std::move(target_factory_info))); return true; } @@ -1057,11 +1056,10 @@ mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver = pending_factory->InitWithNewPipeAndPassReceiver(); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&AwProxyingURLLoaderFactory::CreateProxy, - render_process_id, std::move(factory_receiver), - std::move(pending_proxy))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&AwProxyingURLLoaderFactory::CreateProxy, + render_process_id, std::move(factory_receiver), + std::move(pending_proxy))); } uint32_t AwContentBrowserClient::GetWebSocketOptions(
diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc index dab3e80..f1d6dcd 100644 --- a/android_webview/browser/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -225,7 +225,7 @@ : content::WebContentsObserver(web_contents.get()), browser_view_renderer_( this, - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})), + base::CreateSingleThreadTaskRunner({BrowserThread::UI})), web_contents_(std::move(web_contents)) { base::subtle::NoBarrier_AtomicIncrement(&g_instance_count, 1); icon_helper_.reset(new IconHelper(web_contents_.get())); @@ -550,7 +550,7 @@ const GURL& origin) { JNIEnv* env = AttachCurrentThread(); if (java_ref.get(env).obj()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ShowGeolocationPromptHelperTask, java_ref, origin)); }
diff --git a/android_webview/browser/aw_contents_io_thread_client.h b/android_webview/browser/aw_contents_io_thread_client.h index 546092eb..91d959b 100644 --- a/android_webview/browser/aw_contents_io_thread_client.h +++ b/android_webview/browser/aw_contents_io_thread_client.h
@@ -138,7 +138,7 @@ base::android::ScopedJavaGlobalRef<jobject> java_object_; base::android::ScopedJavaGlobalRef<jobject> bg_thread_client_object_; scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}); DISALLOW_COPY_AND_ASSIGN(AwContentsIoThreadClient); };
diff --git a/android_webview/browser/aw_contents_statics.cc b/android_webview/browser/aw_contents_statics.cc index bce0d1a..fc2e06f 100644 --- a/android_webview/browser/aw_contents_statics.cc +++ b/android_webview/browser/aw_contents_statics.cc
@@ -76,7 +76,7 @@ JNIEnv* env, const JavaParamRef<jobject>& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&NotifyClientCertificatesChanged), base::BindOnce(&ClientCertificatesCleared,
diff --git a/android_webview/browser/aw_download_manager_delegate.cc b/android_webview/browser/aw_download_manager_delegate.cc index a0ef3c4..c34b320a 100644 --- a/android_webview/browser/aw_download_manager_delegate.cc +++ b/android_webview/browser/aw_download_manager_delegate.cc
@@ -84,11 +84,10 @@ // use default user agent if nothing is provided aw_user_agent = user_agent.empty() ? GetUserAgent() : user_agent; } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&DownloadStartingOnUIThread, web_contents, url, - aw_user_agent, content_disposition, mime_type, - content_length)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&DownloadStartingOnUIThread, web_contents, url, + aw_user_agent, content_disposition, mime_type, + content_length)); return true; }
diff --git a/android_webview/browser/aw_form_database_service.cc b/android_webview/browser/aw_form_database_service.cc index 2676cd7..ba364baa 100644 --- a/android_webview/browser/aw_form_database_service.cc +++ b/android_webview/browser/aw_form_database_service.cc
@@ -38,8 +38,8 @@ // TODO(pkasting): http://crbug.com/740773 This should likely be sequenced, // not single-threaded; it's also possible these objects can each use their // own sequences instead of sharing this one. - auto db_task_runner = base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + auto db_task_runner = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); web_database_ = new WebDatabaseService(path.Append(kWebDataFilename), ui_task_runner, db_task_runner);
diff --git a/android_webview/browser/aw_http_auth_handler.cc b/android_webview/browser/aw_http_auth_handler.cc index 6c4418fe..cff849b 100644 --- a/android_webview/browser/aw_http_auth_handler.cc +++ b/android_webview/browser/aw_http_auth_handler.cc
@@ -38,7 +38,7 @@ http_auth_handler_.Reset(Java_AwHttpAuthHandler_create( env, reinterpret_cast<intptr_t>(this), first_auth_attempt)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&AwHttpAuthHandler::Start, weak_factory_.GetWeakPtr())); }
diff --git a/android_webview/browser/aw_print_manager.cc b/android_webview/browser/aw_print_manager.cc index df6f6a91..89bbbc9 100644 --- a/android_webview/browser/aw_print_manager.cc +++ b/android_webview/browser/aw_print_manager.cc
@@ -118,9 +118,9 @@ } base::PostTaskAndReplyWithResult( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}) + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}) .get(), FROM_HERE, base::BindRepeating(&SaveDataToFd, fd_, number_pages_, data), pdf_writing_done_callback_);
diff --git a/android_webview/browser/aw_quota_manager_bridge.cc b/android_webview/browser/aw_quota_manager_bridge.cc index 89ebafdb..1e0fa04 100644 --- a/android_webview/browser/aw_quota_manager_bridge.cc +++ b/android_webview/browser/aw_quota_manager_bridge.cc
@@ -87,7 +87,7 @@ void GetOriginsTask::Run() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&QuotaManager::GetOriginsModifiedSince, quota_manager_, blink::mojom::StorageType::kTemporary, @@ -129,9 +129,8 @@ void GetOriginsTask::CheckDone() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (num_callbacks_received_ == num_callbacks_to_wait_) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&GetOriginsTask::DoneOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&GetOriginsTask::DoneOnUIThread, this)); } else if (num_callbacks_received_ > num_callbacks_to_wait_) { NOTREACHED(); } @@ -147,7 +146,7 @@ if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { std::move(task).Run(); } else { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(task)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(task)); } } @@ -286,9 +285,8 @@ usage = 0; quota = 0; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(ui_callback), usage, quota)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(ui_callback), usage, quota)); } } // namespace @@ -316,7 +314,7 @@ weak_factory_.GetWeakPtr(), callback_id, is_quota); // TODO(crbug.com/889590): Use helper for url::Origin creation from string. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &QuotaManager::GetUsageAndQuota, GetQuotaManager(),
diff --git a/android_webview/browser/aw_speech_recognition_manager_delegate.cc b/android_webview/browser/aw_speech_recognition_manager_delegate.cc index b2e0b52..0b212cd 100644 --- a/android_webview/browser/aw_speech_recognition_manager_delegate.cc +++ b/android_webview/browser/aw_speech_recognition_manager_delegate.cc
@@ -82,10 +82,9 @@ // Check that the render frame type is appropriate, and whether or not we // need to request permission from the user. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CheckRenderFrameType, std::move(callback), - render_process_id, render_frame_id)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CheckRenderFrameType, std::move(callback), + render_process_id, render_frame_id)); } content::SpeechRecognitionEventListener* @@ -108,7 +107,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); // Regular tab contents. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), true /* check_permission */, true /* allowed */));
diff --git a/android_webview/browser/gfx/aw_draw_fn_impl.cc b/android_webview/browser/gfx/aw_draw_fn_impl.cc index 6adeace1..800882e 100644 --- a/android_webview/browser/gfx/aw_draw_fn_impl.cc +++ b/android_webview/browser/gfx/aw_draw_fn_impl.cc
@@ -202,7 +202,7 @@ : is_interop_mode_(!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kWebViewEnableVulkan)), render_thread_manager_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})) { + base::CreateSingleThreadTaskRunner({BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_draw_fn_function_table);
diff --git a/android_webview/browser/gfx/aw_gl_functor.cc b/android_webview/browser/gfx/aw_gl_functor.cc index 32b24f02..82ff9e8 100644 --- a/android_webview/browser/gfx/aw_gl_functor.cc +++ b/android_webview/browser/gfx/aw_gl_functor.cc
@@ -37,7 +37,7 @@ AwGLFunctor::AwGLFunctor(const JavaObjectWeakGlobalRef& java_ref) : java_ref_(java_ref), render_thread_manager_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})) { + base::CreateSingleThreadTaskRunner({BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ++g_instance_count; }
diff --git a/android_webview/browser/net/android_stream_reader_url_request_job.cc b/android_webview/browser/net/android_stream_reader_url_request_job.cc deleted file mode 100644 index a0f32a6..0000000 --- a/android_webview/browser/net/android_stream_reader_url_request_job.cc +++ /dev/null
@@ -1,367 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/browser/net/android_stream_reader_url_request_job.h" - -#include <memory> -#include <string> -#include <utility> - -#include "android_webview/browser/input_stream.h" -#include "android_webview/browser/net/input_stream_reader.h" -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/lazy_instance.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_number_conversions.h" -#include "base/task/post_task.h" -#include "base/threading/thread.h" -#include "base/threading/thread_task_runner_handle.h" -#include "net/base/io_buffer.h" -#include "net/base/mime_util.h" -#include "net/http/http_response_headers.h" -#include "net/http/http_response_info.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job_manager.h" - -using base::android::AttachCurrentThread; - -namespace android_webview { - -namespace { - -const int kHTTPOk = 200; -const int kHTTPNotFound = 404; - -const char kResponseHeaderViaShouldInterceptRequest[] = - "Client-Via: shouldInterceptRequest"; -const char kHTTPOkText[] = "OK"; -const char kHTTPNotFoundText[] = "Not Found"; - -} // namespace - -// The requests posted to the worker thread might outlive the job. Thread-safe -// ref counting is used to ensure that the InputStream and InputStreamReader -// members of this class are still there when the closure is run on the worker -// thread. -class InputStreamReaderWrapper : - public base::RefCountedThreadSafe<InputStreamReaderWrapper> { - public: - InputStreamReaderWrapper( - std::unique_ptr<InputStream> input_stream, - std::unique_ptr<InputStreamReader> input_stream_reader) - : input_stream_(std::move(input_stream)), - input_stream_reader_(std::move(input_stream_reader)) { - DCHECK(input_stream_); - DCHECK(input_stream_reader_); - } - - InputStream* input_stream() { - return input_stream_.get(); - } - - int Seek(const net::HttpByteRange& byte_range) { - return input_stream_reader_->Seek(byte_range); - } - - int ReadRawData(net::IOBuffer* buffer, int buffer_size) { - return input_stream_reader_->ReadRawData(buffer, buffer_size); - } - - private: - friend class base::RefCountedThreadSafe<InputStreamReaderWrapper>; - ~InputStreamReaderWrapper() {} - - std::unique_ptr<InputStream> input_stream_; - std::unique_ptr<InputStreamReader> input_stream_reader_; - - DISALLOW_COPY_AND_ASSIGN(InputStreamReaderWrapper); -}; - -AndroidStreamReaderURLRequestJob::AndroidStreamReaderURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - std::unique_ptr<Delegate> delegate) - : URLRequestJob(request, network_delegate), - range_parse_result_(net::OK), - delegate_(std::move(delegate)), - weak_factory_(this) { - DCHECK(delegate_); -} - -AndroidStreamReaderURLRequestJob::AndroidStreamReaderURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - std::unique_ptr<DelegateObtainer> delegate_obtainer, - bool) - : URLRequestJob(request, network_delegate), - range_parse_result_(net::OK), - delegate_obtainer_(std::move(delegate_obtainer)), - weak_factory_(this) { - DCHECK(delegate_obtainer_); -} - -AndroidStreamReaderURLRequestJob::~AndroidStreamReaderURLRequestJob() { -} - -namespace { - -using OnInputStreamOpenedCallback = base::OnceCallback<void( - std::unique_ptr<AndroidStreamReaderURLRequestJob::Delegate>, - std::unique_ptr<InputStream>)>; - -// static -void OpenInputStreamOnWorkerThread( - scoped_refptr<base::SingleThreadTaskRunner> job_thread_task_runner, - std::unique_ptr<AndroidStreamReaderURLRequestJob::Delegate> delegate, - const GURL& url, - OnInputStreamOpenedCallback callback) { - JNIEnv* env = AttachCurrentThread(); - DCHECK(env); - - std::unique_ptr<InputStream> input_stream = - delegate->OpenInputStream(env, url); - job_thread_task_runner->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), std::move(delegate), - std::move(input_stream))); -} - -} // namespace - -void AndroidStreamReaderURLRequestJob::Start() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!delegate_) { - DCHECK(delegate_obtainer_); - delegate_obtainer_->ObtainDelegate( - request(), - base::BindOnce(&AndroidStreamReaderURLRequestJob::DelegateObtained, - weak_factory_.GetWeakPtr())); - } else { - // Run DoStart asynchronously to avoid re-entering the delegate. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(&AndroidStreamReaderURLRequestJob::DoStart, - weak_factory_.GetWeakPtr())); - } -} - -void AndroidStreamReaderURLRequestJob::Kill() { - DCHECK(thread_checker_.CalledOnValidThread()); - weak_factory_.InvalidateWeakPtrs(); - URLRequestJob::Kill(); -} - -std::unique_ptr<InputStreamReader> -AndroidStreamReaderURLRequestJob::CreateStreamReader(InputStream* stream) { - return std::make_unique<InputStreamReader>(stream); -} - -void AndroidStreamReaderURLRequestJob::OnInputStreamOpened( - std::unique_ptr<Delegate> returned_delegate, - std::unique_ptr<android_webview::InputStream> input_stream) { - DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(returned_delegate); - delegate_ = std::move(returned_delegate); - - if (!input_stream) { - bool restart_required = false; - delegate_->OnInputStreamOpenFailed(request(), &restart_required); - if (restart_required) { - NotifyRestartRequired(); - } else { - HeadersComplete(kHTTPNotFound, kHTTPNotFoundText); - } - return; - } - - std::unique_ptr<InputStreamReader> input_stream_reader( - CreateStreamReader(input_stream.get())); - DCHECK(input_stream_reader); - - DCHECK(!input_stream_reader_wrapper_.get()); - input_stream_reader_wrapper_ = new InputStreamReaderWrapper( - std::move(input_stream), std::move(input_stream_reader)); - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&InputStreamReaderWrapper::Seek, - input_stream_reader_wrapper_, byte_range_), - base::BindOnce(&AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted, - weak_factory_.GetWeakPtr())); -} - -void AndroidStreamReaderURLRequestJob::OnReaderSeekCompleted(int result) { - DCHECK(thread_checker_.CalledOnValidThread()); - if (result >= 0) { - set_expected_content_size(result); - HeadersComplete(kHTTPOk, kHTTPOkText); - } else { - NotifyStartError( - net::URLRequestStatus(net::URLRequestStatus::FAILED, result)); - } -} - -void AndroidStreamReaderURLRequestJob::OnReaderReadCompleted(int result) { - DCHECK(thread_checker_.CalledOnValidThread()); - - ReadRawDataComplete(result); -} - -int AndroidStreamReaderURLRequestJob::ReadRawData(net::IOBuffer* dest, - int dest_size) { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!input_stream_reader_wrapper_.get()) { - // This will happen if opening the InputStream fails in which case the - // error is communicated by setting the HTTP response status header rather - // than failing the request during the header fetch phase. - return 0; - } - - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&InputStreamReaderWrapper::ReadRawData, - input_stream_reader_wrapper_, base::RetainedRef(dest), - dest_size), - base::BindOnce(&AndroidStreamReaderURLRequestJob::OnReaderReadCompleted, - weak_factory_.GetWeakPtr())); - - return net::ERR_IO_PENDING; -} - -bool AndroidStreamReaderURLRequestJob::GetMimeType( - std::string* mime_type) const { - DCHECK(thread_checker_.CalledOnValidThread()); - JNIEnv* env = AttachCurrentThread(); - DCHECK(env); - - if (!input_stream_reader_wrapper_.get()) - return false; - - return delegate_->GetMimeType( - env, request(), input_stream_reader_wrapper_->input_stream(), mime_type); -} - -bool AndroidStreamReaderURLRequestJob::GetCharset(std::string* charset) { - DCHECK(thread_checker_.CalledOnValidThread()); - JNIEnv* env = AttachCurrentThread(); - DCHECK(env); - - if (!input_stream_reader_wrapper_.get()) - return false; - - // Since it's possible for this call to alter the InputStream a - // Seek or ReadRawData operation running in the background is not permitted. - DCHECK(!request_->status().is_io_pending()); - - return delegate_->GetCharset( - env, request(), input_stream_reader_wrapper_->input_stream(), charset); -} - -void AndroidStreamReaderURLRequestJob::DelegateObtained( - std::unique_ptr<Delegate> delegate) { - DCHECK(!delegate_); - delegate_obtainer_.reset(); - if (delegate) { - delegate_.swap(delegate); - DoStart(); - } else { - NotifyRestartRequired(); - } -} - -void AndroidStreamReaderURLRequestJob::DoStart() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (range_parse_result_ != net::OK) { - NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, - range_parse_result_)); - return; - } - - // This could be done in the InputStreamReader but would force more - // complex synchronization in the delegate. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce( - &OpenInputStreamOnWorkerThread, base::ThreadTaskRunnerHandle::Get(), - // This is intentional - the job could be deleted while the callback - // is executing on the background thread. - // The delegate will be "returned" to the job once the InputStream - // open attempt is completed. - std::move(delegate_), request()->url(), - base::BindOnce(&AndroidStreamReaderURLRequestJob::OnInputStreamOpened, - weak_factory_.GetWeakPtr()))); -} - -void AndroidStreamReaderURLRequestJob::HeadersComplete( - int status_code, - const std::string& status_text) { - std::string status("HTTP/1.1 "); - status.append(base::NumberToString(status_code)); - status.append(" "); - status.append(status_text); - // HttpResponseHeaders expects its input string to be terminated by two NULs. - status.append("\0\0", 2); - net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status); - - if (status_code == kHTTPOk) { - if (expected_content_size() != -1) { - std::string content_length_header( - net::HttpRequestHeaders::kContentLength); - content_length_header.append(": "); - content_length_header.append( - base::NumberToString(expected_content_size())); - headers->AddHeader(content_length_header); - } - - std::string mime_type; - if (GetMimeType(&mime_type) && !mime_type.empty()) { - std::string content_type_header(net::HttpRequestHeaders::kContentType); - content_type_header.append(": "); - content_type_header.append(mime_type); - headers->AddHeader(content_type_header); - } - } - - JNIEnv* env = AttachCurrentThread(); - DCHECK(env); - delegate_->AppendResponseHeaders(env, headers); - - // Indicate that the response had been obtained via shouldInterceptRequest. - headers->AddHeader(kResponseHeaderViaShouldInterceptRequest); - - response_info_.reset(new net::HttpResponseInfo()); - response_info_->headers = headers; - - NotifyHeadersComplete(); -} - -void AndroidStreamReaderURLRequestJob::GetResponseInfo( - net::HttpResponseInfo* info) { - if (response_info_) - *info = *response_info_; -} - -void AndroidStreamReaderURLRequestJob::SetExtraRequestHeaders( - const net::HttpRequestHeaders& headers) { - std::string range_header; - if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) { - // This job only cares about the Range header so that we know how many bytes - // in the stream to skip and how many to read after that. Note that - // validation is deferred to DoStart(), because NotifyStartError() is not - // legal to call since the job has not started. - std::vector<net::HttpByteRange> ranges; - if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) { - if (ranges.size() == 1) - byte_range_ = ranges[0]; - } else { - // We don't support multiple range requests in one single URL request, - // because we need to do multipart encoding here. - range_parse_result_ = net::ERR_REQUEST_RANGE_NOT_SATISFIABLE; - } - } -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/android_stream_reader_url_request_job.h b/android_webview/browser/net/android_stream_reader_url_request_job.h deleted file mode 100644 index a7e0a84..0000000 --- a/android_webview/browser/net/android_stream_reader_url_request_job.h +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ANDROID_WEBVIEW_BROWSER_NET_ANDROID_STREAM_READER_URL_REQUEST_JOB_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_ANDROID_STREAM_READER_URL_REQUEST_JOB_H_ - -#include <memory> -#include <string> - -#include "base/android/scoped_java_ref.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/threading/thread_checker.h" -#include "net/base/net_errors.h" -#include "net/http/http_byte_range.h" -#include "net/url_request/url_request_job.h" - -namespace net { -class HttpResponseHeaders; -class HttpResponseInfo; -class URLRequest; -} - -namespace android_webview { - -class InputStream; -class InputStreamReader; -class InputStreamReaderWrapper; - -// A request job that reads data from a Java InputStream. -class AndroidStreamReaderURLRequestJob : public net::URLRequestJob { - public: - /* - * We use a delegate so that we can share code for this job in slightly - * different contexts. - */ - class Delegate { - public: - virtual ~Delegate() {} - - // This method is called from a worker thread, not from the IO thread. - virtual std::unique_ptr<android_webview::InputStream> OpenInputStream( - JNIEnv* env, - const GURL& url) = 0; - - // This method is called on the Job's thread if the result of calling - // OpenInputStream was null. - // Setting the |restart| parameter to true will cause the request to be - // restarted with a new job. - virtual void OnInputStreamOpenFailed( - net::URLRequest* request, - bool* restart) = 0; - - virtual bool GetMimeType( - JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* mime_type) = 0; - - virtual bool GetCharset( - JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* charset) = 0; - - virtual void AppendResponseHeaders(JNIEnv* env, - net::HttpResponseHeaders* headers) = 0; - }; - - class DelegateObtainer { - public: - virtual ~DelegateObtainer() {} - - using Callback = base::OnceCallback<void(std::unique_ptr<Delegate>)>; - virtual void ObtainDelegate(net::URLRequest* request, - Callback callback) = 0; - }; - - AndroidStreamReaderURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - std::unique_ptr<Delegate> delegate); - AndroidStreamReaderURLRequestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - std::unique_ptr<DelegateObtainer> delegate_obtainer, - bool); // resolve ambiguity - - // URLRequestJob: - void Start() override; - void Kill() override; - int ReadRawData(net::IOBuffer* buf, int buf_size) override; - void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override; - bool GetMimeType(std::string* mime_type) const override; - bool GetCharset(std::string* charset) override; - void GetResponseInfo(net::HttpResponseInfo* info) override; - - protected: - ~AndroidStreamReaderURLRequestJob() override; - - // Creates an InputStreamReader instance. - // Overridden in unittests to return a mock. - virtual std::unique_ptr<android_webview::InputStreamReader> - CreateStreamReader(android_webview::InputStream* stream); - - private: - // Used as a callback when obtaining the delegate asynchronously, - // see DelegateObtainer. - void DelegateObtained(std::unique_ptr<Delegate> delegate); - // Actual URLRequestJob::Start implementation. - void DoStart(); - - void HeadersComplete(int status_code, const std::string& status_text); - - void OnInputStreamOpened( - std::unique_ptr<Delegate> delegate, - std::unique_ptr<android_webview::InputStream> input_stream); - void OnReaderSeekCompleted(int content_size); - void OnReaderReadCompleted(int bytes_read); - - net::HttpByteRange byte_range_; - net::Error range_parse_result_; - std::unique_ptr<net::HttpResponseInfo> response_info_; - std::unique_ptr<Delegate> delegate_; - std::unique_ptr<DelegateObtainer> delegate_obtainer_; - scoped_refptr<InputStreamReaderWrapper> input_stream_reader_wrapper_; - base::ThreadChecker thread_checker_; - - base::WeakPtrFactory<AndroidStreamReaderURLRequestJob> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(AndroidStreamReaderURLRequestJob); -}; - -} // namespace android_webview - -#endif // ANDROID_WEBVIEW_BROWSER_NET_ANDROID_STREAM_READER_URL_REQUEST_JOB_H_
diff --git a/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc b/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc deleted file mode 100644 index c90c179f..0000000 --- a/android_webview/browser/net/android_stream_reader_url_request_job_unittest.cc +++ /dev/null
@@ -1,411 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/browser/net/android_stream_reader_url_request_job.h" - -#include <memory> -#include <utility> - -#include "android_webview/browser/input_stream.h" -#include "android_webview/browser/net/aw_url_request_job_factory.h" -#include "android_webview/browser/net/input_stream_reader.h" -#include "base/format_macros.h" -#include "base/run_loop.h" -#include "base/strings/stringprintf.h" -#include "base/test/scoped_task_environment.h" -#include "net/base/request_priority.h" -#include "net/http/http_byte_range.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job_factory_impl.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using net::TestDelegate; -using net::TestJobInterceptor; -using net::TestNetworkDelegate; -using net::TestURLRequestContext; -using net::URLRequest; -using testing::DoAll; -using testing::Ge; -using testing::Gt; -using testing::InSequence; -using testing::Invoke; -using testing::InvokeWithoutArgs; -using testing::NotNull; -using testing::Return; -using testing::SaveArg; -using testing::SetArgPointee; -using testing::StrictMock; -using testing::Test; -using testing::WithArg; -using testing::WithArgs; -using testing::_; - -namespace android_webview { - -namespace { - -// Some of the classes will DCHECK on a null InputStream (which is desirable). -// The workaround is to use this class. None of the methods need to be -// implemented as the mock InputStreamReader should never forward calls to the -// InputStream. -class NotImplInputStream : public InputStream { - public: - NotImplInputStream() {} - ~NotImplInputStream() override {} - bool BytesAvailable(int* bytes_available) const override { - NOTIMPLEMENTED(); - return false; - } - bool Skip(int64_t n, int64_t* bytes_skipped) override { - NOTIMPLEMENTED(); - return false; - } - bool Read(net::IOBuffer* dest, int length, int* bytes_read) override { - NOTIMPLEMENTED(); - return false; - } -}; - -// Required in order to create an instance of AndroidStreamReaderURLRequestJob. -class StreamReaderDelegate : - public AndroidStreamReaderURLRequestJob::Delegate { - public: - StreamReaderDelegate() {} - - std::unique_ptr<InputStream> OpenInputStream(JNIEnv* env, - const GURL& url) override { - return std::make_unique<NotImplInputStream>(); - } - - void OnInputStreamOpenFailed(net::URLRequest* request, - bool* restart) override { - *restart = false; - } - - bool GetMimeType(JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* mime_type) override { - return false; - } - - bool GetCharset(JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* charset) override { - return false; - } - - void AppendResponseHeaders(JNIEnv* env, - net::HttpResponseHeaders* headers) override { - // no-op - } -}; - -class NullStreamReaderDelegate : public StreamReaderDelegate { - public: - NullStreamReaderDelegate() {} - - std::unique_ptr<InputStream> OpenInputStream(JNIEnv* env, - const GURL& url) override { - return nullptr; - } -}; - -class HeaderAlteringStreamReaderDelegate : public NullStreamReaderDelegate { - public: - HeaderAlteringStreamReaderDelegate() {} - - void AppendResponseHeaders(JNIEnv* env, - net::HttpResponseHeaders* headers) override { - headers->ReplaceStatusLine(kStatusLine); - std::string headerLine(kCustomHeaderName); - headerLine.append(": "); - headerLine.append(kCustomHeaderValue); - headers->AddHeader(headerLine); - } - - static const int kResponseCode; - static const char* kStatusLine; - static const char* kCustomHeaderName; - static const char* kCustomHeaderValue; -}; - -const int HeaderAlteringStreamReaderDelegate::kResponseCode = 401; -const char* HeaderAlteringStreamReaderDelegate::kStatusLine = - "HTTP/1.1 401 Gone"; -const char* HeaderAlteringStreamReaderDelegate::kCustomHeaderName = - "X-Test-Header"; -const char* HeaderAlteringStreamReaderDelegate::kCustomHeaderValue = - "TestHeaderValue"; - -class MockInputStreamReader : public InputStreamReader { - public: - MockInputStreamReader() : InputStreamReader(new NotImplInputStream()) {} - ~MockInputStreamReader() {} - - MOCK_METHOD1(Seek, int(const net::HttpByteRange& byte_range)); - MOCK_METHOD2(ReadRawData, int(net::IOBuffer* buffer, int buffer_size)); -}; - - -class TestStreamReaderJob : public AndroidStreamReaderURLRequestJob { - public: - TestStreamReaderJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - std::unique_ptr<Delegate> delegate, - std::unique_ptr<InputStreamReader> stream_reader) - : AndroidStreamReaderURLRequestJob(request, - network_delegate, - std::move(delegate)), - stream_reader_(std::move(stream_reader)) { - } - - ~TestStreamReaderJob() override {} - - std::unique_ptr<InputStreamReader> CreateStreamReader( - InputStream* stream) override { - return std::move(stream_reader_); - } - - protected: - std::unique_ptr<InputStreamReader> stream_reader_; -}; - -} // namespace - - -class AndroidStreamReaderURLRequestJobTest : public Test { - public: - AndroidStreamReaderURLRequestJobTest() {} - - protected: - void SetUp() override { - context_.set_job_factory(&factory_); - context_.set_network_delegate(&network_delegate_); - req_ = context_.CreateRequest(GURL("content://foo"), - net::DEFAULT_PRIORITY, - &url_request_delegate_); - req_->set_method("GET"); - } - - void SetRange(net::URLRequest* req, int first_byte, int last_byte) { - net::HttpRequestHeaders headers; - headers.SetHeader(net::HttpRequestHeaders::kRange, - net::HttpByteRange::Bounded( - first_byte, last_byte).GetHeaderValue()); - req->SetExtraRequestHeaders(headers); - } - - void SetUpTestJob(std::unique_ptr<InputStreamReader> stream_reader) { - SetUpTestJob(std::move(stream_reader), - std::make_unique<StreamReaderDelegate>()); - } - - void SetUpTestJob(std::unique_ptr<InputStreamReader> stream_reader, - std::unique_ptr<AndroidStreamReaderURLRequestJob::Delegate> - stream_reader_delegate) { - std::unique_ptr<TestStreamReaderJob> test_stream_reader_job( - new TestStreamReaderJob(req_.get(), &network_delegate_, - std::move(stream_reader_delegate), - std::move(stream_reader))); - // The Interceptor is owned by the |factory_|. - std::unique_ptr<TestJobInterceptor> protocol_handler( - new TestJobInterceptor); - protocol_handler->set_main_intercept_job(std::move(test_stream_reader_job)); - bool set_protocol = - factory_.SetProtocolHandler("content", std::move(protocol_handler)); - DCHECK(set_protocol); - } - - base::test::ScopedTaskEnvironment scoped_task_environment_ = { - base::test::ScopedTaskEnvironment::MainThreadType::IO}; - TestURLRequestContext context_; - android_webview::AwURLRequestJobFactory factory_; - TestDelegate url_request_delegate_; - TestNetworkDelegate network_delegate_; - std::unique_ptr<URLRequest> req_; -}; - -TEST_F(AndroidStreamReaderURLRequestJobTest, ReadEmptyStream) { - std::unique_ptr<StrictMock<MockInputStreamReader>> stream_reader( - new StrictMock<MockInputStreamReader>()); - { - InSequence s; - EXPECT_CALL(*stream_reader, Seek(_)) - .WillOnce(Return(0)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Gt(0))) - .WillOnce(Return(0)); - } - - SetUpTestJob(std::move(stream_reader)); - - req_->Start(); - - // The TestDelegate will quit the message loop on request completion. - base::RunLoop().Run(); - - EXPECT_FALSE(url_request_delegate_.request_failed()); - EXPECT_EQ(1, network_delegate_.completed_requests()); - EXPECT_EQ(0, network_delegate_.error_count()); - EXPECT_EQ(200, req_->GetResponseCode()); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, ReadWithNullStream) { - SetUpTestJob(nullptr, std::make_unique<NullStreamReaderDelegate>()); - req_->Start(); - - // The TestDelegate will quit the message loop on request completion. - base::RunLoop().Run(); - - // The request_failed() method is named confusingly but all it checks is - // whether the request got as far as calling NotifyHeadersComplete. - EXPECT_FALSE(url_request_delegate_.request_failed()); - EXPECT_EQ(1, network_delegate_.completed_requests()); - // A null input stream shouldn't result in an error. See crbug.com/180950. - EXPECT_EQ(0, network_delegate_.error_count()); - EXPECT_EQ(404, req_->GetResponseCode()); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, ModifyHeadersAndStatus) { - SetUpTestJob(nullptr, std::make_unique<HeaderAlteringStreamReaderDelegate>()); - req_->Start(); - - // The TestDelegate will quit the message loop on request completion. - base::RunLoop().Run(); - - // The request_failed() method is named confusingly but all it checks is - // whether the request got as far as calling NotifyHeadersComplete. - EXPECT_FALSE(url_request_delegate_.request_failed()); - EXPECT_EQ(1, network_delegate_.completed_requests()); - // A null input stream shouldn't result in an error. See crbug.com/180950. - EXPECT_EQ(0, network_delegate_.error_count()); - EXPECT_EQ(HeaderAlteringStreamReaderDelegate::kResponseCode, - req_->GetResponseCode()); - EXPECT_EQ(HeaderAlteringStreamReaderDelegate::kStatusLine, - req_->response_headers()->GetStatusLine()); - EXPECT_TRUE(req_->response_headers()->HasHeader( - HeaderAlteringStreamReaderDelegate::kCustomHeaderName)); - std::string header_value; - EXPECT_TRUE(req_->response_headers()->EnumerateHeader( - NULL, HeaderAlteringStreamReaderDelegate::kCustomHeaderName, - &header_value)); - EXPECT_EQ(HeaderAlteringStreamReaderDelegate::kCustomHeaderValue, - header_value); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, ReadPartOfStream) { - const int bytes_available = 128; - const int offset = 32; - const int bytes_to_read = bytes_available - offset; - std::unique_ptr<StrictMock<MockInputStreamReader>> stream_reader( - new StrictMock<MockInputStreamReader>()); - { - InSequence s; - EXPECT_CALL(*stream_reader, Seek(_)) - .WillOnce(Return(bytes_available)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read))) - .WillOnce(Return(bytes_to_read/2)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read))) - .WillOnce(Return(bytes_to_read/2)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read))) - .WillOnce(Return(0)); - } - - SetUpTestJob(std::move(stream_reader)); - - SetRange(req_.get(), offset, bytes_available); - req_->Start(); - - base::RunLoop().Run(); - - EXPECT_FALSE(url_request_delegate_.request_failed()); - EXPECT_EQ(bytes_to_read, url_request_delegate_.bytes_received()); - EXPECT_EQ(1, network_delegate_.completed_requests()); - EXPECT_EQ(0, network_delegate_.error_count()); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, - ReadStreamWithMoreAvailableThanActual) { - const int bytes_available_reported = 190; - const int bytes_available = 128; - const int offset = 0; - const int bytes_to_read = bytes_available - offset; - std::unique_ptr<StrictMock<MockInputStreamReader>> stream_reader( - new StrictMock<MockInputStreamReader>()); - { - InSequence s; - EXPECT_CALL(*stream_reader, Seek(_)) - .WillOnce(Return(bytes_available_reported)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read))) - .WillOnce(Return(bytes_available)); - EXPECT_CALL(*stream_reader, ReadRawData(NotNull(), Ge(bytes_to_read))) - .WillOnce(Return(0)); - } - - SetUpTestJob(std::move(stream_reader)); - - SetRange(req_.get(), offset, bytes_available_reported); - req_->Start(); - - base::RunLoop().Run(); - - EXPECT_FALSE(url_request_delegate_.request_failed()); - EXPECT_EQ(bytes_to_read, url_request_delegate_.bytes_received()); - EXPECT_EQ(1, network_delegate_.completed_requests()); - EXPECT_EQ(0, network_delegate_.error_count()); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, DeleteJobMidWaySeek) { - const int offset = 20; - const int bytes_available = 128; - base::RunLoop loop; - std::unique_ptr<StrictMock<MockInputStreamReader>> stream_reader( - new StrictMock<MockInputStreamReader>()); - EXPECT_CALL(*stream_reader, Seek(_)) - .WillOnce(DoAll(InvokeWithoutArgs(&loop, &base::RunLoop::Quit), - Return(bytes_available))); - ON_CALL(*stream_reader, ReadRawData(_, _)) - .WillByDefault(Return(0)); - - SetUpTestJob(std::move(stream_reader)); - - SetRange(req_.get(), offset, bytes_available); - req_->Start(); - - loop.Run(); - - EXPECT_EQ(0, network_delegate_.completed_requests()); - req_->Cancel(); - EXPECT_EQ(1, network_delegate_.completed_requests()); -} - -TEST_F(AndroidStreamReaderURLRequestJobTest, DeleteJobMidWayRead) { - const int offset = 20; - const int bytes_available = 128; - base::RunLoop loop; - std::unique_ptr<StrictMock<MockInputStreamReader>> stream_reader( - new StrictMock<MockInputStreamReader>()); - EXPECT_CALL(*stream_reader, Seek(_)) - .WillOnce(Return(bytes_available)); - EXPECT_CALL(*stream_reader, ReadRawData(_, _)) - .WillOnce(DoAll(InvokeWithoutArgs(&loop, &base::RunLoop::Quit), - Return(bytes_available))); - - SetUpTestJob(std::move(stream_reader)); - - SetRange(req_.get(), offset, bytes_available); - req_->Start(); - - loop.Run(); - - EXPECT_EQ(0, network_delegate_.completed_requests()); - req_->Cancel(); - EXPECT_EQ(1, network_delegate_.completed_requests()); -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/aw_network_delegate.cc b/android_webview/browser/net/aw_network_delegate.cc deleted file mode 100644 index b896020..0000000 --- a/android_webview/browser/net/aw_network_delegate.cc +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/browser/net/aw_network_delegate.h" - -#include "android_webview/browser/aw_browser_context.h" -#include "android_webview/browser/aw_contents_client_bridge.h" -#include "android_webview/browser/aw_contents_io_thread_client.h" -#include "android_webview/browser/aw_cookie_access_policy.h" -#include "android_webview/browser/net/aw_web_resource_request.h" -#include "base/android/build_info.h" -#include "base/bind.h" -#include "base/task/post_task.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "net/base/completion_once_callback.h" -#include "net/base/net_errors.h" -#include "net/base/proxy_server.h" -#include "net/http/http_response_headers.h" -#include "net/proxy_resolution/proxy_info.h" -#include "net/url_request/url_request.h" - -using content::BrowserThread; - -namespace android_webview { - -AwNetworkDelegate::AwNetworkDelegate() {} - -AwNetworkDelegate::~AwNetworkDelegate() { -} - -int AwNetworkDelegate::OnBeforeStartTransaction( - net::URLRequest* request, - net::CompletionOnceCallback callback, - net::HttpRequestHeaders* headers) { - DCHECK(headers); - headers->SetHeaderIfMissing( - "X-Requested-With", - base::android::BuildInfo::GetInstance()->host_package_name()); - return net::OK; -} - -void AwNetworkDelegate::OnStartTransaction( - net::URLRequest* request, - const net::HttpRequestHeaders& headers) {} - -int AwNetworkDelegate::OnHeadersReceived( - net::URLRequest* request, - net::CompletionOnceCallback callback, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr<net::HttpResponseHeaders>* override_response_headers, - GURL* allowed_unsafe_redirect_url) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - return net::OK; -} - -bool AwNetworkDelegate::OnCanGetCookies(const net::URLRequest& request, - const net::CookieList& cookie_list, - bool allow_from_caller) { - return allow_from_caller && - AwCookieAccessPolicy::GetInstance()->AllowCookies(request); -} - -bool AwNetworkDelegate::OnCanSetCookie(const net::URLRequest& request, - const net::CanonicalCookie& cookie, - net::CookieOptions* options, - bool allow_from_caller) { - return allow_from_caller && - AwCookieAccessPolicy::GetInstance()->AllowCookies(request); -} - -bool AwNetworkDelegate::OnCanAccessFile( - const net::URLRequest& request, - const base::FilePath& original_path, - const base::FilePath& absolute_path) const { - return true; -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/aw_network_delegate.h b/android_webview/browser/net/aw_network_delegate.h deleted file mode 100644 index 136fdff..0000000 --- a/android_webview/browser/net/aw_network_delegate.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ANDROID_WEBVIEW_BROWSER_NET_AW_NETWORK_DELEGATE_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_AW_NETWORK_DELEGATE_H_ - -#include "base/macros.h" -#include "net/base/network_delegate_impl.h" - -namespace net { -class URLRequest; -} - -namespace android_webview { - -// WebView's implementation of the NetworkDelegate. -class AwNetworkDelegate : public net::NetworkDelegateImpl { - public: - AwNetworkDelegate(); - ~AwNetworkDelegate() override; - - private: - // NetworkDelegate implementation. - int OnBeforeStartTransaction(net::URLRequest* request, - net::CompletionOnceCallback callback, - net::HttpRequestHeaders* headers) override; - void OnStartTransaction(net::URLRequest* request, - const net::HttpRequestHeaders& headers) override; - int OnHeadersReceived( - net::URLRequest* request, - net::CompletionOnceCallback callback, - const net::HttpResponseHeaders* original_response_headers, - scoped_refptr<net::HttpResponseHeaders>* override_response_headers, - GURL* allowed_unsafe_redirect_url) override; - bool OnCanGetCookies(const net::URLRequest& request, - const net::CookieList& cookie_list, - bool allow_from_caller) override; - bool OnCanSetCookie(const net::URLRequest& request, - const net::CanonicalCookie& cookie, - net::CookieOptions* options, - bool allow_from_caller) override; - bool OnCanAccessFile(const net::URLRequest& request, - const base::FilePath& original_path, - const base::FilePath& absolute_path) const override; - - DISALLOW_COPY_AND_ASSIGN(AwNetworkDelegate); -}; - -} // namespace android_webview - -#endif // ANDROID_WEBVIEW_BROWSER_NET_AW_NETWORK_DELEGATE_H_
diff --git a/android_webview/browser/net/aw_request_interceptor.cc b/android_webview/browser/net/aw_request_interceptor.cc deleted file mode 100644 index 62c5340..0000000 --- a/android_webview/browser/net/aw_request_interceptor.cc +++ /dev/null
@@ -1,158 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/browser/net/aw_request_interceptor.h" - -#include <memory> -#include <utility> - -#include "android_webview/browser/aw_contents_io_thread_client.h" -#include "android_webview/browser/input_stream.h" -#include "android_webview/browser/net/android_stream_reader_url_request_job.h" -#include "android_webview/browser/net/aw_web_resource_request.h" -#include "android_webview/browser/net/aw_web_resource_response.h" -#include "base/bind.h" -#include "base/memory/weak_ptr.h" -#include "base/strings/string_number_conversions.h" -#include "base/supports_user_data.h" -#include "content/public/browser/browser_thread.h" -#include "net/http/http_response_headers.h" -#include "net/url_request/url_request_job.h" -#include "url/url_constants.h" - -namespace android_webview { - -namespace { - -const void* const kRequestAlreadyHasJobDataKey = &kRequestAlreadyHasJobDataKey; - -class StreamReaderJobDelegateImpl - : public AndroidStreamReaderURLRequestJob::Delegate { - public: - StreamReaderJobDelegateImpl( - std::unique_ptr<AwWebResourceResponse> aw_web_resource_response) - : aw_web_resource_response_(std::move(aw_web_resource_response)) { - DCHECK(aw_web_resource_response_); - } - - std::unique_ptr<InputStream> OpenInputStream(JNIEnv* env, - const GURL& url) override { - return aw_web_resource_response_->GetInputStream(env); - } - - void OnInputStreamOpenFailed(net::URLRequest* request, - bool* restart) override { - *restart = false; - } - - bool GetMimeType(JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* mime_type) override { - return aw_web_resource_response_->GetMimeType(env, mime_type); - } - - bool GetCharset(JNIEnv* env, - net::URLRequest* request, - android_webview::InputStream* stream, - std::string* charset) override { - return aw_web_resource_response_->GetCharset(env, charset); - } - - void AppendResponseHeaders(JNIEnv* env, - net::HttpResponseHeaders* headers) override { - int status_code; - std::string reason_phrase; - if (aw_web_resource_response_->GetStatusInfo( - env, &status_code, &reason_phrase)) { - std::string status_line("HTTP/1.1 "); - status_line.append(base::NumberToString(status_code)); - status_line.append(" "); - status_line.append(reason_phrase); - headers->ReplaceStatusLine(status_line); - } - aw_web_resource_response_->GetResponseHeaders(env, headers); - } - - private: - std::unique_ptr<AwWebResourceResponse> aw_web_resource_response_; -}; - -class ShouldInterceptRequestAdaptor - : public AndroidStreamReaderURLRequestJob::DelegateObtainer { - public: - explicit ShouldInterceptRequestAdaptor( - std::unique_ptr<AwContentsIoThreadClient> io_thread_client) - : io_thread_client_(std::move(io_thread_client)), weak_factory_(this) {} - ~ShouldInterceptRequestAdaptor() override {} - - void ObtainDelegate(net::URLRequest* request, Callback callback) override {} - - private: - void WebResourceResponseObtained( - std::unique_ptr<AwWebResourceResponse> response) { - if (response) { - std::move(callback_).Run( - std::make_unique<StreamReaderJobDelegateImpl>(std::move(response))); - } else { - std::move(callback_).Run(nullptr); - } - } - - std::unique_ptr<AwContentsIoThreadClient> io_thread_client_; - Callback callback_; - base::WeakPtrFactory<ShouldInterceptRequestAdaptor> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(ShouldInterceptRequestAdaptor); -}; - -std::unique_ptr<AwContentsIoThreadClient> GetCorrespondingIoThreadClient( - net::URLRequest* request) { - return nullptr; -} - -} // namespace - -AwRequestInterceptor::AwRequestInterceptor() {} - -AwRequestInterceptor::~AwRequestInterceptor() {} - -net::URLRequestJob* AwRequestInterceptor::MaybeInterceptRequest( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - - // MaybeInterceptRequest can be called multiple times for the same request. - if (request->GetUserData(kRequestAlreadyHasJobDataKey)) - return nullptr; - - // It's not useful to emit shouldInterceptRequest for blob URLs, so we - // intentionally skip the callback for all such URLs. See - // http://crbug.com/822983. - if (request->url().SchemeIs(url::kBlobScheme)) { - return nullptr; - } - - std::unique_ptr<AwContentsIoThreadClient> io_thread_client = - GetCorrespondingIoThreadClient(request); - - if (!io_thread_client) - return nullptr; - - GURL referrer(request->referrer()); - if (referrer.is_valid() && - (!request->is_pending() || request->is_redirecting())) { - request->SetExtraRequestHeaderByName(net::HttpRequestHeaders::kReferer, - referrer.spec(), true); - } - request->SetUserData(kRequestAlreadyHasJobDataKey, - std::make_unique<base::SupportsUserData::Data>()); - return new AndroidStreamReaderURLRequestJob( - request, network_delegate, - std::make_unique<ShouldInterceptRequestAdaptor>( - std::move(io_thread_client)), - true); -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/aw_request_interceptor.h b/android_webview/browser/net/aw_request_interceptor.h deleted file mode 100644 index db9ffc5..0000000 --- a/android_webview/browser/net/aw_request_interceptor.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ANDROID_WEBVIEW_BROWSER_NET_AW_REQUEST_INTERCEPTOR_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_AW_REQUEST_INTERCEPTOR_H_ - -#include <memory> - -#include "base/macros.h" -#include "net/url_request/url_request_interceptor.h" - -namespace net { -class URLRequest; -class URLRequestJob; -class NetworkDelegate; -} - -namespace android_webview { - -// This class allows the Java-side embedder to substitute the default -// URLRequest of a given request for an alternative job that will read data -// from a Java stream. -class AwRequestInterceptor : public net::URLRequestInterceptor { - public: - AwRequestInterceptor(); - ~AwRequestInterceptor() override; - - // net::URLRequestInterceptor override -------------------------------------- - net::URLRequestJob* MaybeInterceptRequest( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(AwRequestInterceptor); -}; - -} // namespace android_webview - -#endif // ANDROID_WEBVIEW_BROWSER_NET_AW_REQUEST_INTERCEPTOR_H_
diff --git a/android_webview/browser/net/aw_url_request_context_getter.cc b/android_webview/browser/net/aw_url_request_context_getter.cc index 40d194f..3dbd1cb 100644 --- a/android_webview/browser/net/aw_url_request_context_getter.cc +++ b/android_webview/browser/net/aw_url_request_context_getter.cc
@@ -15,9 +15,6 @@ #include "android_webview/browser/aw_feature_list.h" #include "android_webview/browser/net/aw_cookie_store_wrapper.h" #include "android_webview/browser/net/aw_http_user_agent_settings.h" -#include "android_webview/browser/net/aw_network_delegate.h" -#include "android_webview/browser/net/aw_request_interceptor.h" -#include "android_webview/browser/net/aw_url_request_job_factory.h" #include "android_webview/browser/net/init_native_callback.h" #include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/common/aw_content_client.h" @@ -83,98 +80,6 @@ // On apps targeting API level O or later, check cleartext is enforced. bool g_check_cleartext_permitted = false; - -const char kProxyServerSwitch[] = "proxy-server"; -const char kProxyBypassListSwitch[] = "proxy-bypass-list"; - -std::string GetCmdlineOverridesForHostResolver() { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - return command_line.GetSwitchValueASCII( - network::switches::kHostResolverRules); -} - -void ApplyCmdlineOverridesToNetworkSessionParams( - net::HttpNetworkSession::Params* params) { - int value; - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) { - base::StringToInt(command_line.GetSwitchValueASCII( - switches::kTestingFixedHttpPort), &value); - params->testing_fixed_http_port = value; - } - if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) { - base::StringToInt(command_line.GetSwitchValueASCII( - switches::kTestingFixedHttpsPort), &value); - params->testing_fixed_https_port = value; - } - if (command_line.HasSwitch(switches::kIgnoreCertificateErrors)) { - params->ignore_certificate_errors = true; - } -} - -std::unique_ptr<net::URLRequestJobFactory> CreateJobFactory( - content::ProtocolHandlerMap* protocol_handlers, - content::URLRequestInterceptorScopedVector request_interceptors) { - std::unique_ptr<AwURLRequestJobFactory> aw_job_factory( - new AwURLRequestJobFactory); - // Note that the registered schemes must also be specified in - // AwContentBrowserClient::IsHandledURL. - bool set_protocol = aw_job_factory->SetProtocolHandler( - url::kFileScheme, - std::make_unique<net::FileProtocolHandler>( - base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))); - DCHECK(set_protocol); - set_protocol = aw_job_factory->SetProtocolHandler( - url::kDataScheme, std::make_unique<net::DataProtocolHandler>()); - DCHECK(set_protocol); - set_protocol = aw_job_factory->SetProtocolHandler( - url::kBlobScheme, - base::WrapUnique((*protocol_handlers)[url::kBlobScheme].release())); - DCHECK(set_protocol); - set_protocol = aw_job_factory->SetProtocolHandler( - url::kFileSystemScheme, - base::WrapUnique((*protocol_handlers)[url::kFileSystemScheme].release())); - DCHECK(set_protocol); - set_protocol = aw_job_factory->SetProtocolHandler( - content::kChromeUIScheme, - base::WrapUnique( - (*protocol_handlers)[content::kChromeUIScheme].release())); - DCHECK(set_protocol); - protocol_handlers->clear(); - - // Note that even though the content:// scheme handler is created here, - // it cannot be used by child processes until access to it is granted via - // ChildProcessSecurityPolicy::GrantRequestScheme(). This is done in - // AwContentBrowserClient. - request_interceptors.push_back(CreateAndroidContentRequestInterceptor()); - request_interceptors.push_back(CreateAndroidAssetFileRequestInterceptor()); - // The AwRequestInterceptor must come after the content and asset file job - // factories. This for WebViewClassic compatibility where it was not - // possible to intercept resource loads to resolvable content:// and - // file:// URIs. - // This logical dependency is also the reason why the Content - // URLRequestInterceptor has to be added as an interceptor rather than as a - // ProtocolHandler. - request_interceptors.push_back(std::make_unique<AwRequestInterceptor>()); - - // The chain of responsibility will execute the handlers in reverse to the - // order in which the elements of the chain are created. - std::unique_ptr<net::URLRequestJobFactory> job_factory( - std::move(aw_job_factory)); - for (auto i = request_interceptors.rbegin(); i != request_interceptors.rend(); - ++i) { - job_factory.reset(new net::URLRequestInterceptingJobFactory( - std::move(job_factory), std::move(*i))); - } - request_interceptors.clear(); - - return job_factory; -} - } // namespace AwURLRequestContextGetter::AwURLRequestContextGetter( @@ -191,7 +96,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); scoped_refptr<base::SingleThreadTaskRunner> io_thread_proxy = - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}); auth_server_allowlist_.Init( prefs::kAuthServerWhitelist, user_pref_service, @@ -256,91 +161,8 @@ } void AwURLRequestContextGetter::InitializeURLRequestContext() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - DCHECK(!url_request_context_); - DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService)); - - net::URLRequestContextBuilder builder; - - builder.set_network_delegate(std::make_unique<AwNetworkDelegate>()); -#if !BUILDFLAG(DISABLE_FTP_SUPPORT) - builder.set_ftp_enabled(false); // Android WebView does not support ftp yet. -#endif - DCHECK(proxy_config_service_.get()); - - // Android provides a local HTTP proxy that handles all the proxying. - // Create the proxy without a resolver since we rely on this local HTTP proxy. - // TODO(sgurun) is this behavior guaranteed through SDK? - - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - if (command_line.HasSwitch(kProxyServerSwitch)) { - std::string proxy = command_line.GetSwitchValueASCII(kProxyServerSwitch); - net::ProxyConfig proxy_config; - proxy_config.proxy_rules().ParseFromString(proxy); - if (command_line.HasSwitch(kProxyBypassListSwitch)) { - std::string bypass_list = - command_line.GetSwitchValueASCII(kProxyBypassListSwitch); - proxy_config.proxy_rules().bypass_rules.ParseFromString(bypass_list); - } - - builder.set_proxy_resolution_service( - net::ProxyResolutionService::CreateFixed(net::ProxyConfigWithAnnotation( - proxy_config, NO_TRAFFIC_ANNOTATION_YET))); - } else { - builder.set_proxy_resolution_service( - net::ProxyResolutionService::CreateWithoutProxyResolver( - std::move(proxy_config_service_), net_log_)); - } - builder.set_net_log(net_log_); - builder.SetCookieStore(std::make_unique<AwCookieStoreWrapper>()); - - net::URLRequestContextBuilder::HttpCacheParams cache_params; - cache_params.type = - net::URLRequestContextBuilder::HttpCacheParams::DISK_SIMPLE; - cache_params.max_size = GetHttpCacheSize(); - cache_params.path = cache_path_; - builder.EnableHttpCache(cache_params); - - net::HttpNetworkSession::Params network_session_params; - ApplyCmdlineOverridesToNetworkSessionParams(&network_session_params); - builder.set_http_network_session_params(network_session_params); - - // Quic is only supported when network service is enabled. - builder.SetSpdyAndQuicEnabled(true, false); - - builder.SetHttpAuthHandlerFactory(CreateAuthHandlerFactory()); - builder.set_host_mapping_rules(GetCmdlineOverridesForHostResolver()); - - // Context copy allowed because NetworkService is confirmed disabled. - builder.set_allow_copy(); - - builder.set_enable_brotli(base::FeatureList::IsEnabled( - android_webview::features::kWebViewBrotliSupport)); - - url_request_context_ = builder.Build(); - - // For Android WebView, do not enforce policies that are not consistent with - // the underlying OS validator. - // This means not enforcing the Legacy Symantec PKI policies outlined in - // https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html - // or disabling SHA-1 for locally-installed trust anchors. - net::CertVerifier::Config config; - config.enable_sha1_local_anchors = true; - config.disable_symantec_enforcement = true; - url_request_context_->cert_verifier()->SetConfig(config); - -#if DCHECK_IS_ON() - g_created_url_request_context_builder = true; -#endif - url_request_context_->set_check_cleartext_permitted( - g_check_cleartext_permitted); - - job_factory_ = - CreateJobFactory(&protocol_handlers_, std::move(request_interceptors_)); - url_request_context_->set_job_factory(job_factory_.get()); - url_request_context_->set_http_user_agent_settings( - http_user_agent_settings_.get()); + // network service is enabled by default, this code path is never executed. + NOTREACHED(); } // static @@ -361,7 +183,7 @@ scoped_refptr<base::SingleThreadTaskRunner> AwURLRequestContextGetter::GetNetworkTaskRunner() const { - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + return base::CreateSingleThreadTaskRunner({BrowserThread::IO}); } void AwURLRequestContextGetter::SetHandlersAndInterceptors(
diff --git a/android_webview/browser/net/aw_url_request_context_getter.h b/android_webview/browser/net/aw_url_request_context_getter.h index 1743ee81..486546a 100644 --- a/android_webview/browser/net/aw_url_request_context_getter.h +++ b/android_webview/browser/net/aw_url_request_context_getter.h
@@ -28,7 +28,6 @@ class ProxyConfigServiceAndroid; class ProxyConfigService; class URLRequestContext; -class URLRequestJobFactory; } namespace android_webview { @@ -86,7 +85,6 @@ net::NetLog* net_log_; std::unique_ptr<net::ProxyConfigServiceAndroid> proxy_config_service_; net::ProxyConfigServiceAndroid* proxy_config_service_android_; - std::unique_ptr<net::URLRequestJobFactory> job_factory_; std::unique_ptr<net::HttpUserAgentSettings> http_user_agent_settings_; std::unique_ptr<net::FileNetLogObserver> file_net_log_observer_; // http_auth_preferences_ holds the preferences for the negotiate
diff --git a/android_webview/browser/net/aw_url_request_context_getter_unittest.cc b/android_webview/browser/net/aw_url_request_context_getter_unittest.cc deleted file mode 100644 index 6289d94..0000000 --- a/android_webview/browser/net/aw_url_request_context_getter_unittest.cc +++ /dev/null
@@ -1,184 +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 "android_webview/browser/net/aw_url_request_context_getter.h" - -#include <memory> - -#include "android_webview/browser/aw_browser_context.h" -#include "android_webview/browser/aw_browser_process.h" -#include "base/android/jni_android.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/ref_counted.h" -#include "base/task/post_task.h" -#include "base/test/scoped_feature_list.h" -#include "components/prefs/testing_pref_service.h" -#include "content/public/browser/browser_task_traits.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/common/url_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "net/base/net_errors.h" -#include "net/base/test_completion_callback.h" -#include "net/cert/cert_verifier.h" -#include "net/cert/test_root_certs.h" -#include "net/log/net_log.h" -#include "net/log/net_log_with_source.h" -#include "net/proxy_resolution/proxy_config_service.h" -#include "net/proxy_resolution/proxy_config_service_android.h" -#include "net/proxy_resolution/proxy_resolution_service.h" -#include "net/test/cert_test_util.h" -#include "net/test/gtest_util.h" -#include "net/test/test_data_directory.h" -#include "net/test/url_request/url_request_failed_job.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_job_factory.h" -#include "services/network/public/cpp/features.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/boringssl/src/include/openssl/pool.h" - -namespace android_webview { - -namespace { - -// A ProtocolHandler that will immediately fail all jobs. -class FailingProtocolHandler - : public net::URLRequestJobFactory::ProtocolHandler { - public: - net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - return new net::URLRequestFailedJob(request, network_delegate, - net::URLRequestFailedJob::START, - net::ERR_FAILED); - } -}; - -} // namespace - -class AwURLRequestContextGetterTest : public ::testing::Test { - public: - AwURLRequestContextGetterTest() = default; - - protected: - void SetUp() override { - // These are the pre-network service tests. Forcing network service to be - // disabled and these tests will be deleted in a future CL. - scoped_feature_list_.InitWithFeatures({}, - {network::features::kNetworkService}); - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - env_ = base::android::AttachCurrentThread(); - ASSERT_TRUE(env_); - - pref_service_ = std::make_unique<TestingPrefServiceSimple>(); - AwBrowserProcess::RegisterNetworkContextLocalStatePrefs( - pref_service_->registry()); - - std::unique_ptr<net::ProxyConfigServiceAndroid> config_service_android; - config_service_android.reset(static_cast<net::ProxyConfigServiceAndroid*>( - net::ProxyResolutionService::CreateSystemProxyConfigService( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})) - .release())); - - getter_ = base::MakeRefCounted<android_webview::AwURLRequestContextGetter>( - temp_dir_.GetPath(), std::move(config_service_android), - pref_service_.get(), &net_log_); - - // AwURLRequestContextGetter implicitly depends on having protocol handlers - // provided for url::kBlobScheme, url::kFileSystemScheme, and - // content::kChromeUIScheme, so provide testing values here. - content::ProtocolHandlerMap fake_handlers; - fake_handlers[url::kBlobScheme].reset(new FailingProtocolHandler()); - fake_handlers[url::kFileSystemScheme].reset(new FailingProtocolHandler()); - fake_handlers[content::kChromeUIScheme].reset(new FailingProtocolHandler()); - content::URLRequestInterceptorScopedVector interceptors; - getter_->SetHandlersAndInterceptors(&fake_handlers, - std::move(interceptors)); - } - - base::test::ScopedFeatureList scoped_feature_list_; - content::TestBrowserThreadBundle thread_bundle_; - base::ScopedTempDir temp_dir_; - JNIEnv* env_; - net::NetLog net_log_; - std::unique_ptr<TestingPrefServiceSimple> pref_service_; - scoped_refptr<android_webview::AwURLRequestContextGetter> getter_; -}; - -// Tests that constraints on trust for Symantec-issued certificates are not -// enforced for the AwURLRequestContext(Getter), as it should behave like -// the Android system. -TEST_F(AwURLRequestContextGetterTest, SymantecPoliciesExempted) { - net::URLRequestContext* context = getter_->GetURLRequestContext(); - ASSERT_TRUE(context); - - scoped_refptr<net::X509Certificate> cert = - net::CreateCertificateChainFromFile(net::GetTestCertsDirectory(), - "www.ahrn.com.pem", - net::X509Certificate::FORMAT_AUTO); - ASSERT_TRUE(cert); - ASSERT_EQ(2u, cert->intermediate_buffers().size()); - - scoped_refptr<net::X509Certificate> root = - net::X509Certificate::CreateFromBuffer( - bssl::UpRef(cert->intermediate_buffers().back()), {}); - ASSERT_TRUE(root); - net::ScopedTestRoot test_root(root.get()); - - net::CertVerifyResult result; - int flags = 0; - net::TestCompletionCallback callback; - std::unique_ptr<net::CertVerifier::Request> request; - int error = context->cert_verifier()->Verify( - net::CertVerifier::RequestParams(cert, "www.ahrn.com", flags, - /*ocsp_response=*/std::string(), - /*sct_list=*/std::string()), - &result, callback.callback(), &request, net::NetLogWithSource()); - EXPECT_THAT(error, net::test::IsError(net::ERR_IO_PENDING)); - EXPECT_TRUE(request); - - error = callback.WaitForResult(); - EXPECT_THAT(error, net::test::IsError(net::OK)); -} - -// Tests that SHA-1 is still allowed for locally-installed trust anchors, -// including those in application manifests, as it should behave like -// the Android system. -TEST_F(AwURLRequestContextGetterTest, SHA1LocalAnchorsAllowed) { - net::URLRequestContext* context = getter_->GetURLRequestContext(); - ASSERT_TRUE(context); - - net::CertificateList certs; - ASSERT_TRUE(net::LoadCertificateFiles( - {"weak_digest_sha1_ee.pem", "weak_digest_sha1_intermediate.pem", - "weak_digest_sha1_root.pem"}, - &certs)); - ASSERT_EQ(3u, certs.size()); - - std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates; - intermediates.push_back(bssl::UpRef(certs[1]->cert_buffer())); - scoped_refptr<net::X509Certificate> cert = - net::X509Certificate::CreateFromBuffer( - bssl::UpRef(certs[0]->cert_buffer()), std::move(intermediates)); - ASSERT_TRUE(cert); - - net::ScopedTestRoot test_root(certs[2].get()); - - net::CertVerifyResult result; - int flags = 0; - net::TestCompletionCallback callback; - std::unique_ptr<net::CertVerifier::Request> request; - int error = context->cert_verifier()->Verify( - net::CertVerifier::RequestParams(cert, "127.0.0.1", flags, - /*ocsp_response=*/std::string(), - /*sct_list=*/std::string()), - &result, callback.callback(), &request, net::NetLogWithSource()); - EXPECT_THAT(error, net::test::IsError(net::ERR_IO_PENDING)); - EXPECT_TRUE(request); - - error = callback.WaitForResult(); - EXPECT_THAT(error, net::test::IsError(net::OK)); -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/aw_url_request_job_factory.cc b/android_webview/browser/net/aw_url_request_job_factory.cc deleted file mode 100644 index 93884ae..0000000 --- a/android_webview/browser/net/aw_url_request_job_factory.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "android_webview/browser/net/aw_url_request_job_factory.h" - -#include <utility> - -#include "net/base/net_errors.h" -#include "net/url_request/url_request_error_job.h" -#include "net/url_request/url_request_job_factory_impl.h" -#include "net/url_request/url_request_job_manager.h" - -using net::NetworkDelegate; -using net::URLRequest; -using net::URLRequestJob; - -namespace android_webview { - -AwURLRequestJobFactory::AwURLRequestJobFactory() - : next_factory_(new net::URLRequestJobFactoryImpl()) { -} - -AwURLRequestJobFactory::~AwURLRequestJobFactory() { -} - -bool AwURLRequestJobFactory::IsHandledProtocol( - const std::string& scheme) const { - // This introduces a dependency on the URLRequestJobManager - // implementation. The assumption is that if true is returned from this - // method it is still valid to return NULL from the - // MaybeCreateJobWithProtocolHandler method and in that case the - // URLRequestJobManager will try and create the URLRequestJob by using the - // set of built in handlers. - return true; -} - -URLRequestJob* AwURLRequestJobFactory::MaybeCreateJobWithProtocolHandler( - const std::string& scheme, - URLRequest* request, - NetworkDelegate* network_delegate) const { - URLRequestJob* job = next_factory_->MaybeCreateJobWithProtocolHandler( - scheme, request, network_delegate); - - if (job) - return job; - - // If URLRequest supports the scheme NULL should be returned from this method. - // In that case the built in handlers will then be used to create the job. - // NOTE(joth): See the assumption in IsHandledProtocol above. - if (net::URLRequest::IsHandledProtocol(scheme)) - return NULL; - - return new net::URLRequestErrorJob( - request, network_delegate, net::ERR_UNKNOWN_URL_SCHEME); -} - -net::URLRequestJob* AwURLRequestJobFactory::MaybeInterceptRedirect( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& location) const { - return next_factory_->MaybeInterceptRedirect( - request, network_delegate, location); -} - -net::URLRequestJob* AwURLRequestJobFactory::MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const { - return next_factory_->MaybeInterceptResponse(request, network_delegate); -} - -bool AwURLRequestJobFactory::SetProtocolHandler( - const std::string& scheme, - std::unique_ptr<ProtocolHandler> protocol_handler) { - return next_factory_->SetProtocolHandler(scheme, std::move(protocol_handler)); -} - -bool AwURLRequestJobFactory::IsSafeRedirectTarget(const GURL& location) const { - return next_factory_->IsSafeRedirectTarget(location); -} - -} // namespace android_webview
diff --git a/android_webview/browser/net/aw_url_request_job_factory.h b/android_webview/browser/net/aw_url_request_job_factory.h deleted file mode 100644 index 289efcf..0000000 --- a/android_webview/browser/net/aw_url_request_job_factory.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef ANDROID_WEBVIEW_BROWSER_NET_AW_URL_REQUEST_JOB_FACTORY_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_AW_URL_REQUEST_JOB_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "net/url_request/url_request_job_factory.h" - -namespace net { -class URLRequestJobFactoryImpl; -} // namespace net - -namespace android_webview { - -// android_webview uses a custom URLRequestJobFactoryImpl to support -// navigation interception and URLRequestJob interception for navigations to -// url with unsupported schemes. -// This is achieved by returning a URLRequestErrorJob for schemes that would -// otherwise be unhandled, which gives the embedder an opportunity to intercept -// the request. -class AwURLRequestJobFactory : public net::URLRequestJobFactory { - public: - AwURLRequestJobFactory(); - ~AwURLRequestJobFactory() override; - - bool SetProtocolHandler(const std::string& scheme, - std::unique_ptr<ProtocolHandler> protocol_handler); - - // net::URLRequestJobFactory implementation. - net::URLRequestJob* MaybeCreateJobWithProtocolHandler( - const std::string& scheme, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override; - - net::URLRequestJob* MaybeInterceptRedirect( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& location) const override; - - net::URLRequestJob* MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override; - - bool IsHandledProtocol(const std::string& scheme) const override; - bool IsSafeRedirectTarget(const GURL& location) const override; - - private: - // By default calls are forwarded to this factory, to avoid having to - // subclass an existing implementation class. - std::unique_ptr<net::URLRequestJobFactoryImpl> next_factory_; - - DISALLOW_COPY_AND_ASSIGN(AwURLRequestJobFactory); -}; - -} // namespace android_webview - -#endif // ANDROID_WEBVIEW_BROWSER_NET_AW_URL_REQUEST_JOB_FACTORY_H_
diff --git a/android_webview/browser/net/init_native_callback.cc b/android_webview/browser/net/init_native_callback.cc index 5099e80b..ece1dd8 100644 --- a/android_webview/browser/net/init_native_callback.cc +++ b/android_webview/browser/net/init_native_callback.cc
@@ -5,7 +5,6 @@ #include "android_webview/browser/net/init_native_callback.h" #include "android_webview/browser/android_protocol_handler.h" -#include "android_webview/browser/net/aw_url_request_job_factory.h" #include "base/callback.h" #include "base/single_thread_task_runner.h" #include "net/url_request/url_request_interceptor.h"
diff --git a/android_webview/browser/network_service/android_stream_reader_url_loader.cc b/android_webview/browser/network_service/android_stream_reader_url_loader.cc index 17bd726..d3aa7e55 100644 --- a/android_webview/browser/network_service/android_stream_reader_url_loader.cc +++ b/android_webview/browser/network_service/android_stream_reader_url_loader.cc
@@ -134,8 +134,8 @@ return; } - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce( &OpenInputStreamOnWorkerThread, base::ThreadTaskRunnerHandle::Get(), // This is intentional - the loader could be deleted while the @@ -186,8 +186,8 @@ input_stream_reader_wrapper_ = base::MakeRefCounted<InputStreamReaderWrapper>( std::move(input_stream), std::move(input_stream_reader)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&InputStreamReaderWrapper::Seek, input_stream_reader_wrapper_, byte_range_), base::BindOnce(&AndroidStreamReaderURLLoader::OnReaderSeekCompleted, @@ -332,8 +332,8 @@ } // TODO(timvolodine): consider using a sequenced task runner. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce( &InputStreamReaderWrapper::ReadRawData, input_stream_reader_wrapper_, base::RetainedRef(buffer.get()), base::checked_cast<int>(num_bytes)),
diff --git a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc index b1d84a8a..c38ba61 100644 --- a/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc +++ b/android_webview/browser/network_service/aw_proxying_restricted_cookie_manager.cc
@@ -51,7 +51,7 @@ network::mojom::RestrictedCookieManagerRequest request) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &AwProxyingRestrictedCookieManager::CreateAndBindOnIoThread,
diff --git a/android_webview/browser/network_service/aw_proxying_url_loader_factory.cc b/android_webview/browser/network_service/aw_proxying_url_loader_factory.cc index db361f58..2bd36cb 100644 --- a/android_webview/browser/network_service/aw_proxying_url_loader_factory.cc +++ b/android_webview/browser/network_service/aw_proxying_url_loader_factory.cc
@@ -499,7 +499,7 @@ std::unique_ptr<AwContentsClientBridge::HttpErrorInfo> error_info = AwContentsClientBridge::ExtractHttpErrorInfo(head.headers.get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&OnReceivedHttpErrorOnUiThread, process_id_, request_.render_frame_id, AwWebResourceRequest(request_), @@ -516,7 +516,7 @@ if (ParseHeader(header_string, ALLOW_ANY_REALM, &header_data)) { // TODO(timvolodine): consider simplifying this and above callback // code, crbug.com/897149. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&OnNewLoginRequestOnUiThread, process_id_, request_.render_frame_id, header_data.realm, @@ -692,7 +692,7 @@ return; sent_error_callback_ = true; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&OnReceivedErrorOnUiThread, process_id_, request_.render_frame_id, AwWebResourceRequest(request_),
diff --git a/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc index eda44e6..fd9fe9f 100644 --- a/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc +++ b/android_webview/browser/safe_browsing/aw_safe_browsing_ui_manager.cc
@@ -100,7 +100,7 @@ AwSafeBrowsingUIManager::GetURLLoaderFactoryOnIOThread() { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!shared_url_loader_factory_on_io_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&AwSafeBrowsingUIManager::CreateURLLoaderFactoryForIO, this, MakeRequest(&url_loader_factory_on_io_)));
diff --git a/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc index 3789984..99271761 100644 --- a/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc +++ b/android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.cc
@@ -50,7 +50,7 @@ AwWebResourceRequest request(resource.url.spec(), method, is_main_frame, has_user_gesture, headers); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&AwUrlCheckerDelegateImpl::StartApplicationResponse, ui_manager_, resource, std::move(request))); @@ -137,7 +137,7 @@ bool proceed; switch (action) { case SafeBrowsingAction::SHOW_INTERSTITIAL: - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &AwUrlCheckerDelegateImpl::StartDisplayingDefaultBlockingPage, @@ -183,8 +183,8 @@ } // Reporting back that it is not okay to proceed with loading the URL. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(resource.callback, false)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(resource.callback, false)); } } // namespace android_webview
diff --git a/android_webview/browser/tracing/aw_tracing_controller.cc b/android_webview/browser/tracing/aw_tracing_controller.cc index c81c5a2..f6948cf6 100644 --- a/android_webview/browser/tracing/aw_tracing_controller.cc +++ b/android_webview/browser/tracing/aw_tracing_controller.cc
@@ -45,15 +45,14 @@ void ReceiveTraceFinalContents( std::unique_ptr<const base::DictionaryValue> metadata) override { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(completed_callback_), std::move(metadata))); } void ReceiveTraceChunk(std::unique_ptr<std::string> chunk) override { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(received_chunk_callback_, std::move(chunk))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(received_chunk_callback_, std::move(chunk))); } explicit AwTraceDataEndpoint(ReceivedChunkCallback received_chunk_callback,
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java index 7763d394..bf38567 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromium.java
@@ -60,13 +60,13 @@ import org.chromium.android_webview.AwPrintDocumentAdapter; import org.chromium.android_webview.AwSettings; import org.chromium.android_webview.ResourcesContextWrapperFactory; -import org.chromium.android_webview.ScopedSysTraceEvent; import org.chromium.android_webview.gfx.AwDrawFnImpl; import org.chromium.android_webview.renderer_priority.RendererPriority; import org.chromium.base.BuildInfo; import org.chromium.base.ThreadUtils; import org.chromium.base.metrics.CachedMetrics.EnumeratedHistogramSample; import org.chromium.base.metrics.CachedMetrics.TimesHistogramSample; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.PostTask; import org.chromium.components.autofill.AutofillProvider; import org.chromium.content_public.browser.NavigationHistory;
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java index 7e7d66f7..375c31d 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumAwInit.java
@@ -33,7 +33,6 @@ import org.chromium.android_webview.AwTracingController; import org.chromium.android_webview.HttpAuthDatabase; import org.chromium.android_webview.R; -import org.chromium.android_webview.ScopedSysTraceEvent; import org.chromium.android_webview.VariationsSeedLoader; import org.chromium.android_webview.WebViewChromiumRunQueue; import org.chromium.android_webview.common.AwResource; @@ -51,6 +50,7 @@ import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.metrics.CachedMetrics; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; import org.chromium.content_public.browser.UiThreadTaskTraits;
diff --git a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java index c23cbd6..bbeee392 100644 --- a/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java +++ b/android_webview/glue/java/src/com/android/webview/chromium/WebViewChromiumFactoryProvider.java
@@ -36,7 +36,6 @@ import org.chromium.android_webview.AwSettings; import org.chromium.android_webview.AwSwitches; import org.chromium.android_webview.ResourcesContextWrapperFactory; -import org.chromium.android_webview.ScopedSysTraceEvent; import org.chromium.android_webview.WebViewChromiumRunQueue; import org.chromium.android_webview.command_line.CommandLineUtil; import org.chromium.base.BuildInfo; @@ -51,6 +50,7 @@ import org.chromium.base.annotations.DoNotInline; import org.chromium.base.library_loader.NativeLibraries; import org.chromium.base.metrics.CachedMetrics.TimesHistogramSample; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.components.autofill.AutofillProvider; import org.chromium.content_public.browser.LGEmailActionModeWorkaround;
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 bded5066..6071e69 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
@@ -47,12 +47,12 @@ import org.chromium.android_webview.AwWebResourceResponse; import org.chromium.android_webview.JsPromptResultReceiver; import org.chromium.android_webview.JsResultReceiver; -import org.chromium.android_webview.ScopedSysTraceEvent; import org.chromium.android_webview.permission.AwPermissionRequest; import org.chromium.android_webview.permission.Resource; import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.TraceEvent; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.PostTask; import org.chromium.content_public.browser.UiThreadTaskTraits;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwAutofillProvider.java b/android_webview/java/src/org/chromium/android_webview/AwAutofillProvider.java index ab8e2b6..d53ef79 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwAutofillProvider.java +++ b/android_webview/java/src/org/chromium/android_webview/AwAutofillProvider.java
@@ -18,6 +18,7 @@ import android.view.autofill.AutofillValue; import org.chromium.base.ThreadUtils; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.components.autofill.AutofillProvider; import org.chromium.components.autofill.FormData; import org.chromium.components.autofill.FormFieldData;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java index 0967fb7..f7578aa3 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java +++ b/android_webview/java/src/org/chromium/android_webview/AwBrowserProcess.java
@@ -28,6 +28,7 @@ import org.chromium.base.library_loader.LibraryLoader; import org.chromium.base.library_loader.LibraryProcessType; import org.chromium.base.library_loader.ProcessInitException; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskRunner; import org.chromium.base.task.TaskTraits;
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 e960126..cf3b99b 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -65,6 +65,7 @@ import org.chromium.base.annotations.CalledByNativeUnchecked; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.base.task.AsyncTask; import org.chromium.base.task.PostTask; import org.chromium.components.autofill.AutofillProvider;
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 994e270..05f5450 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContentsClient.java
@@ -25,6 +25,7 @@ import org.chromium.base.Callback; import org.chromium.base.Log; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.content_public.common.ContentUrlConstants; import java.security.Principal;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConfigHelper.java b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConfigHelper.java index 052cfaa..bb1f9d3 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConfigHelper.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSafeBrowsingConfigHelper.java
@@ -15,6 +15,7 @@ import org.chromium.base.Log; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.ScopedSysTraceEvent; /** * Helper class for getting the configuration settings related to safebrowsing in WebView.
diff --git a/android_webview/java/src/org/chromium/android_webview/ScopedSysTraceEvent.java b/android_webview/java/src/org/chromium/android_webview/ScopedSysTraceEvent.java index 4bb2397b..004067a 100644 --- a/android_webview/java/src/org/chromium/android_webview/ScopedSysTraceEvent.java +++ b/android_webview/java/src/org/chromium/android_webview/ScopedSysTraceEvent.java
@@ -6,9 +6,10 @@ import android.os.Trace; +// TODO(changwan): remove this file once downstream change lands. /** * An alternative to @{TraceEvent} that allows us to trace events before native - * initialization for WebView. + * initialization. * * Note that TraceEvent / EarlyTraceEvent cannot be used before native initialization since * it directly purges to the kernel debug message but that method does not allow tracing events @@ -39,4 +40,4 @@ public void close() { Trace.endSection(); } -} \ No newline at end of file +}
diff --git a/android_webview/support_library/callback/java/src/org/chromium/support_lib_callback_glue/SupportLibWebViewContentsClientAdapter.java b/android_webview/support_library/callback/java/src/org/chromium/support_lib_callback_glue/SupportLibWebViewContentsClientAdapter.java index 566fffe..f5a5691 100644 --- a/android_webview/support_library/callback/java/src/org/chromium/support_lib_callback_glue/SupportLibWebViewContentsClientAdapter.java +++ b/android_webview/support_library/callback/java/src/org/chromium/support_lib_callback_glue/SupportLibWebViewContentsClientAdapter.java
@@ -12,9 +12,9 @@ import org.chromium.android_webview.AwContentsClient.AwWebResourceError; import org.chromium.android_webview.AwSafeBrowsingResponse; -import org.chromium.android_webview.ScopedSysTraceEvent; import org.chromium.base.Callback; import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.ScopedSysTraceEvent; import org.chromium.support_lib_boundary.SafeBrowsingResponseBoundaryInterface; import org.chromium.support_lib_boundary.WebResourceErrorBoundaryInterface; import org.chromium.support_lib_boundary.WebViewClientBoundaryInterface;
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index ad1f461..e8c5340 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -374,9 +374,7 @@ "../browser/gfx/test/rendering_test.cc", "../browser/gfx/test/rendering_test.h", "../browser/input_stream_unittest.cc", - "../browser/net/android_stream_reader_url_request_job_unittest.cc", "../browser/net/aw_cookie_store_wrapper_unittest.cc", - "../browser/net/aw_url_request_context_getter_unittest.cc", "../browser/net/input_stream_reader_unittest.cc", "../browser/network_service/android_stream_reader_url_loader_unittest.cc", "../browser/permission/media_access_permission_request_unittest.cc",
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index f1fcc0c..cc1ddc2 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -516,6 +516,10 @@ "power/gatt_battery_percentage_fetcher.h", "power/gatt_battery_poller.cc", "power/gatt_battery_poller.h", + "power/hid_battery_listener.cc", + "power/hid_battery_listener.h", + "power/hid_battery_util.cc", + "power/hid_battery_util.h", "power/peripheral_battery_tracker.cc", "power/peripheral_battery_tracker.h", "root_window_controller.cc", @@ -1736,6 +1740,8 @@ "power/gatt_battery_controller_unittest.cc", "power/gatt_battery_percentage_fetcher_unittest.cc", "power/gatt_battery_poller_unittest.cc", + "power/hid_battery_listener_unittest.cc", + "power/hid_battery_util_unittest.cc", "root_window_controller_unittest.cc", "rotator/screen_rotation_animation_unittest.cc", "rotator/screen_rotation_animator_unittest.cc",
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 7e9cfa4..ab0b36b 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -662,7 +662,7 @@ params.bounds = gfx::Rect(5, 5, 20, 20); views::Widget* widget = new views::Widget; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->Activate(); widget->GetNativeView()->SetProperty(
diff --git a/ash/accelerators/exit_warning_handler.cc b/ash/accelerators/exit_warning_handler.cc index 51dedf1..dc17cfa 100644 --- a/ash/accelerators/exit_warning_handler.cc +++ b/ash/accelerators/exit_warning_handler.cc
@@ -154,7 +154,7 @@ params.parent = root_window->GetChildById(kShellWindowId_SettingBubbleContainer); widget_ = std::make_unique<views::Widget>(); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); delegate->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
diff --git a/ash/accessibility/accessibility_panel_layout_manager_unittest.cc b/ash/accessibility/accessibility_panel_layout_manager_unittest.cc index 4ea0b463..a9ab7b5 100644 --- a/ash/accessibility/accessibility_panel_layout_manager_unittest.cc +++ b/ash/accessibility/accessibility_panel_layout_manager_unittest.cc
@@ -40,7 +40,7 @@ params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; params.bounds = gfx::Rect(0, 0, root_window->bounds().width(), root_window->bounds().height()); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ash/ambient/ui/ambient_container_view.cc b/ash/ambient/ui/ambient_container_view.cc index 6abe903..3e3e639 100644 --- a/ash/ambient/ui/ambient_container_view.cc +++ b/ash/ambient/ui/ambient_container_view.cc
@@ -37,7 +37,7 @@ params.name = view->GetClassName(); views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); widget->SetFullscreen(true); }
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc index adf41a1..4edaaf58 100644 --- a/ash/app_list/app_list_controller_impl.cc +++ b/ash/app_list/app_list_controller_impl.cc
@@ -593,7 +593,8 @@ } void AppListControllerImpl::OnShelfAlignmentChanged(aura::Window* root_window) { - DismissAppList(); + if (!IsHomeScreenAvailable()) + DismissAppList(); } void AppListControllerImpl::OnShellDestroying() {
diff --git a/ash/app_list/model/search/search_model.cc b/ash/app_list/model/search/search_model.cc index 7de4def..9c49536 100644 --- a/ash/app_list/model/search/search_model.cc +++ b/ash/app_list/model/search/search_model.cc
@@ -53,9 +53,8 @@ if (matches.size() == max_results) break; SearchResult* item = results->GetItemAt(i); - if (result_filter.Run(*item)) { + if (result_filter.Run(*item)) matches.push_back(item); - } } return matches; }
diff --git a/ash/app_list/views/app_list_view.cc b/ash/app_list/views/app_list_view.cc index 015ab92..0c2af42 100644 --- a/ash/app_list/views/app_list_view.cc +++ b/ash/app_list/views/app_list_view.cc
@@ -579,7 +579,7 @@ params.layer_type = ui::LAYER_NOT_DRAWN; views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); DCHECK_EQ(widget, GetWidget()); widget->GetNativeWindow()->SetEventTargeter( std::make_unique<AppListEventTargeter>()); @@ -604,7 +604,7 @@ search_box_widget_params.delegate = search_box_view_; views::Widget* search_box_widget = new views::Widget; - search_box_widget->Init(search_box_widget_params); + search_box_widget->Init(std::move(search_box_widget_params)); DCHECK_EQ(search_box_widget, search_box_view_->GetWidget()); // Assign an accessibility role to the native window of |search_box_widget|,
diff --git a/ash/app_list/views/folder_header_view_unittest.cc b/ash/app_list/views/folder_header_view_unittest.cc index 9aec227..f1475c2 100644 --- a/ash/app_list/views/folder_header_view_unittest.cc +++ b/ash/app_list/views/folder_header_view_unittest.cc
@@ -70,7 +70,7 @@ views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); folder_header_view_ = std::make_unique<FolderHeaderView>(delegate_.get());
diff --git a/ash/app_list/views/search_result_tile_item_list_view.cc b/ash/app_list/views/search_result_tile_item_list_view.cc index 7fdb015..0b625cf 100644 --- a/ash/app_list/views/search_result_tile_item_list_view.cc +++ b/ash/app_list/views/search_result_tile_item_list_view.cc
@@ -254,19 +254,20 @@ base::string16 query; base::TrimWhitespace(raw_query, base::TRIM_ALL, &query); - // We ask for |max_search_result_tiles_| total results, and we prefer - // reinstall candidates if appropriate. we fetch |reinstall_results| first, - // and front-fill the rest from the regular result types. - auto reinstall_filter = + // We ask for |max_search_result_tiles_| policy tile results first, + // then add them to their preferred position in the tile list if found. + auto policy_tiles_filter = base::BindRepeating([](const SearchResult& r) -> bool { - return r.display_type() == - ash::SearchResultDisplayType::kRecommendation && - r.result_type() == ash::SearchResultType::kPlayStoreReinstallApp; + return r.display_location() == + ash::SearchResultDisplayLocation::kTileListContainer && + r.display_index() != ash::SearchResultDisplayIndex::kUndefined && + r.display_type() == + ash::SearchResultDisplayType::kRecommendation; }); - std::vector<SearchResult*> reinstall_results = + std::vector<SearchResult*> policy_tiles_results = is_app_reinstall_recommendation_enabled_ && query.empty() ? SearchModel::FilterSearchResultsByFunction( - results(), reinstall_filter, max_search_result_tiles_) + results(), policy_tiles_filter, max_search_result_tiles_) : std::vector<SearchResult*>(); SearchResult::DisplayType display_type = @@ -274,10 +275,11 @@ ? (query.empty() ? ash::SearchResultDisplayType::kRecommendation : ash::SearchResultDisplayType::kTile) : ash::SearchResultDisplayType::kTile; - size_t display_num = max_search_result_tiles_ - reinstall_results.size(); + size_t display_num = max_search_result_tiles_ - policy_tiles_results.size(); - // Do not display the continue reading app in the search result list. - auto non_reinstall_filter = base::BindRepeating( + // Do not display the repeat reinstall results or continue reading app in the + // search result list. + auto non_policy_tiles_filter = base::BindRepeating( [](const SearchResult::DisplayType& display_type, const SearchResult& r) -> bool { return r.display_type() == display_type && @@ -288,11 +290,23 @@ display_type); std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByFunction( - results(), non_reinstall_filter, display_num); + results(), non_policy_tiles_filter, display_num); - // Append the reinstalls to the display results. - display_results.insert(display_results.end(), reinstall_results.begin(), - reinstall_results.end()); + // Policy tile results will be appended to the final tiles list + // based on their specified index. If the requested index is out of + // range of the current list, the result will be appended to the back. + std::sort(policy_tiles_results.begin(), policy_tiles_results.end(), + [](const SearchResult* r1, const SearchResult* r2) -> bool { + return r1->display_index() < r2->display_index(); + }); + for (auto* result : policy_tiles_results) { + if (result->display_index() > display_results.size() - 1) { + display_results.emplace_back(result); + } else { + display_results.emplace(display_results.begin() + result->display_index(), + result); + } + } return display_results; }
diff --git a/ash/app_list/views/search_result_tile_item_list_view_unittest.cc b/ash/app_list/views/search_result_tile_item_list_view_unittest.cc index 1bfd473..cd58d21 100644 --- a/ash/app_list/views/search_result_tile_item_list_view_unittest.cc +++ b/ash/app_list/views/search_result_tile_item_list_view_unittest.cc
@@ -29,6 +29,10 @@ constexpr size_t kInstalledApps = 4; constexpr size_t kPlayStoreApps = 2; constexpr size_t kRecommendedApps = 1; + +// used to test when multiple chips with specified display +// indexes have been added +constexpr size_t kRecommendedAppsWithDisplayIndex = 3; } // namespace class SearchResultTileItemListViewTest @@ -125,6 +129,9 @@ result->set_result_id("RecommendedApp " + base::NumberToString(i)); result->set_display_type(ash::SearchResultDisplayType::kRecommendation); result->set_result_type(ash::SearchResultType::kPlayStoreReinstallApp); + result->set_display_location( + ash::SearchResultDisplayLocation::kTileListContainer); + result->set_display_index(ash::SearchResultDisplayIndex::kSixthIndex); result->set_title(base::ASCIIToUTF16("RecommendedApp ") + base::NumberToString16(i)); result->SetRating(1 + i); @@ -137,6 +144,67 @@ RunPendingMessages(); } + void SetUpSearchResultsWithMultipleDisplayIndexesRequested() { + SearchModel::SearchResults* results = GetResults(); + + // Populate results for installed applications. + for (size_t i = 0; i < kInstalledApps; ++i) { + std::unique_ptr<TestSearchResult> result = + std::make_unique<TestSearchResult>(); + result->set_result_id("InstalledApp " + base::NumberToString(i)); + result->set_display_type(ash::SearchResultDisplayType::kTile); + result->set_result_type(ash::SearchResultType::kInstalledApp); + result->set_title(base::ASCIIToUTF16("InstalledApp ") + + base::NumberToString16(i)); + results->Add(std::move(result)); + } + + // Populate results for Play Store search applications. + if (IsPlayStoreAppSearchEnabled()) { + for (size_t i = 0; i < kPlayStoreApps; ++i) { + std::unique_ptr<TestSearchResult> result = + std::make_unique<TestSearchResult>(); + result->set_result_id("PlayStoreApp " + base::NumberToString(i)); + result->set_display_type(ash::SearchResultDisplayType::kTile); + result->set_result_type(ash::SearchResultType::kPlayStoreApp); + result->set_title(base::ASCIIToUTF16("PlayStoreApp ") + + base::NumberToString16(i)); + result->SetRating(1 + i); + result->SetFormattedPrice(base::ASCIIToUTF16("Price ") + + base::NumberToString16(i)); + results->Add(std::move(result)); + } + } + + const ash::SearchResultDisplayIndex + display_indexes[kRecommendedAppsWithDisplayIndex] = { + ash::SearchResultDisplayIndex::kFourthIndex, + ash::SearchResultDisplayIndex::kFifthIndex, + ash::SearchResultDisplayIndex::kSixthIndex, + }; + + if (IsReinstallAppRecommendationEnabled()) { + for (size_t i = 0; i < kRecommendedAppsWithDisplayIndex; ++i) { + std::unique_ptr<TestSearchResult> result = + std::make_unique<TestSearchResult>(); + result->set_result_id("RecommendedApp " + base::NumberToString(i)); + result->set_display_type(ash::SearchResultDisplayType::kRecommendation); + result->set_result_type(ash::SearchResultType::kPlayStoreReinstallApp); + result->set_display_location( + ash::SearchResultDisplayLocation::kTileListContainer); + result->set_display_index(display_indexes[i]); + result->set_title(base::ASCIIToUTF16("RecommendedApp ") + + base::NumberToString16(i)); + result->SetRating(1 + i); + results->AddAt(result->display_index(), std::move(result)); + } + } + + // Adding results calls SearchResultContainerView::ScheduleUpdate(). + // It will post a delayed task to update the results and relayout. + RunPendingMessages(); + } + size_t GetOpenResultCount(int ranking) { return view_delegate_.open_search_result_counts()[ranking]; } @@ -244,6 +312,31 @@ } } +// Tests that when multiple apps with specified indexes are added to the app +// results list, they are found at the indexes they requested. +TEST_P(SearchResultTileItemListViewTest, TestRecommendations) { + if (!IsReinstallAppRecommendationEnabled()) + return; + + CreateSearchResultTileItemListView(); + SetUpSearchResultsWithMultipleDisplayIndexesRequested(); + + const size_t child_step = 2; + + size_t first_index = kInstalledApps + kRecommendedAppsWithDisplayIndex; + + size_t stepper = IsPlayStoreAppSearchEnabled() ? 3 : 2; + for (size_t i = 0; i < stepper; ++i) { + ui::AXNodeData node_data; + view()->children()[first_index + i * child_step]->GetAccessibleNodeData( + &node_data); + EXPECT_EQ(ax::mojom::Role::kButton, node_data.role); + EXPECT_EQ("RecommendedApp " + base::NumberToString(i) + ", Star rating " + + base::NumberToString(i + 1) + ".0, App recommendation", + node_data.GetStringAttribute(ax::mojom::StringAttribute::kName)); + } +} + INSTANTIATE_TEST_SUITE_P(, SearchResultTileItemListViewTest, testing::ValuesIn({std::make_pair(false, false),
diff --git a/ash/app_list/views/suggestion_chip_container_view.cc b/ash/app_list/views/suggestion_chip_container_view.cc index e77b757..250b568 100644 --- a/ash/app_list/views/suggestion_chip_container_view.cc +++ b/ash/app_list/views/suggestion_chip_container_view.cc
@@ -28,16 +28,10 @@ // The spacing between chips. constexpr int kChipSpacing = 8; -// Sort suggestion chip results by |display_index| value in ascending order. -bool IndexOrdering(const SearchResult* result1, const SearchResult* result2) { - return result1->display_index() < result2->display_index(); -} - -bool IsPolicySuggestionChip(const SearchResult* result) { - return result->display_location() == +bool IsPolicySuggestionChip(const SearchResult& result) { + return result.display_location() == ash::SearchResultDisplayLocation::kSuggestionChipContainer && - result->display_index() != - ash::SearchResultDisplayIndex::kPlacementUndefined; + result.display_index() != ash::SearchResultDisplayIndex::kUndefined; } } // namespace @@ -87,7 +81,7 @@ // Filter out priority suggestion chips with a non-default value // for |display_index|. auto filter_indexed_policy_chips = [](const SearchResult& r) -> bool { - return IsPolicySuggestionChip(&r); + return IsPolicySuggestionChip(r); }; std::vector<SearchResult*> indexed_policy_results = SearchModel::FilterSearchResultsByFunction( @@ -95,7 +89,9 @@ AppListConfig::instance().num_start_page_tiles()); std::sort(indexed_policy_results.begin(), indexed_policy_results.end(), - &IndexOrdering); + [](const SearchResult* r1, const SearchResult* r2) -> bool { + return r1->display_index() < r2->display_index(); + }); // Need to filter out kArcAppShortcut since it will be confusing to users // if shortcuts are displayed as suggestion chips. Also filter out any @@ -104,7 +100,7 @@ return r.display_type() == ash::SearchResultDisplayType::kRecommendation && r.result_type() != ash::SearchResultType::kPlayStoreReinstallApp && r.result_type() != ash::SearchResultType::kArcAppShortcut && - !IsPolicySuggestionChip(&r); + !IsPolicySuggestionChip(r); }; std::vector<SearchResult*> display_results = SearchModel::FilterSearchResultsByFunction( @@ -115,9 +111,8 @@ // Update display results list by placing policy result chips at their // specified |display_index|. for (auto* result : indexed_policy_results) { - std::vector<SearchResult*>::iterator desired_index = - display_results.begin() + result->display_index(); - display_results.emplace(desired_index, result); + display_results.emplace(display_results.begin() + result->display_index(), + result); } // Update search results here, but wait until layout to add them as child
diff --git a/ash/app_menu/notification_menu_view_unittest.cc b/ash/app_menu/notification_menu_view_unittest.cc index d25db6dc..111c2b31 100644 --- a/ash/app_menu/notification_menu_view_unittest.cc +++ b/ash/app_menu/notification_menu_view_unittest.cc
@@ -106,7 +106,7 @@ init_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.activatable = views::Widget::InitParams::ACTIVATABLE_YES; - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(notification_menu_view_.get()); widget_->SetSize(notification_menu_view_->GetPreferredSize()); widget_->Show();
diff --git a/ash/components/fast_ink/fast_ink_view.cc b/ash/components/fast_ink/fast_ink_view.cc index 6d2ba4e..7f7bebb 100644 --- a/ash/components/fast_ink/fast_ink_view.cc +++ b/ash/components/fast_ink/fast_ink_view.cc
@@ -296,7 +296,7 @@ params.layer_type = ui::LAYER_SOLID_COLOR; gfx::Rect screen_bounds = container->GetRootWindow()->GetBoundsInScreen(); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); widget_->SetContentsView(this); widget_->SetBounds(screen_bounds);
diff --git a/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc b/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc index 8c59a1a1..b4ac79c 100644 --- a/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc +++ b/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc
@@ -158,7 +158,7 @@ // based on CalculatePreferredSize(). views::Widget* widget = new views::Widget; params.context = context; - widget->Init(params); + widget->Init(std::move(params)); // Set frame view Active and Inactive colors, both are SK_ColorWHITE. aura::Window* window = g_ksv_view->GetWidget()->GetNativeWindow();
diff --git a/ash/display/display_move_window_util_unittest.cc b/ash/display/display_move_window_util_unittest.cc index f35af70..9f71630 100644 --- a/ash/display/display_move_window_util_unittest.cc +++ b/ash/display/display_move_window_util_unittest.cc
@@ -54,7 +54,7 @@ params.bounds = bounds; params.child = child; views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/display/shared_display_edge_indicator.cc b/ash/display/shared_display_edge_indicator.cc index 9e795794..c6820b9 100644 --- a/ash/display/shared_display_edge_indicator.cc +++ b/ash/display/shared_display_edge_indicator.cc
@@ -53,7 +53,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.z_order = ui::ZOrderLevel::kFloatingUIElement; widget->set_focus_on_creation(false); - widget->Init(params); + widget->Init(std::move(params)); widget->SetVisibilityChangedAnimationsEnabled(false); widget->GetNativeWindow()->SetName("SharedEdgeIndicator"); widget->SetContentsView(contents_view);
diff --git a/ash/drag_drop/drag_drop_controller_unittest.cc b/ash/drag_drop/drag_drop_controller_unittest.cc index 1a0c2c5e..63ab3e2 100644 --- a/ash/drag_drop/drag_drop_controller_unittest.cc +++ b/ash/drag_drop/drag_drop_controller_unittest.cc
@@ -358,7 +358,7 @@ params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/drag_drop/drag_drop_unittest.cc b/ash/drag_drop/drag_drop_unittest.cc index e668d0b..da979501 100644 --- a/ash/drag_drop/drag_drop_unittest.cc +++ b/ash/drag_drop/drag_drop_unittest.cc
@@ -77,7 +77,7 @@ params.accept_events = true; params.bounds = bounds; params.context = context; - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(contents_view); widget->Show();
diff --git a/ash/drag_drop/drag_image_view.cc b/ash/drag_drop/drag_image_view.cc index 73e9da60..aafc030e 100644 --- a/ash/drag_drop/drag_image_view.cc +++ b/ash/drag_drop/drag_image_view.cc
@@ -33,7 +33,7 @@ root_window->GetChildById(kShellWindowId_DragImageAndTooltipContainer); if (!params.parent) params.context = root_window; // Happens in tests. - drag_widget->Init(params); + drag_widget->Init(std::move(params)); drag_widget->SetOpacity(1.f); return drag_widget; }
diff --git a/ash/extended_desktop_unittest.cc b/ash/extended_desktop_unittest.cc index 6c1796fd..47ea1c7 100644 --- a/ash/extended_desktop_unittest.cc +++ b/ash/extended_desktop_unittest.cc
@@ -156,7 +156,7 @@ params.bounds = bounds; views::Widget* widget = new views::Widget; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/focus_cycler_unittest.cc b/ash/focus_cycler_unittest.cc index 4637b763..ab4c2e2 100644 --- a/ash/focus_cycler_unittest.cc +++ b/ash/focus_cycler_unittest.cc
@@ -286,7 +286,7 @@ widget_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget_params.context = CurrentContext(); - browser_widget->Init(widget_params); + browser_widget->Init(std::move(widget_params)); browser_widget->Show(); aura::Window* browser_window = browser_widget->GetNativeView();
diff --git a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc index 4209db6..1254bcc 100644 --- a/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc +++ b/ash/frame/caption_buttons/frame_caption_button_container_view_unittest.cc
@@ -72,7 +72,7 @@ close_button_visible == CLOSE_BUTTON_VISIBLE); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ash/frame/caption_buttons/frame_size_button_unittest.cc b/ash/frame/caption_buttons/frame_size_button_unittest.cc index 2bb33d6..20c87879 100644 --- a/ash/frame/caption_buttons/frame_size_button_unittest.cc +++ b/ash/frame/caption_buttons/frame_size_button_unittest.cc
@@ -113,7 +113,7 @@ params.delegate = delegate; params.bounds = gfx::Rect(10, 10, 100, 100); params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget;
diff --git a/ash/frame/wide_frame_view.cc b/ash/frame/wide_frame_view.cc index e9d845e..b1dcefa 100644 --- a/ash/frame/wide_frame_view.cc +++ b/ash/frame/wide_frame_view.cc
@@ -101,7 +101,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; - widget_->Init(params); + widget_->Init(std::move(params)); aura::Window* window = widget_->GetNativeWindow(); // Overview normally clips the caption container which exists on the same
diff --git a/ash/highlighter/highlighter_result_view.cc b/ash/highlighter/highlighter_result_view.cc index d3b0532a..a2175130 100644 --- a/ash/highlighter/highlighter_result_view.cc +++ b/ash/highlighter/highlighter_result_view.cc
@@ -179,7 +179,7 @@ Shell::GetContainer(root_window, kShellWindowId_OverlayContainer); params.layer_type = ui::LAYER_SOLID_COLOR; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); widget_->SetContentsView(this); widget_->SetFullscreen(true);
diff --git a/ash/lock_screen_action/lock_screen_action_background_controller_impl.cc b/ash/lock_screen_action/lock_screen_action_background_controller_impl.cc index 2ee9241a..54ca865 100644 --- a/ash/lock_screen_action/lock_screen_action_background_controller_impl.cc +++ b/ash/lock_screen_action/lock_screen_action_background_controller_impl.cc
@@ -107,7 +107,7 @@ params.delegate = contents_view_; views::Widget* widget = new views::Widget(); - widget->Init(params); + widget->Init(std::move(params)); widget->SetVisibilityChangedAnimationsEnabled(false); widget_observer_.Add(widget);
diff --git a/ash/lock_screen_action/test_lock_screen_action_background_controller.cc b/ash/lock_screen_action/test_lock_screen_action_background_controller.cc index 8642a920..dffa0a13 100644 --- a/ash/lock_screen_action/test_lock_screen_action_background_controller.cc +++ b/ash/lock_screen_action/test_lock_screen_action_background_controller.cc
@@ -65,7 +65,7 @@ params.delegate = new TestWindowDelegate(widget_.get()); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); } widget_->Show();
diff --git a/ash/login/ui/login_test_base.cc b/ash/login/ui/login_test_base.cc index f3cec94..1722ded 100644 --- a/ash/login/ui/login_test_base.cc +++ b/ash/login/ui/login_test_base.cc
@@ -84,7 +84,7 @@ kShellWindowId_LockScreenContainer); auto new_widget = std::make_unique<views::Widget>(); - new_widget->Init(params); + new_widget->Init(std::move(params)); new_widget->SetContentsView(content); new_widget->Show(); return new_widget;
diff --git a/ash/login/ui/parent_access_widget.cc b/ash/login/ui/parent_access_widget.cc index 9c9eb98..e8a3a117 100644 --- a/ash/login/ui/parent_access_widget.cc +++ b/ash/login/ui/parent_access_widget.cc
@@ -49,7 +49,7 @@ } widget_ = std::make_unique<views::Widget>(); - widget_->Init(widget_params); + widget_->Init(std::move(widget_params)); widget_->Show(); }
diff --git a/ash/magnifier/docked_magnifier_controller_impl.cc b/ash/magnifier/docked_magnifier_controller_impl.cc index b14388b..115b16f 100644 --- a/ash/magnifier/docked_magnifier_controller_impl.cc +++ b/ash/magnifier/docked_magnifier_controller_impl.cc
@@ -717,7 +717,7 @@ params.parent = GetViewportParentContainerForRoot(current_source_root_window_); params.name = kDockedMagnifierViewportWindowName; - viewport_widget_->Init(params); + viewport_widget_->Init(std::move(params)); viewport_widget_->Show(); viewport_widget_->AddObserver(this);
diff --git a/ash/magnifier/partial_magnification_controller.cc b/ash/magnifier/partial_magnification_controller.cc index 455988d1..222185b0 100644 --- a/ash/magnifier/partial_magnification_controller.cc +++ b/ash/magnifier/partial_magnification_controller.cc
@@ -330,7 +330,7 @@ params.bounds = GetBounds(mouse); params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.parent = root_window; - host_widget_->Init(params); + host_widget_->Init(std::move(params)); host_widget_->set_focus_on_creation(false); host_widget_->Show();
diff --git a/ash/power/hid_battery_listener.cc b/ash/power/hid_battery_listener.cc new file mode 100644 index 0000000..6ebb0f06 --- /dev/null +++ b/ash/power/hid_battery_listener.cc
@@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/power/hid_battery_listener.h" + +#include "ash/power/hid_battery_util.h" +#include "device/bluetooth/bluetooth_adapter.h" +#include "device/bluetooth/bluetooth_device.h" + +namespace ash { + +HidBatteryListener::HidBatteryListener( + scoped_refptr<device::BluetoothAdapter> adapter) + : adapter_(adapter) { + chromeos::PowerManagerClient::Get()->AddObserver(this); +} + +HidBatteryListener::~HidBatteryListener() { + chromeos::PowerManagerClient::Get()->RemoveObserver(this); +} + +void HidBatteryListener::PeripheralBatteryStatusReceived( + const std::string& path, + const std::string& name, + int level) { + const std::string bluetooth_address = + ExtractBluetoothAddressFromHIDBatteryPath(path); + if (bluetooth_address.empty()) + return; + + device::BluetoothDevice* device = adapter_->GetDevice(bluetooth_address); + if (!device) + return; + + if (level < 0 || level > 100) + device->SetBatteryPercentage(base::nullopt); + else + device->SetBatteryPercentage(level); +} + +} // namespace ash
diff --git a/ash/power/hid_battery_listener.h b/ash/power/hid_battery_listener.h new file mode 100644 index 0000000..452f42a --- /dev/null +++ b/ash/power/hid_battery_listener.h
@@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_POWER_HID_BATTERY_LISTENER_H_ +#define ASH_POWER_HID_BATTERY_LISTENER_H_ + +#include "ash/ash_export.h" +#include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "chromeos/dbus/power/power_manager_client.h" + +namespace device { +class BluetoothAdapter; +} // namespace device + +namespace ash { + +// Listens to changes in battery level for HID devices, updating the +// corresponding device::BluetoothDevice. +class ASH_EXPORT HidBatteryListener + : public chromeos::PowerManagerClient::Observer { + public: + explicit HidBatteryListener(scoped_refptr<device::BluetoothAdapter> adapter); + ~HidBatteryListener() override; + + private: + friend class HidBatteryListenerTest; + + // chromeos::PowerManagerClient::Observer: + void PeripheralBatteryStatusReceived(const std::string& path, + const std::string& name, + int level) override; + + scoped_refptr<device::BluetoothAdapter> adapter_; + + DISALLOW_COPY_AND_ASSIGN(HidBatteryListener); +}; + +} // namespace ash + +#endif // ASH_POWER_HID_BATTERY_LISTENER_H_
diff --git a/ash/power/hid_battery_listener_unittest.cc b/ash/power/hid_battery_listener_unittest.cc new file mode 100644 index 0000000..d83d6929 --- /dev/null +++ b/ash/power/hid_battery_listener_unittest.cc
@@ -0,0 +1,114 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/power/hid_battery_listener.h" + +#include <memory> + +#include "ash/test/ash_test_base.h" +#include "device/bluetooth/test/mock_bluetooth_adapter.h" +#include "device/bluetooth/test/mock_bluetooth_device.h" +#include "testing/gmock/include/gmock/gmock.h" + +using testing::_; +using testing::NiceMock; +using testing::Return; + +namespace ash { +namespace { + +const char kPath[] = "/sys/class/power_supply/hid-AA:BB:CC:DD:EE:FF-battery"; +const char kAddress[] = "ff:ee:dd:cc:bb:aa"; +const char kDeviceName[] = "test device"; + +} // namespace + +class HidBatteryListenerTest : public AshTestBase { + public: + HidBatteryListenerTest() = default; + + ~HidBatteryListenerTest() override = default; + + void SetUp() override { + AshTestBase::SetUp(); + + mock_adapter_ = + base::MakeRefCounted<NiceMock<device::MockBluetoothAdapter>>(); + + mock_device_ = std::make_unique<NiceMock<device::MockBluetoothDevice>>( + mock_adapter_.get(), 0 /* bluetooth_class */, kDeviceName, kAddress, + true /* paired */, true /* connected */); + ASSERT_FALSE(mock_device_->battery_percentage()); + ON_CALL(*mock_adapter_, GetDevice(kAddress)) + .WillByDefault(Return(mock_device_.get())); + + listener_ = std::make_unique<HidBatteryListener>(mock_adapter_); + } + + void TearDown() override { + listener_.reset(); + AshTestBase::TearDown(); + } + + void NotifyPeripheralBatteryStatusReceived(const std::string& path, + const std::string& name, + int level) { + listener_->PeripheralBatteryStatusReceived(path, name, level); + } + + protected: + scoped_refptr<NiceMock<device::MockBluetoothAdapter>> mock_adapter_; + std::unique_ptr<device::MockBluetoothDevice> mock_device_; + std::unique_ptr<HidBatteryListener> listener_; + + private: + DISALLOW_COPY_AND_ASSIGN(HidBatteryListenerTest); +}; + +TEST_F(HidBatteryListenerTest, SetsBatteryToDevice) { + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 100); + EXPECT_EQ(100, mock_device_->battery_percentage()); + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 0); + EXPECT_EQ(0, mock_device_->battery_percentage()); + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 55); + EXPECT_EQ(55, mock_device_->battery_percentage()); +} + +TEST_F(HidBatteryListenerTest, InvalidBatteryLevel) { + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 101); + EXPECT_EQ(base::nullopt, mock_device_->battery_percentage()); + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 200); + EXPECT_EQ(base::nullopt, mock_device_->battery_percentage()); + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, -1); + EXPECT_EQ(base::nullopt, mock_device_->battery_percentage()); + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, -100); + EXPECT_EQ(base::nullopt, mock_device_->battery_percentage()); +} + +TEST_F(HidBatteryListenerTest, InvalidHIDAddress) { + EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); + + NotifyPeripheralBatteryStatusReceived("invalid-path", kDeviceName, 100); + NotifyPeripheralBatteryStatusReceived("/sys/class/power_supply/hid-battery", + kDeviceName, 100); + + // 3 characters at the end of the address, "f55". + NotifyPeripheralBatteryStatusReceived( + "/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f55-battery", kDeviceName, + 100); + + // 3 characters at the start of the address, "A00". + NotifyPeripheralBatteryStatusReceived( + "/sys/class/power_supply/hid-A00:b1:C2:d3:E4:f5-battery", kDeviceName, + 100); +} + +TEST_F(HidBatteryListenerTest, DeviceNotPresentInAdapter) { + ON_CALL(*mock_adapter_, GetDevice(kAddress)).WillByDefault(Return(nullptr)); + + // Should not crash. + NotifyPeripheralBatteryStatusReceived(kPath, kDeviceName, 100); +} + +} // namespace ash
diff --git a/ash/power/hid_battery_util.cc b/ash/power/hid_battery_util.cc new file mode 100644 index 0000000..74c7852 --- /dev/null +++ b/ash/power/hid_battery_util.cc
@@ -0,0 +1,63 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/power/hid_battery_util.h" + +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "third_party/re2/src/re2/re2.h" + +namespace ash { + +namespace { + +// HID device's battery sysfs entry path looks like +// /sys/class/power_supply/hid-{AA:BB:CC:DD:EE:FF|AAAA:BBBB:CCCC.DDDD}-battery. +constexpr char kHIDBatteryPrefix[] = "/sys/class/power_supply/hid-"; +constexpr char kHIDBatterySuffix[] = "-battery"; +constexpr size_t kPrefixLen = base::size(kHIDBatteryPrefix) - 1; +constexpr size_t kPrefixAndSuffixLen = + (base::size(kHIDBatteryPrefix) - 1) + (base::size(kHIDBatterySuffix) - 1); + +// Regex to check for valid bluetooth addresses. +constexpr char kBluetoothAddressRegex[] = + "^([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2})$"; + +} // namespace + +bool IsHIDBattery(const std::string& path) { + if (!base::StartsWith(path, kHIDBatteryPrefix, + base::CompareCase::INSENSITIVE_ASCII) || + !base::EndsWith(path, kHIDBatterySuffix, + base::CompareCase::INSENSITIVE_ASCII)) { + return false; + } + + return path.size() > kPrefixAndSuffixLen; +} + +std::string ExtractHIDBatteryIdentifier(const std::string& path) { + if (path.size() <= kPrefixAndSuffixLen) + return std::string(); + + size_t id_len = path.size() - kPrefixAndSuffixLen; + return path.substr(kPrefixLen, id_len); +} + +std::string ExtractBluetoothAddressFromHIDBatteryPath(const std::string& path) { + if (!IsHIDBattery(path)) + return std::string(); + + std::string identifier = ExtractHIDBatteryIdentifier(path); + if (!RE2::FullMatch(identifier, kBluetoothAddressRegex)) + return std::string(); + + std::string reverse_address = base::ToLowerASCII(identifier); + std::vector<base::StringPiece> result = base::SplitStringPiece( + reverse_address, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); + std::reverse(result.begin(), result.end()); + return base::JoinString(result, ":"); +} + +} // namespace ash
diff --git a/ash/power/hid_battery_util.h b/ash/power/hid_battery_util.h new file mode 100644 index 0000000..4091689 --- /dev/null +++ b/ash/power/hid_battery_util.h
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef ASH_POWER_HID_BATTERY_UTIL_H_ +#define ASH_POWER_HID_BATTERY_UTIL_H_ + +#include <string> + +#include "ash/ash_export.h" + +namespace ash { + +// Checks whether the device at |path| is a HID battery. |path| is a sysfs +// device path like "/sys/class/power-supply/hid-FF:EE:DD:CC:BB:AA-battery" +// Returns false if |path| is lacking the HID battery prefix or suffix, or if it +// contains them but has nothing in between. +ASH_EXPORT bool IsHIDBattery(const std::string& path); + +// Extract the identifier in |path| found between the path prefix and suffix. +// |path| is a sysfs device path like +// "/sys/class/power-supply/hid-FF:EE:DD:CC:BB:AA-battery" +ASH_EXPORT std::string ExtractHIDBatteryIdentifier(const std::string& path); + +// Extracts a Bluetooth address (e.g. "AA:BB:CC:DD:EE:FF") from |path|, a sysfs +// device path like "/sys/class/power-supply/hid-FF:EE:DD:CC:BB:AA-battery". +// The address supplied in |path| is reversed, so this method will reverse the +// extracted address. Returns an empty string if |path| does not contain a +// Bluetooth address. +ASH_EXPORT std::string ExtractBluetoothAddressFromHIDBatteryPath( + const std::string& path); + +} // namespace ash + +#endif // ASH_POWER_HID_BATTERY_UTIL_H_
diff --git a/ash/power/hid_battery_util_unittest.cc b/ash/power/hid_battery_util_unittest.cc new file mode 100644 index 0000000..5973d4b --- /dev/null +++ b/ash/power/hid_battery_util_unittest.cc
@@ -0,0 +1,53 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/power/hid_battery_util.h" + +#include <string> + +#include "base/macros.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace ash { + +using HidBatteryUtilTest = testing::Test; + +TEST_F(HidBatteryUtilTest, IsHIDBattery) { + EXPECT_FALSE(IsHIDBattery(std::string())); + EXPECT_FALSE(IsHIDBattery("invalid-path")); + EXPECT_FALSE(IsHIDBattery("/sys/class/power_supply/hid-")); + EXPECT_FALSE(IsHIDBattery("-battery")); + EXPECT_FALSE(IsHIDBattery("/sys/class/power_supply/hid--battery")); + + EXPECT_TRUE( + IsHIDBattery("/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f5-battery")); +} + +TEST_F(HidBatteryUtilTest, ExtractHIDIdentifier) { + EXPECT_EQ(std::string(), ExtractHIDBatteryIdentifier("invalid-path")); + EXPECT_EQ("A0:b1:C2:d3:E4:f5", + ExtractHIDBatteryIdentifier( + "/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f5-battery")); +} + +TEST_F(HidBatteryUtilTest, ExtractBluetoothAddressFromHIDBatteryPath) { + EXPECT_EQ(std::string(), + ExtractBluetoothAddressFromHIDBatteryPath("invalid-path")); + + // 3 characters at the end of the address, "f55". + EXPECT_EQ(std::string(), + ExtractBluetoothAddressFromHIDBatteryPath( + "/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f55-battery")); + + // 3 characters at the start of the address, "A00". + EXPECT_EQ(std::string(), + ExtractBluetoothAddressFromHIDBatteryPath( + "/sys/class/power_supply/hid-A00:b1:C2:d3:E4:f5-battery")); + + EXPECT_EQ("f5:e4:d3:c2:b1:a0", + ExtractBluetoothAddressFromHIDBatteryPath( + "/sys/class/power_supply/hid-A0:b1:C2:d3:E4:f5-battery")); +} + +} // namespace ash
diff --git a/ash/power/peripheral_battery_tracker.cc b/ash/power/peripheral_battery_tracker.cc index d0c5d45..293d9b9 100644 --- a/ash/power/peripheral_battery_tracker.cc +++ b/ash/power/peripheral_battery_tracker.cc
@@ -5,6 +5,7 @@ #include "ash/power/peripheral_battery_tracker.h" #include "ash/power/gatt_battery_controller.h" +#include "ash/power/hid_battery_listener.h" #include "base/bind.h" #include "base/logging.h" #include "device/bluetooth/bluetooth_adapter.h" @@ -24,6 +25,7 @@ scoped_refptr<device::BluetoothAdapter> adapter) { adapter_ = adapter; DCHECK(adapter_.get()); + hid_battery_listener_ = std::make_unique<HidBatteryListener>(adapter_); gatt_battery_controller_ = std::make_unique<GattBatteryController>(adapter_); }
diff --git a/ash/power/peripheral_battery_tracker.h b/ash/power/peripheral_battery_tracker.h index c6ccab65..648c490 100644 --- a/ash/power/peripheral_battery_tracker.h +++ b/ash/power/peripheral_battery_tracker.h
@@ -16,11 +16,11 @@ namespace ash { +class HidBatteryListener; class GattBatteryController; // Creates instances of classes to collect the battery status of peripheral -// devices. Currently only tracks Bluetooth devices that support GATT. -// TODO(https://crbug.com/785758): Add support for other protocols, like HID. +// devices. Currently only tracks Bluetooth devices that support GATT or HID. class ASH_EXPORT PeripheralBatteryTracker { public: PeripheralBatteryTracker(); @@ -32,6 +32,7 @@ scoped_refptr<device::BluetoothAdapter> adapter_; + std::unique_ptr<HidBatteryListener> hid_battery_listener_; std::unique_ptr<GattBatteryController> gatt_battery_controller_; base::WeakPtrFactory<PeripheralBatteryTracker> weak_ptr_factory_{this};
diff --git a/ash/public/cpp/app_list/app_list_types.h b/ash/public/cpp/app_list/app_list_types.h index 1581226..017e7cb33 100644 --- a/ash/public/cpp/app_list/app_list_types.h +++ b/ash/public/cpp/app_list/app_list_types.h
@@ -143,7 +143,7 @@ enum SearchResultDisplayLocation { kSuggestionChipContainer, kTileListContainer, - kUnknown, + kPlacementUndefined, }; // Which index in the UI container should the result be placed in. @@ -154,7 +154,7 @@ kFourthIndex, kFifthIndex, kSixthIndex, - kPlacementUndefined, + kUndefined, }; // Actions for OmniBox zero state suggestion. @@ -261,11 +261,10 @@ // Which UI container should the result be displayed in. SearchResultDisplayLocation display_location = - SearchResultDisplayLocation::kUnknown; + SearchResultDisplayLocation::kPlacementUndefined; // Which index in the UI container should the result be placed in. - SearchResultDisplayIndex display_index = - SearchResultDisplayIndex::kPlacementUndefined; + SearchResultDisplayIndex display_index = SearchResultDisplayIndex::kUndefined; // A score to determine the result display order. double display_score = 0;
diff --git a/ash/public/cpp/lock_screen_widget_factory.cc b/ash/public/cpp/lock_screen_widget_factory.cc index 14a4423..2b53ed6d 100644 --- a/ash/public/cpp/lock_screen_widget_factory.cc +++ b/ash/public/cpp/lock_screen_widget_factory.cc
@@ -44,7 +44,7 @@ params.show_state = ui::SHOW_STATE_FULLSCREEN; params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.parent = parent; - widget->Init(params); + widget->Init(std::move(params)); widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_NONE); return widget; }
diff --git a/ash/root_window_controller_unittest.cc b/ash/root_window_controller_unittest.cc index ea792c4..fd7ec91c 100644 --- a/ash/root_window_controller_unittest.cc +++ b/ash/root_window_controller_unittest.cc
@@ -184,7 +184,7 @@ params.bounds = gfx::Rect(650, 10, 100, 100); params.type = Widget::InitParams::TYPE_CONTROL; params.context = CurrentContext(); - unparented_control->Init(params); + unparented_control->Init(std::move(params)); EXPECT_EQ(root_windows[1], unparented_control->GetNativeView()->GetRootWindow()); EXPECT_EQ(kShellWindowId_UnparentedControlContainer,
diff --git a/ash/session/test_session_controller_client.cc b/ash/session/test_session_controller_client.cc index 07894f2d..829ef06 100644 --- a/ash/session/test_session_controller_client.cc +++ b/ash/session/test_session_controller_client.cc
@@ -265,7 +265,7 @@ params.context = Shell::GetPrimaryRootWindow(); multi_profile_login_widget_ = std::make_unique<views::Widget>(); - multi_profile_login_widget_->Init(params); + multi_profile_login_widget_->Init(std::move(params)); multi_profile_login_widget_->Show(); }
diff --git a/ash/shelf/home_button.cc b/ash/shelf/home_button.cc index 79176d8..5655e4d 100644 --- a/ash/shelf/home_button.cc +++ b/ash/shelf/home_button.cc
@@ -23,6 +23,7 @@ #include "ui/gfx/scoped_canvas.h" #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_impl.h" +#include "ui/views/controls/button/button_controller.h" namespace ash { namespace { @@ -39,7 +40,8 @@ : ShelfControlButton(shelf, this), controller_(this) { SetAccessibleName( l10n_util::GetStringUTF16(IDS_ASH_SHELF_APP_LIST_LAUNCHER_TITLE)); - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_PRESS); set_has_ink_drop_action_on_click(false); SetEventTargeter(std::make_unique<views::ViewTargeter>(this));
diff --git a/ash/shelf/shelf_control_button.cc b/ash/shelf/shelf_control_button.cc index 7fd05f3..9a890fc 100644 --- a/ash/shelf/shelf_control_button.cc +++ b/ash/shelf/shelf_control_button.cc
@@ -61,7 +61,8 @@ } gfx::Size ShelfControlButton::CalculatePreferredSize() const { - return gfx::Size(kShelfControlSize, kShelfControlSize); + return gfx::Size(ShelfConstants::control_size(), + ShelfConstants::control_size()); } void ShelfControlButton::GetAccessibleNodeData(ui::AXNodeData* node_data) {
diff --git a/ash/shelf/shelf_layout_manager.cc b/ash/shelf/shelf_layout_manager.cc index 75c02050..7c413350 100644 --- a/ash/shelf/shelf_layout_manager.cc +++ b/ash/shelf/shelf_layout_manager.cc
@@ -1198,11 +1198,11 @@ available_bounds.right() - (hidden_at_start ? 0 : shelf_size)); if (horizontal) { target_bounds->shelf_bounds.set_y(baseline + translate); - target_bounds->nav_bounds_in_shelf.set_y(kShelfButtonSpacing); + target_bounds->nav_bounds_in_shelf.set_y(ShelfConstants::button_spacing()); target_bounds->status_bounds_in_shelf.set_y(0); } else { target_bounds->shelf_bounds.set_x(baseline + translate); - target_bounds->nav_bounds_in_shelf.set_x(kShelfButtonSpacing); + target_bounds->nav_bounds_in_shelf.set_x(ShelfConstants::button_spacing()); target_bounds->status_bounds_in_shelf.set_x(0); } }
diff --git a/ash/shelf/shelf_layout_manager_unittest.cc b/ash/shelf/shelf_layout_manager_unittest.cc index f02c738..4e5bb71 100644 --- a/ash/shelf/shelf_layout_manager_unittest.cc +++ b/ash/shelf/shelf_layout_manager_unittest.cc
@@ -375,7 +375,7 @@ params.bounds = gfx::Rect(0, 0, 200, 200); params.context = CurrentContext(); views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/shelf/shelf_navigation_widget.cc b/ash/shelf/shelf_navigation_widget.cc index 13675def..f0a8aff 100644 --- a/ash/shelf/shelf_navigation_widget.cc +++ b/ash/shelf/shelf_navigation_widget.cc
@@ -82,16 +82,17 @@ : shelf_(shelf) { set_allow_deactivate_on_esc(true); + const int control_size = ShelfConstants::control_size(); std::unique_ptr<BackButton> back_button_ptr = std::make_unique<BackButton>(shelf); back_button_ = AddChildView(std::move(back_button_ptr)); - back_button_->SetSize(gfx::Size(kShelfControlSize, kShelfControlSize)); + back_button_->SetSize(gfx::Size(control_size, control_size)); std::unique_ptr<HomeButton> home_button_ptr = std::make_unique<HomeButton>(shelf); home_button_ = AddChildView(std::move(home_button_ptr)); home_button_->set_context_menu_controller(shelf_view); - home_button_->SetSize(gfx::Size(kShelfControlSize, kShelfControlSize)); + home_button_->SetSize(gfx::Size(control_size, control_size)); GetViewAccessibility().OverrideNextFocus(shelf->shelf_widget()); GetViewAccessibility().OverridePreviousFocus(shelf->GetStatusAreaWidget()); @@ -141,7 +142,7 @@ ? views::BoxLayout::Orientation::kHorizontal : views::BoxLayout::Orientation::kVertical; SetLayoutManager(std::make_unique<views::BoxLayout>( - orientation, gfx::Insets(), kShelfButtonSpacing)); + orientation, gfx::Insets(), ShelfConstants::button_spacing())); } ShelfNavigationWidget::ShelfNavigationWidget(Shelf* shelf, @@ -168,7 +169,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = container; - Init(params); + Init(std::move(params)); set_focus_on_creation(false); GetFocusManager()->set_arrow_key_traversal_enabled_for_widget(true); SetContentsView(delegate_); @@ -178,12 +179,13 @@ } gfx::Size ShelfNavigationWidget::GetIdealSize() const { + const int control_size = ShelfConstants::control_size(); if (!shelf_->IsHorizontalAlignment()) - return gfx::Size(kShelfControlSize, kShelfControlSize); + return gfx::Size(control_size, control_size); return gfx::Size(IsTabletMode() - ? (2 * kShelfControlSize + kShelfButtonSpacing) - : kShelfControlSize, - kShelfControlSize); + ? (2 * control_size + ShelfConstants::button_spacing()) + : control_size, + control_size); } bool ShelfNavigationWidget::OnNativeWidgetActivationChanged(bool active) { @@ -228,8 +230,10 @@ bounds_animator_->SetAnimationDuration(kBackButtonOpacityAnimationDurationMs); bounds_animator_->AnimateViewTo( - GetHomeButton(), gfx::Rect(kShelfControlSize + kShelfButtonSpacing, 0, - kShelfControlSize, kShelfControlSize)); + GetHomeButton(), + gfx::Rect( + ShelfConstants::control_size() + ShelfConstants::button_spacing(), 0, + ShelfConstants::control_size(), ShelfConstants::control_size())); } void ShelfNavigationWidget::OnTabletModeEnded() { @@ -243,7 +247,8 @@ GetBackButton()->SetFocusBehavior(views::View::FocusBehavior::NEVER); bounds_animator_->SetAnimationDuration(kBackButtonOpacityAnimationDurationMs); bounds_animator_->AnimateViewTo( - GetHomeButton(), gfx::Rect(0, 0, kShelfControlSize, kShelfControlSize)); + GetHomeButton(), gfx::Rect(0, 0, ShelfConstants::control_size(), + ShelfConstants::control_size())); } void ShelfNavigationWidget::OnImplicitAnimationsCompleted() {
diff --git a/ash/shelf/shelf_widget.cc b/ash/shelf/shelf_widget.cc index 5e5c2fa..17e6eb7 100644 --- a/ash/shelf/shelf_widget.cc +++ b/ash/shelf/shelf_widget.cc
@@ -320,7 +320,7 @@ params.delegate = delegate_view_; params.parent = shelf_container; - Init(params); + Init(std::move(params)); // The shelf should not take focus when initially shown. set_focus_on_creation(false);
diff --git a/ash/shelf/shelf_widget_unittest.cc b/ash/shelf/shelf_widget_unittest.cc index 291566cb..62c63818f 100644 --- a/ash/shelf/shelf_widget_unittest.cc +++ b/ash/shelf/shelf_widget_unittest.cc
@@ -155,7 +155,7 @@ params.bounds = gfx::Rect(0, 0, 200, 200); params.context = CurrentContext(); // Widget is now owned by the parent window. - widget->Init(params); + widget->Init(std::move(params)); widget->SetFullscreen(true); } @@ -221,7 +221,7 @@ kWindowWidth, kWindowHeight); params.context = CurrentContext(); // Widget is now owned by the parent window. - widget->Init(params); + widget->Init(std::move(params)); // Explicitly set the bounds which will allow the widget to overlap the shelf. widget->SetBounds(params.bounds); widget->Show(); @@ -302,7 +302,7 @@ params.bounds = gfx::Rect(0, 0, 200, 200); params.context = CurrentContext(); // Widget is now owned by the parent window. - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); aura::Window* root = shelf_widget->GetNativeWindow()->GetRootWindow();
diff --git a/ash/shell/content/embedded_browser.cc b/ash/shell/content/embedded_browser.cc index 23c23d0..e58fc888 100644 --- a/ash/shell/content/embedded_browser.cc +++ b/ash/shell/content/embedded_browser.cc
@@ -51,7 +51,7 @@ views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.bounds = bounds; params.delegate = new BrowserWidgetDelegateView(context, url); - widget_->Init(params); + widget_->Init(std::move(params)); WindowState::Get(widget_->GetNativeWindow())->SetWindowPositionManaged(true); widget_->Show(); }
diff --git a/ash/shell/lock_view.cc b/ash/shell/lock_view.cc index 8acda50..089d822 100644 --- a/ash/shell/lock_view.cc +++ b/ash/shell/lock_view.cc
@@ -96,7 +96,7 @@ params.delegate = lock_view; params.parent = Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_LockScreenContainer); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->GetNativeView()->SetName("LockView"); widget->GetNativeView()->Focus();
diff --git a/ash/shell_unittest.cc b/ash/shell_unittest.cc index 31c4252e..a2a844e 100644 --- a/ash/shell_unittest.cc +++ b/ash/shell_unittest.cc
@@ -187,7 +187,7 @@ views::Widget* CreateTestWindow(views::Widget::InitParams params) { views::Widget* widget = new views::Widget; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -198,7 +198,7 @@ if (always_on_top) widget_params.z_order = ui::ZOrderLevel::kFloatingWindow; - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); EXPECT_TRUE( @@ -220,7 +220,7 @@ // Create a LockScreen window. views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); - views::Widget* lock_widget = CreateTestWindow(widget_params); + views::Widget* lock_widget = CreateTestWindow(std::move(widget_params)); Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_LockScreenContainer) ->AddChild(lock_widget->GetNativeView()); @@ -274,7 +274,7 @@ params.delegate = new WindowWithPreferredSize; views::Widget widget; params.context = CurrentContext(); - widget.Init(params); + widget.Init(std::move(params)); // Widget is centered on secondary display. EXPECT_EQ(secondary_root, widget.GetNativeWindow()->GetRootWindow()); @@ -287,7 +287,7 @@ views::Widget::InitParams::TYPE_WINDOW); // Creates a normal window. - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); // It should be in the active desk container. @@ -319,7 +319,7 @@ views::Widget::InitParams::TYPE_WINDOW); // Create a normal window. - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); // It should be in the active desk container. @@ -353,7 +353,7 @@ views::Widget::InitParams::TYPE_WINDOW); // Create a normal window. - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); EXPECT_TRUE(widget->GetNativeView()->HasFocus()); @@ -363,7 +363,7 @@ GetSessionControllerClient()->LockScreen(); // Create a LockScreen window. - views::Widget* lock_widget = CreateTestWindow(widget_params); + views::Widget* lock_widget = CreateTestWindow(std::move(widget_params)); Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_LockScreenContainer) ->AddChild(lock_widget->GetNativeView()); @@ -466,7 +466,7 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); widget_params.bounds.SetRect(11, 22, 300, 400); - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); EXPECT_FALSE(widget->IsMaximized()); @@ -481,7 +481,7 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); widget_params.bounds.SetRect(11, 22, 300, 400); - views::Widget* widget = CreateTestWindow(widget_params); + views::Widget* widget = CreateTestWindow(std::move(widget_params)); widget->Show(); EXPECT_FALSE(widget->IsMaximized());
diff --git a/ash/sticky_keys/sticky_keys_overlay.cc b/ash/sticky_keys/sticky_keys_overlay.cc index b86db125..ce7ff0f 100644 --- a/ash/sticky_keys/sticky_keys_overlay.cc +++ b/ash/sticky_keys/sticky_keys_overlay.cc
@@ -216,7 +216,7 @@ params.parent = Shell::GetContainer(Shell::GetRootWindowForNewWindows(), kShellWindowId_OverlayContainer); overlay_widget_.reset(new views::Widget); - overlay_widget_->Init(params); + overlay_widget_->Init(std::move(params)); overlay_widget_->SetVisibilityChangedAnimationsEnabled(false); overlay_widget_->SetContentsView(overlay_view_.get()); overlay_widget_->GetNativeView()->SetName("StickyKeysOverlay");
diff --git a/ash/system/bluetooth/bluetooth_feature_pod_controller.cc b/ash/system/bluetooth/bluetooth_feature_pod_controller.cc index 4124945..5c47e09 100644 --- a/ash/system/bluetooth/bluetooth_feature_pod_controller.cc +++ b/ash/system/bluetooth/bluetooth_feature_pod_controller.cc
@@ -144,10 +144,17 @@ void BluetoothFeaturePodController::SetTooltipState( const base::string16& tooltip_state) { - button_->SetIconTooltip(l10n_util::GetStringFUTF16( - IDS_ASH_STATUS_TRAY_BLUETOOTH_TOGGLE_TOOLTIP, tooltip_state)); - button_->SetLabelTooltip(l10n_util::GetStringFUTF16( - IDS_ASH_STATUS_TRAY_BLUETOOTH_SETTINGS_TOOLTIP, tooltip_state)); + if (button_->GetEnabled()) { + button_->SetIconTooltip(l10n_util::GetStringFUTF16( + IDS_ASH_STATUS_TRAY_BLUETOOTH_TOGGLE_TOOLTIP, tooltip_state)); + button_->SetLabelTooltip(l10n_util::GetStringFUTF16( + IDS_ASH_STATUS_TRAY_BLUETOOTH_SETTINGS_TOOLTIP, tooltip_state)); + } else { + // Do not show "Toggle" text in tooltip when the button is disabled (e.g. + // when the screen is locked or for secondary users). + button_->SetIconTooltip(tooltip_state); + button_->SetLabelTooltip(tooltip_state); + } } void BluetoothFeaturePodController::OnBluetoothSystemStateChanged() {
diff --git a/ash/system/bluetooth/bluetooth_notification_controller.cc b/ash/system/bluetooth/bluetooth_notification_controller.cc index d9160b2..fd330c3b 100644 --- a/ash/system/bluetooth/bluetooth_notification_controller.cc +++ b/ash/system/bluetooth/bluetooth_notification_controller.cc
@@ -17,6 +17,7 @@ #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "device/bluetooth/bluetooth_adapter_factory.h" @@ -36,6 +37,8 @@ namespace { const char kNotifierBluetooth[] = "ash.bluetooth"; +const char kPairedNotificationPrefix[] = + "cros_bluetooth_device_paired_notification_id-"; // The BluetoothPairingNotificationDelegate handles user interaction with the // pairing notification and sending the confirmation, rejection or cancellation @@ -128,10 +131,6 @@ BluetoothNotificationController::kBluetoothDevicePairingNotificationId[] = "cros_bluetooth_device_pairing_notification_id"; -const char - BluetoothNotificationController::kBluetoothDevicePairedNotificationId[] = - "cros_bluetooth_device_paired_notification_id"; - // This class handles opening the Bluetooth Settings UI when the user clicks // on the Paired Notification. class BluetoothNotificationController::BluetoothPairedNotificationDelegate @@ -267,6 +266,12 @@ NotifyPairing(device, message, true); } +// static +std::string BluetoothNotificationController::GetPairedNotificationId( + const BluetoothDevice* device) { + return kPairedNotificationPrefix + base::ToLowerASCII(device->GetAddress()); +} + void BluetoothNotificationController::OnGetAdapter( scoped_refptr<BluetoothAdapter> adapter) { DCHECK(!adapter_.get()); @@ -346,8 +351,8 @@ } std::unique_ptr<Notification> notification = ash::CreateSystemNotification( - message_center::NOTIFICATION_TYPE_SIMPLE, - kBluetoothDevicePairedNotificationId, base::string16() /* title */, + message_center::NOTIFICATION_TYPE_SIMPLE, GetPairedNotificationId(device), + base::string16() /* title */, l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BLUETOOTH_PAIRED, device->GetNameForDisplay()), base::string16() /* display source */, GURL(),
diff --git a/ash/system/bluetooth/bluetooth_notification_controller.h b/ash/system/bluetooth/bluetooth_notification_controller.h index 81accf4d..3ee3301 100644 --- a/ash/system/bluetooth/bluetooth_notification_controller.h +++ b/ash/system/bluetooth/bluetooth_notification_controller.h
@@ -68,7 +68,10 @@ // and means we "update" one notification if not handled rather than // continually bugging the user. static const char kBluetoothDevicePairingNotificationId[]; - static const char kBluetoothDevicePairedNotificationId[]; + + // Adds a prefix to the device's address to obtain an unique notification ID. + static std::string GetPairedNotificationId( + const device::BluetoothDevice* device); // Internal method called by BluetoothAdapterFactory to provide the adapter // object.
diff --git a/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc b/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc index 5f830470..dc84077 100644 --- a/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc +++ b/ash/system/bluetooth/bluetooth_notification_controller_unittest.cc
@@ -55,37 +55,40 @@ std::make_unique<BluetoothNotificationController>( &test_message_center_); system_tray_client_ = GetSystemTrayClient(); - bluetooth_device_ = + + bluetooth_device_1_ = std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( - nullptr /* adapter */, 0 /* bluetooth_class */, "name", "address", - false /* paired */, false /* connected */); - - // Mock the device is paired. - ON_CALL(*bluetooth_device_, IsPaired()).WillByDefault(Return(true)); + nullptr /* adapter */, 0 /* bluetooth_class */, "name_1", + "address_1", false /* paired */, false /* connected */); + bluetooth_device_2_ = + std::make_unique<testing::NiceMock<device::MockBluetoothDevice>>( + nullptr /* adapter */, 0 /* bluetooth_class */, "name_2", + "address_2", false /* paired */, false /* connected */); } - void ClickPairedNotification() { + void ClickPairedNotification(const device::BluetoothDevice* device) { test_message_center_.ClickOnNotification( - BluetoothNotificationController::kBluetoothDevicePairedNotificationId); + BluetoothNotificationController::GetPairedNotificationId(device)); } - void DismissPairedNotification(bool by_user) { + void DismissPairedNotification(const device::BluetoothDevice* device, + bool by_user) { test_message_center_.RemoveNotification( - BluetoothNotificationController::kBluetoothDevicePairedNotificationId, + BluetoothNotificationController::GetPairedNotificationId(device), by_user); } - void VerifyPairedNotificationIsNotVisible() { + void VerifyPairedNotificationIsNotVisible( + const device::BluetoothDevice* device) { EXPECT_FALSE(test_message_center_.FindVisibleNotificationById( - BluetoothNotificationController::kBluetoothDevicePairedNotificationId)); + BluetoothNotificationController::GetPairedNotificationId(device))); } void VerifyPairedNotificationIsVisible( const device::BluetoothDevice* device) { message_center::Notification* visible_notification = test_message_center_.FindVisibleNotificationById( - BluetoothNotificationController:: - kBluetoothDevicePairedNotificationId); + BluetoothNotificationController::GetPairedNotificationId(device)); EXPECT_TRUE(visible_notification); EXPECT_EQ(base::string16(), visible_notification->title()); EXPECT_EQ(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BLUETOOTH_PAIRED, @@ -104,7 +107,8 @@ TestMessageCenter test_message_center_; std::unique_ptr<BluetoothNotificationController> notification_controller_; TestSystemTrayClient* system_tray_client_; - std::unique_ptr<device::MockBluetoothDevice> bluetooth_device_; + std::unique_ptr<device::MockBluetoothDevice> bluetooth_device_1_; + std::unique_ptr<device::MockBluetoothDevice> bluetooth_device_2_; DISALLOW_COPY_AND_ASSIGN(BluetoothNotificationControllerTest); }; @@ -113,29 +117,49 @@ PairedDeviceNotification_TapNotification) { // Show the notification to the user. ShowPairedNotification(notification_controller_.get(), - bluetooth_device_.get()); + bluetooth_device_1_.get()); - VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); - ClickPairedNotification(); + ClickPairedNotification(bluetooth_device_1_.get()); // The notification shouldn't dismiss after a click. - VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); // Check the notification controller tried to open the UI. EXPECT_EQ(1, system_tray_client_->show_bluetooth_settings_count()); } TEST_F(BluetoothNotificationControllerTest, + PairedDeviceNotification_MultipleNotifications) { + // Show the notification to the user. + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_1_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); + + // Pairing a new device should create a new notification. + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_2_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_2_.get()); +} + +TEST_F(BluetoothNotificationControllerTest, PairedDeviceNotification_UserDismissesNotification) { ShowPairedNotification(notification_controller_.get(), - bluetooth_device_.get()); + bluetooth_device_1_.get()); + ShowPairedNotification(notification_controller_.get(), + bluetooth_device_2_.get()); - VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_2_.get()); - DismissPairedNotification(true /* by_user */); + // Remove one notification, the other one should still be visible. + DismissPairedNotification(bluetooth_device_1_.get(), true /* by_user */); - VerifyPairedNotificationIsNotVisible(); + VerifyPairedNotificationIsNotVisible(bluetooth_device_1_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_2_.get()); + // The settings UI should not open when closing the notification. EXPECT_EQ(0, system_tray_client_->show_bluetooth_settings_count()); } @@ -143,13 +167,13 @@ TEST_F(BluetoothNotificationControllerTest, PairedDeviceNotification_SystemDismissesNotification) { ShowPairedNotification(notification_controller_.get(), - bluetooth_device_.get()); + bluetooth_device_1_.get()); - VerifyPairedNotificationIsVisible(bluetooth_device_.get()); + VerifyPairedNotificationIsVisible(bluetooth_device_1_.get()); - DismissPairedNotification(false /* by_user */); + DismissPairedNotification(bluetooth_device_1_.get(), false /* by_user */); - VerifyPairedNotificationIsNotVisible(); + VerifyPairedNotificationIsNotVisible(bluetooth_device_1_.get()); EXPECT_EQ(0, system_tray_client_->show_bluetooth_settings_count()); }
diff --git a/ash/system/message_center/arc/arc_notification_content_view.cc b/ash/system/message_center/arc/arc_notification_content_view.cc index a9db22d..28725a6635 100644 --- a/ash/system/message_center/arc/arc_notification_content_view.cc +++ b/ash/system/message_center/arc/arc_notification_content_view.cc
@@ -376,7 +376,7 @@ params.parent = surface_->GetWindow(); floating_control_buttons_widget_.reset(new views::Widget); - floating_control_buttons_widget_->Init(params); + floating_control_buttons_widget_->Init(std::move(params)); floating_control_buttons_widget_->SetContentsView(&control_buttons_view_); floating_control_buttons_widget_->GetNativeWindow()->AddPreTargetHandler( mouse_enter_exit_handler_.get());
diff --git a/ash/system/message_center/arc/arc_notification_content_view_unittest.cc b/ash/system/message_center/arc/arc_notification_content_view_unittest.cc index 4a903d2..094d880 100644 --- a/ash/system/message_center/arc/arc_notification_content_view_unittest.cc +++ b/ash/system/message_center/arc/arc_notification_content_view_unittest.cc
@@ -175,7 +175,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = Shell::GetPrimaryRootWindow(); auto wrapper_widget = std::make_unique<views::Widget>(); - wrapper_widget->Init(params); + wrapper_widget->Init(std::move(params)); wrapper_widget->SetContentsView(notification_view.get()); wrapper_widget->SetSize(notification_view->GetPreferredSize());
diff --git a/ash/system/message_center/arc/arc_notification_view_unittest.cc b/ash/system/message_center/arc/arc_notification_view_unittest.cc index 3354527..c18d113 100644 --- a/ash/system/message_center/arc/arc_notification_view_unittest.cc +++ b/ash/system/message_center/arc/arc_notification_view_unittest.cc
@@ -95,7 +95,7 @@ init_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; views::Widget* widget = new views::Widget(); - widget->Init(init_params); + widget->Init(std::move(init_params)); widget->SetContentsView(notification_view_.get()); widget->SetSize(notification_view_->GetPreferredSize()); widget->Show();
diff --git a/ash/system/power/peripheral_battery_notifier.cc b/ash/system/power/peripheral_battery_notifier.cc index 0ff8951..2b80579 100644 --- a/ash/system/power/peripheral_battery_notifier.cc +++ b/ash/system/power/peripheral_battery_notifier.cc
@@ -6,6 +6,7 @@ #include <vector> +#include "ash/power/hid_battery_util.h" #include "ash/public/cpp/notification_utils.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/shell.h" @@ -15,13 +16,10 @@ #include "base/macros.h" #include "base/strings/string16.h" #include "base/strings/string_piece.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/default_tick_clock.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h" -#include "third_party/re2/src/re2/re2.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/events/devices/device_data_manager.h" @@ -49,69 +47,13 @@ const char kNotificationOriginUrl[] = "chrome://peripheral-battery"; const char kNotifierNonStylusBattery[] = "power.peripheral-battery"; -// HID device's battery sysfs entry path looks like -// /sys/class/power_supply/hid-{AA:BB:CC:DD:EE:FF|AAAA:BBBB:CCCC.DDDD}-battery. -// Here the bluetooth address is showed in reverse order and its true -// address "FF:EE:DD:CC:BB:AA". -const char kHIDBatteryPathPrefix[] = "/sys/class/power_supply/hid-"; -const char kHIDBatteryPathSuffix[] = "-battery"; - // Prefix added to the address of a Bluetooth device to generate an unique ID // when posting a notification to the Message Center. const char kBluetoothDeviceIdPrefix[] = "battery_notification_bluetooth-"; -// Regex to check for valid bluetooth addresses. -constexpr char kBluetoothAddressRegex[] = - "^([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2})$"; - -// Checks whether the device at |path| is a HID battery. Returns false if |path| -// is lacking the HID battery prefix or suffix, or if it contains them but has -// nothing in between. -bool IsHIDBattery(const std::string& path) { - if (!base::StartsWith(path, kHIDBatteryPathPrefix, - base::CompareCase::INSENSITIVE_ASCII) || - !base::EndsWith(path, kHIDBatteryPathSuffix, - base::CompareCase::INSENSITIVE_ASCII)) { - return false; - } - - return static_cast<int>(path.size()) - - static_cast<int>(strlen(kHIDBatteryPathPrefix) + - strlen(kHIDBatteryPathSuffix)) > - 0; -} - -// Extract the identifier in |path| found between the path prefix and suffix. -std::string ExtractIdentifier(const std::string& path) { - int header_size = strlen(kHIDBatteryPathPrefix); - int end_size = strlen(kHIDBatteryPathSuffix); - int key_len = path.size() - header_size - end_size; - if (key_len <= 0) - return std::string(); - - return path.substr(header_size, key_len); -} - -// Extracts a Bluetooth address (e.g. "AA:BB:CC:DD:EE:FF") from |path|, a sysfs -// device path like "/sys/class/power-supply/hid-AA:BB:CC:DD:EE:FF-battery". -// The address supplied in |path| is reversed, so this method will reverse the -// extracted address. Returns an empty string if |path| does not contain a -// Bluetooth address. -std::string ExtractBluetoothAddressFromPath(const std::string& path) { - std::string identifier = ExtractIdentifier(path); - if (!RE2::FullMatch(identifier, kBluetoothAddressRegex)) - return std::string(); - - std::string reverse_address = base::ToLowerASCII(identifier); - std::vector<base::StringPiece> result = base::SplitStringPiece( - reverse_address, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); - std::reverse(result.begin(), result.end()); - return base::JoinString(result, ":"); -} - // Checks if the device is an external stylus. bool IsStylusDevice(const std::string& path, const std::string& model_name) { - std::string identifier = ExtractIdentifier(path); + std::string identifier = ExtractHIDBatteryIdentifier(path); for (const ui::TouchscreenDevice& device : ui::DeviceDataManager::GetInstance()->GetTouchscreenDevices()) { if (device.has_stylus && @@ -168,7 +110,8 @@ // Returns the corresponding map key for a HID device. std::string GetBatteryMapKey(const std::string& path) { // Check if the HID path corresponds to a Bluetooth device. - const std::string bluetooth_address = ExtractBluetoothAddressFromPath(path); + const std::string bluetooth_address = + ExtractBluetoothAddressFromHIDBatteryPath(path); return bluetooth_address.empty() ? path : GetMapKeyForBluetoothAddress(bluetooth_address); @@ -248,7 +191,7 @@ BatteryInfo battery{base::ASCIIToUTF16(name), level, base::TimeTicks(), IsStylusDevice(path, name), - ExtractBluetoothAddressFromPath(path)}; + ExtractBluetoothAddressFromHIDBatteryPath(path)}; UpdateBattery(GetBatteryMapKey(path), battery); }
diff --git a/ash/system/power/power_button_controller.cc b/ash/system/power/power_button_controller.cc index 192d9e9..65201a4 100644 --- a/ash/system/power/power_button_controller.cc +++ b/ash/system/power/power_button_controller.cc
@@ -71,7 +71,7 @@ params.layer_type = ui::LAYER_SOLID_COLOR; params.parent = Shell::GetPrimaryRootWindow()->GetChildById( kShellWindowId_PowerMenuContainer); - menu_widget->Init(params); + menu_widget->Init(std::move(params)); gfx::Rect widget_bounds = display::Screen::GetScreen()->GetPrimaryDisplay().bounds();
diff --git a/ash/system/session/logout_confirmation_dialog.cc b/ash/system/session/logout_confirmation_dialog.cc index e1a5e87..fdba529 100644 --- a/ash/system/session/logout_confirmation_dialog.cc +++ b/ash/system/session/logout_confirmation_dialog.cc
@@ -54,7 +54,7 @@ GetDialogWidgetInitParams(this, nullptr, nullptr, gfx::Rect()); params.parent = Shell::GetPrimaryRootWindow()->GetChildById( kShellWindowId_SystemModalContainer); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); update_timer_.Start(
diff --git a/ash/system/status_area_widget.cc b/ash/system/status_area_widget.cc index 8179464e..0f5bb10 100644 --- a/ash/system/status_area_widget.cc +++ b/ash/system/status_area_widget.cc
@@ -35,7 +35,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = status_container; - Init(params); + Init(std::move(params)); set_focus_on_creation(false); SetContentsView(status_area_widget_delegate_); }
diff --git a/ash/system/toast/toast_overlay.cc b/ash/system/toast/toast_overlay.cc index 26450a5..feff7ef 100644 --- a/ash/system/toast/toast_overlay.cc +++ b/ash/system/toast/toast_overlay.cc
@@ -237,7 +237,7 @@ params.parent = Shell::GetRootWindowForNewWindows()->GetChildById( show_on_lock_screen ? kShellWindowId_LockSystemModalContainer : kShellWindowId_SystemModalContainer); - overlay_widget_->Init(params); + overlay_widget_->Init(std::move(params)); overlay_widget_->SetVisibilityChangedAnimationsEnabled(true); overlay_widget_->SetContentsView(overlay_view_.get()); UpdateOverlayBounds();
diff --git a/ash/test/ash_test_base.cc b/ash/test/ash_test_base.cc index f355384..bd421c0 100644 --- a/ash/test/ash_test_base.cc +++ b/ash/test/ash_test_base.cc
@@ -242,7 +242,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.parent = Shell::GetPrimaryRootWindow()->GetChildById(container_id); - widget->Init(params); + widget->Init(std::move(params)); if (show) widget->Show(); return widget; @@ -266,7 +266,7 @@ params.bounds = bounds_in_screen.IsEmpty() ? gfx::Rect(0, 0, 300, 300) : bounds_in_screen; params.context = Shell::GetPrimaryRootWindow(); - widget->Init(params); + widget->Init(std::move(params)); widget->GetNativeWindow()->set_id(shell_window_id); widget->Show(); return base::WrapUnique(widget->GetNativeWindow());
diff --git a/ash/test/ash_test_helper_unittest.cc b/ash/test/ash_test_helper_unittest.cc index 65410e1..ceeb3d0 100644 --- a/ash/test/ash_test_helper_unittest.cc +++ b/ash/test/ash_test_helper_unittest.cc
@@ -53,7 +53,7 @@ Widget::InitParams params; params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = ash_test_helper()->CurrentContext(); - w1->Init(params); + w1->Init(std::move(params)); w1->Show(); EXPECT_TRUE(w1->IsActive()); EXPECT_TRUE(w1->IsVisible());
diff --git a/ash/tooltips/tooltip_controller_unittest.cc b/ash/tooltips/tooltip_controller_unittest.cc index 9c6c0b5..0756bd0 100644 --- a/ash/tooltips/tooltip_controller_unittest.cc +++ b/ash/tooltips/tooltip_controller_unittest.cc
@@ -44,7 +44,7 @@ Shell::Get()->GetContainer(Shell::GetAllRootWindows().at(display), desks_util::GetActiveDeskContainerId()); params.bounds = bounds; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/touch/touch_observer_hud.cc b/ash/touch/touch_observer_hud.cc index 1f29c2c..632158a 100644 --- a/ash/touch/touch_observer_hud.cc +++ b/ash/touch/touch_observer_hud.cc
@@ -39,7 +39,7 @@ params.parent = Shell::GetContainer(root_window_, kShellWindowId_OverlayContainer); params.name = widget_name; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetContentsView(content); widget_->StackAtTop(); widget_->Show();
diff --git a/ash/wallpaper/wallpaper_view.cc b/ash/wallpaper/wallpaper_view.cc index 1a85917..13c874b10 100644 --- a/ash/wallpaper/wallpaper_view.cc +++ b/ash/wallpaper/wallpaper_view.cc
@@ -183,7 +183,7 @@ if (controller->GetWallpaper().isNull()) params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.parent = root_window->GetChildById(container_id); - wallpaper_widget->Init(params); + wallpaper_widget->Init(std::move(params)); // Owned by views. WallpaperView* wallpaper_view = new WallpaperView(blur, opacity); wallpaper_widget->SetContentsView(new LayerControlView(wallpaper_view));
diff --git a/ash/wm/ash_focus_rules_unittest.cc b/ash/wm/ash_focus_rules_unittest.cc index a19ec68..ae58a06 100644 --- a/ash/wm/ash_focus_rules_unittest.cc +++ b/ash/wm/ash_focus_rules_unittest.cc
@@ -72,7 +72,7 @@ params.parent = Shell::GetContainer(Shell::GetPrimaryRootWindow(), kShellWindowId_LockScreenContainer); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - lock_screen_widget_->Init(params); + lock_screen_widget_->Init(std::move(params)); lock_screen_widget_->SetContentsView(lock_view); lock_screen_widget_->Show(); lock_screen_widget_->GetNativeView()->SetName("LockView");
diff --git a/ash/wm/client_controlled_state_unittest.cc b/ash/wm/client_controlled_state_unittest.cc index a56e0fc..ca7cfde 100644 --- a/ash/wm/client_controlled_state_unittest.cc +++ b/ash/wm/client_controlled_state_unittest.cc
@@ -118,7 +118,7 @@ params.delegate = widget_delegate_; widget_ = std::make_unique<views::Widget>(); - widget_->Init(params); + widget_->Init(std::move(params)); WindowState* window_state = WindowState::Get(window()); window_state->set_allow_set_bounds_direct(true); auto delegate = std::make_unique<TestClientControlledStateDelegate>();
diff --git a/ash/wm/desks/desks_bar_view.cc b/ash/wm/desks/desks_bar_view.cc index 9ecfa12..93f99339 100644 --- a/ash/wm/desks/desks_bar_view.cc +++ b/ash/wm/desks/desks_bar_view.cc
@@ -153,7 +153,7 @@ params.parent = root->GetChildById(kShellWindowId_WallpaperContainer); params.bounds = bounds; params.name = "VirtualDesksWidget"; - widget->Init(params); + widget->Init(std::move(params)); ::wm::SetWindowVisibilityAnimationTransition(widget->GetNativeWindow(), ::wm::ANIMATE_NONE);
diff --git a/ash/wm/desks/desks_unittests.cc b/ash/wm/desks/desks_unittests.cc index 6b537331..81d67703 100644 --- a/ash/wm/desks/desks_unittests.cc +++ b/ash/wm/desks/desks_unittests.cc
@@ -1292,6 +1292,39 @@ EXPECT_EQ(nullptr, window_util::GetActiveWindow()); } +TEST_F(DesksTest, NoMiniViewsUpdateOnOverviewEnter) { + auto* controller = DesksController::Get(); + NewDesk(); + ASSERT_EQ(2u, controller->desks().size()); + auto* desk_1 = controller->desks()[0].get(); + auto* desk_2 = controller->desks()[1].get(); + + auto win0 = CreateTestWindow(gfx::Rect(0, 0, 250, 100)); + auto win1 = CreateTestWindow(gfx::Rect(50, 50, 200, 200)); + wm::ActivateWindow(win1.get()); + EXPECT_EQ(win1.get(), window_util::GetActiveWindow()); + + TestDeskObserver desk_1_observer; + TestDeskObserver desk_2_observer; + desk_1->AddObserver(&desk_1_observer); + desk_2->AddObserver(&desk_2_observer); + EXPECT_EQ(0, desk_1_observer.notify_counts()); + EXPECT_EQ(0, desk_2_observer.notify_counts()); + + // The widgets created by overview mode, whose windows are added to the active + // desk's container, should never result in mini_views updates since they're + // not mirrored there at all. + auto* overview_controller = Shell::Get()->overview_controller(); + overview_controller->StartOverview(); + EXPECT_TRUE(overview_controller->InOverviewSession()); + + EXPECT_EQ(0, desk_1_observer.notify_counts()); + EXPECT_EQ(0, desk_2_observer.notify_counts()); + + desk_1->RemoveObserver(&desk_1_observer); + desk_2->RemoveObserver(&desk_2_observer); +} + class TabletModeDesksTest : public DesksTest { public: TabletModeDesksTest() = default;
diff --git a/ash/wm/immersive_fullscreen_controller_unittest.cc b/ash/wm/immersive_fullscreen_controller_unittest.cc index 641d9c5..e05a65f3 100644 --- a/ash/wm/immersive_fullscreen_controller_unittest.cc +++ b/ash/wm/immersive_fullscreen_controller_unittest.cc
@@ -176,7 +176,7 @@ views::Widget::InitParams params; params.delegate = new TestWidgetDelegate(); params.context = CurrentContext(); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); SetWindowShowState(ui::SHOW_STATE_FULLSCREEN); @@ -932,7 +932,7 @@ transient_params.parent = top_container_widget->GetNativeView(); transient_params.bounds = gfx::Rect(0, 100, 100, 100); std::unique_ptr<views::Widget> transient_widget(new views::Widget()); - transient_widget->Init(transient_params); + transient_widget->Init(std::move(transient_params)); EXPECT_FALSE(controller()->IsRevealed()); AttemptReveal(MODALITY_MOUSE); @@ -951,7 +951,7 @@ non_transient_params.bounds = gfx::Rect(0, 100, 100, 100); std::unique_ptr<views::Widget> non_transient_widget(new views::Widget()); non_transient_params.context = CurrentContext(); - non_transient_widget->Init(non_transient_params); + non_transient_widget->Init(std::move(non_transient_params)); EXPECT_FALSE(controller()->IsRevealed()); AttemptReveal(MODALITY_MOUSE);
diff --git a/ash/wm/lock_action_handler_layout_manager_unittest.cc b/ash/wm/lock_action_handler_layout_manager_unittest.cc index abe2b8b..f571ca8 100644 --- a/ash/wm/lock_action_handler_layout_manager_unittest.cc +++ b/ash/wm/lock_action_handler_layout_manager_unittest.cc
@@ -91,9 +91,9 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; - lock_window_ = - CreateTestingWindow(widget_params, kShellWindowId_LockScreenContainer, - std::make_unique<TestWindowDelegate>()); + lock_window_ = CreateTestingWindow(std::move(widget_params), + kShellWindowId_LockScreenContainer, + std::make_unique<TestWindowDelegate>()); } void TearDown() override { @@ -112,7 +112,7 @@ window_delegate->set_widget(widget); params.delegate = window_delegate.release(); } - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return base::WrapUnique<aura::Window>(widget->GetNativeView()); } @@ -202,7 +202,7 @@ // Note: default window delegate (used when no widget delegate is set) does // not allow the window to be maximized. std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); EXPECT_EQ(bounds.ToString(), window->GetBoundsInScreen().ToString()); @@ -229,7 +229,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, std::make_unique<TestWindowDelegate>()); // Verify that the window bounds are equal to work area for the bottom shelf @@ -253,7 +253,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, std::make_unique<TestWindowDelegate>()); // Verify that the window bounds are equal to work area for the bottom shelf @@ -274,7 +274,7 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW); std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, std::make_unique<TestWindowDelegate>()); gfx::Rect target_bounds = @@ -296,7 +296,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, std::make_unique<TestWindowDelegate>()); ASSERT_EQ(initial_bounds.ToString(), window->GetBoundsInScreen().ToString()); @@ -339,7 +339,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); EXPECT_TRUE(window->IsVisible()); @@ -353,7 +353,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); EXPECT_TRUE(window->IsVisible()); @@ -367,7 +367,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); // The window should not be visible if the note action is not in active state. @@ -399,7 +399,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); EXPECT_EQ(GetContainer(kShellWindowId_LockActionHandlerContainer), @@ -421,7 +421,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_MAXIMIZED; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, nullptr /* window_delegate */); EXPECT_EQ(GetContainer(kShellWindowId_LockActionHandlerContainer), @@ -444,7 +444,7 @@ views::Widget::InitParams::TYPE_WINDOW); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; std::unique_ptr<aura::Window> window = CreateTestingWindow( - widget_params, kShellWindowId_LockActionHandlerContainer, + std::move(widget_params), kShellWindowId_LockActionHandlerContainer, std::make_unique<TestWindowDelegate>()); gfx::Rect target_bounds =
diff --git a/ash/wm/lock_layout_manager_unittest.cc b/ash/wm/lock_layout_manager_unittest.cc index 7c985c2..c907c53 100644 --- a/ash/wm/lock_layout_manager_unittest.cc +++ b/ash/wm/lock_layout_manager_unittest.cc
@@ -71,7 +71,7 @@ if (use_delegate) params.delegate = new LoginTestWidgetDelegate(widget); params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); aura::Window* window = widget->GetNativeView(); return window; @@ -110,8 +110,8 @@ views::Widget::InitParams::TYPE_WINDOW); const gfx::Rect bounds = gfx::Rect(10, 10, 300, 300); widget_params.bounds = bounds; - std::unique_ptr<aura::Window> window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); EXPECT_EQ(bounds.ToString(), window->GetBoundsInScreen().ToString()); gfx::Rect work_area = @@ -138,12 +138,12 @@ // Maximized TYPE_WINDOW_FRAMELESS windows needs a delegate defined otherwise // it won't get initial SetBounds event. std::unique_ptr<aura::Window> maximized_window( - CreateTestLoginWindow(widget_params, true /* use_delegate */)); + CreateTestLoginWindow(std::move(widget_params), true /* use_delegate */)); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; widget_params.delegate = NULL; - std::unique_ptr<aura::Window> fullscreen_window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> fullscreen_window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); EXPECT_EQ(screen_bounds.ToString(), maximized_window->GetBoundsInScreen().ToString()); @@ -190,8 +190,8 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; - std::unique_ptr<aura::Window> window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); display::Display primary_display = display::Screen::GetScreen()->GetPrimaryDisplay(); @@ -222,8 +222,8 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; - std::unique_ptr<aura::Window> window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); EXPECT_EQ(screen_bounds.ToString(), window->GetBoundsInScreen().ToString()); @@ -292,8 +292,8 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; - std::unique_ptr<aura::Window> window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); window->SetProperty(aura::client::kResizeBehaviorKey, aura::client::kResizeBehaviorCanMaximize); @@ -350,8 +350,8 @@ views::Widget::InitParams widget_params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); widget_params.show_state = ui::SHOW_STATE_FULLSCREEN; - std::unique_ptr<aura::Window> window( - CreateTestLoginWindow(widget_params, false /* use_delegate */)); + std::unique_ptr<aura::Window> window(CreateTestLoginWindow( + std::move(widget_params), false /* use_delegate */)); window->SetProperty(aura::client::kResizeBehaviorKey, aura::client::kResizeBehaviorCanMaximize);
diff --git a/ash/wm/overview/cleanup_animation_observer_unittest.cc b/ash/wm/overview/cleanup_animation_observer_unittest.cc index 1dde603..bd548036 100644 --- a/ash/wm/overview/cleanup_animation_observer_unittest.cc +++ b/ash/wm/overview/cleanup_animation_observer_unittest.cc
@@ -74,7 +74,7 @@ params.type = views::Widget::InitParams::TYPE_WINDOW; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->AddObserver(this); widget_ = widget.get();
diff --git a/ash/wm/overview/overview_grid.cc b/ash/wm/overview/overview_grid.cc index e6d53f3..1e1e3cb 100644 --- a/ash/wm/overview/overview_grid.cc +++ b/ash/wm/overview/overview_grid.cc
@@ -169,15 +169,15 @@ params.accept_events = false; params.parent = parent; params.bounds = bounds; + params.init_properties_container.SetProperty(kHideInDeskMiniViewKey, true); auto widget = std::make_unique<views::Widget>(); widget->set_focus_on_creation(false); - widget->Init(params); + widget->Init(std::move(params)); // Show plus icon if drag a tab from a multi-tab window. widget->SetContentsView(new DropTargetView( dragged_window->GetProperty(ash::kTabDraggingSourceWindowKey))); aura::Window* drop_target_window = widget->GetNativeWindow(); - drop_target_window->SetProperty(kHideInDeskMiniViewKey, true); drop_target_window->parent()->StackChildAtBottom(drop_target_window); widget->Show();
diff --git a/ash/wm/overview/overview_highlight_controller.cc b/ash/wm/overview/overview_highlight_controller.cc index 074c73a7..51b00a89 100644 --- a/ash/wm/overview/overview_highlight_controller.cc +++ b/ash/wm/overview/overview_highlight_controller.cc
@@ -93,11 +93,11 @@ params.accept_events = false; params.parent = root_window->GetChildById(kShellWindowId_WallpaperContainer); + params.init_properties_container.SetProperty(kHideInDeskMiniViewKey, true); set_focus_on_creation(false); - Init(params); + Init(std::move(params)); aura::Window* widget_window = GetNativeWindow(); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); // Disable the "bounce in" animation when showing the window. ::wm::SetWindowVisibilityAnimationTransition(widget_window, ::wm::ANIMATE_NONE);
diff --git a/ash/wm/overview/overview_item.cc b/ash/wm/overview/overview_item.cc index af33e2f..e24e7ea 100644 --- a/ash/wm/overview/overview_item.cc +++ b/ash/wm/overview/overview_item.cc
@@ -521,10 +521,9 @@ params.message_id = IDS_ASH_SPLIT_VIEW_CANNOT_SNAP; params.parent = root_window()->GetChildById(kShellWindowId_AlwaysOnTopContainer); + params.hide_in_mini_view = true; cannot_snap_widget_ = std::make_unique<RoundedLabelWidget>(); - cannot_snap_widget_->Init(params); - auto* widget_window = cannot_snap_widget_->GetNativeWindow(); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); + cannot_snap_widget_->Init(std::move(params)); } DoSplitviewOpacityAnimation(cannot_snap_widget_->GetNativeWindow()->layer(), @@ -973,13 +972,13 @@ views::Widget::InitParams::Activatable::ACTIVATABLE_DEFAULT; params.accept_events = true; params.parent = transform_window_.window()->parent(); + params.init_properties_container.SetProperty(kHideInDeskMiniViewKey, true); item_widget_ = std::make_unique<views::Widget>(); item_widget_->set_focus_on_creation(false); - item_widget_->Init(params); + item_widget_->Init(std::move(params)); aura::Window* widget_window = item_widget_->GetNativeWindow(); widget_window->parent()->StackChildBelow(widget_window, GetWindow()); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); shadow_ = std::make_unique<ui::Shadow>(); shadow_->Init(kShadowElevation);
diff --git a/ash/wm/overview/overview_session.cc b/ash/wm/overview/overview_session.cc index 1a2b18e..89b7b405d 100644 --- a/ash/wm/overview/overview_session.cc +++ b/ash/wm/overview/overview_session.cc
@@ -261,7 +261,7 @@ params.name = "OverviewModeFocusedWidget"; params.parent = Shell::GetPrimaryRootWindow()->GetChildById( kShellWindowId_StatusContainer); - overview_focus_widget_->Init(params); + overview_focus_widget_->Init(std::move(params)); UMA_HISTOGRAM_COUNTS_100("Ash.WindowSelector.Items", num_items_); @@ -1025,11 +1025,11 @@ params.message_id = IDS_ASH_OVERVIEW_NO_RECENT_ITEMS; params.parent = Shell::GetPrimaryRootWindow()->GetChildById( desks_util::GetActiveDeskContainerId()); + params.hide_in_mini_view = true; no_windows_widget_ = std::make_unique<RoundedLabelWidget>(); - no_windows_widget_->Init(params); + no_windows_widget_->Init(std::move(params)); aura::Window* widget_window = no_windows_widget_->GetNativeWindow(); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); widget_window->parent()->StackChildAtBottom(widget_window); ScopedOverviewAnimationSettings settings(OVERVIEW_ANIMATION_NO_RECENTS_FADE, widget_window);
diff --git a/ash/wm/overview/rounded_label_widget.cc b/ash/wm/overview/rounded_label_widget.cc index f8b3f5b..5459d703 100644 --- a/ash/wm/overview/rounded_label_widget.cc +++ b/ash/wm/overview/rounded_label_widget.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "ash/public/cpp/window_properties.h" #include "ash/wm/overview/scoped_overview_animation_settings.h" #include "ui/aura/window.h" #include "ui/base/l10n/l10n_util.h" @@ -71,11 +72,13 @@ RoundedLabelWidget::InitParams::InitParams() = default; +RoundedLabelWidget::InitParams::InitParams(InitParams&& other) = default; + RoundedLabelWidget::RoundedLabelWidget() = default; RoundedLabelWidget::~RoundedLabelWidget() = default; -void RoundedLabelWidget::Init(const InitParams& params) { +void RoundedLabelWidget::Init(InitParams params) { views::Widget::InitParams widget_params; widget_params.name = params.name; widget_params.type = views::Widget::InitParams::TYPE_POPUP; @@ -86,7 +89,11 @@ widget_params.accept_events = false; widget_params.parent = params.parent; set_focus_on_creation(false); - views::Widget::Init(widget_params); + if (params.hide_in_mini_view) { + widget_params.init_properties_container.SetProperty(kHideInDeskMiniViewKey, + true); + } + views::Widget::Init(std::move(widget_params)); SetContentsView(new RoundedLabelView( params.horizontal_padding, params.vertical_padding,
diff --git a/ash/wm/overview/rounded_label_widget.h b/ash/wm/overview/rounded_label_widget.h index 958e5472..dcc7226 100644 --- a/ash/wm/overview/rounded_label_widget.h +++ b/ash/wm/overview/rounded_label_widget.h
@@ -21,6 +21,8 @@ // Params to modify the look of the label. struct InitParams { InitParams(); + InitParams(InitParams&& other); + std::string name; int horizontal_padding; int vertical_padding; @@ -30,12 +32,13 @@ int preferred_height; int message_id; aura::Window* parent; + bool hide_in_mini_view; }; RoundedLabelWidget(); ~RoundedLabelWidget() override; - void Init(const InitParams& params); + void Init(InitParams params); // Gets the preferred size of the widget centered in |bounds|. gfx::Rect GetBoundsCenteredIn(const gfx::Rect& bounds);
diff --git a/ash/wm/pip/pip_unittest.cc b/ash/wm/pip/pip_unittest.cc index 9dc7e7d..8eed660d 100644 --- a/ash/wm/pip/pip_unittest.cc +++ b/ash/wm/pip/pip_unittest.cc
@@ -37,7 +37,7 @@ params.delegate = new views::WidgetDelegateView(); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = context; - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ash/wm/pip/pip_window_resizer_unittest.cc b/ash/wm/pip/pip_window_resizer_unittest.cc index d1a04ab..3819193 100644 --- a/ash/wm/pip/pip_window_resizer_unittest.cc +++ b/ash/wm/pip/pip_window_resizer_unittest.cc
@@ -117,7 +117,7 @@ params.bounds = screen_bounds; params.z_order = ui::ZOrderLevel::kFloatingWindow; params.context = root_window; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ash/wm/splitview/split_view_controller_unittest.cc b/ash/wm/splitview/split_view_controller_unittest.cc index 32c978a..4e88482 100644 --- a/ash/wm/splitview/split_view_controller_unittest.cc +++ b/ash/wm/splitview/split_view_controller_unittest.cc
@@ -4187,7 +4187,7 @@ widget_delegate->set_widget(widget); params.delegate = widget_delegate.release(); params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return base::WrapUnique<aura::Window>(widget->GetNativeView()); }
diff --git a/ash/wm/splitview/split_view_divider.cc b/ash/wm/splitview/split_view_divider.cc index 7f2806c..121f0245 100644 --- a/ash/wm/splitview/split_view_divider.cc +++ b/ash/wm/splitview/split_view_divider.cc
@@ -443,11 +443,10 @@ params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; params.parent = Shell::GetContainer(root_window, kShellWindowId_AlwaysOnTopContainer); + params.init_properties_container.SetProperty(kHideInDeskMiniViewKey, true); DividerView* divider_view = new DividerView(this); divider_widget_->set_focus_on_creation(false); - divider_widget_->Init(params); - aura::Window* widget_window = divider_widget_->GetNativeWindow(); - widget_window->SetProperty(kHideInDeskMiniViewKey, true); + divider_widget_->Init(std::move(params)); divider_widget_->SetVisibilityAnimationTransition( views::Widget::ANIMATE_NONE); divider_widget_->SetContentsView(divider_view);
diff --git a/ash/wm/splitview/split_view_drag_indicators.cc b/ash/wm/splitview/split_view_drag_indicators.cc index 8f3b692..09166b6 100644 --- a/ash/wm/splitview/split_view_drag_indicators.cc +++ b/ash/wm/splitview/split_view_drag_indicators.cc
@@ -49,7 +49,7 @@ params.parent = Shell::GetContainer(Shell::Get()->GetPrimaryRootWindow(), kShellWindowId_OverlayContainer); widget->set_focus_on_creation(false); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc index 8963932..07f99bb 100644 --- a/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc +++ b/ash/wm/tablet_mode/tablet_mode_window_manager_unittest.cc
@@ -120,7 +120,7 @@ views::Widget* widget = new views::Widget(); views::Widget::InitParams params; params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); aura::Window* window = widget->GetNativeWindow(); window->SetBounds(bounds);
diff --git a/ash/wm/test_child_modal_parent.cc b/ash/wm/test_child_modal_parent.cc index c607d43..53d792d 100644 --- a/ash/wm/test_child_modal_parent.cc +++ b/ash/wm/test_child_modal_parent.cc
@@ -82,7 +82,7 @@ params.context = context; params.bounds = gfx::Rect(kWindowLeft, kWindowTop, kWindowWidth, kWindowHeight); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return test_child_modal_parent; } @@ -95,7 +95,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = context; - modal_parent_->Init(params); + modal_parent_->Init(std::move(params)); modal_parent_->GetRootView()->SetBackground( views::CreateSolidBackground(kModalParentColor)); auto* modal_parent_textfield = new views::Textfield;
diff --git a/ash/wm/window_cycle_list.cc b/ash/wm/window_cycle_list.cc index df3d36a..125148e 100644 --- a/ash/wm/window_cycle_list.cc +++ b/ash/wm/window_cycle_list.cc
@@ -570,7 +570,7 @@ (widget_rect.height() - widget_height) / 2); widget_rect.set_height(widget_height); params.bounds = widget_rect; - widget->Init(params); + widget->Init(std::move(params)); screen_observer_.Add(display::Screen::GetScreen()); widget->Show();
diff --git a/ash/wm/workspace/backdrop_controller.cc b/ash/wm/workspace/backdrop_controller.cc index b1fd944..94db4180 100644 --- a/ash/wm/workspace/backdrop_controller.cc +++ b/ash/wm/workspace/backdrop_controller.cc
@@ -322,7 +322,7 @@ params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; DCHECK_NE(kShellWindowId_Invalid, container_->id()); params.parent = container_; - backdrop_->Init(params); + backdrop_->Init(std::move(params)); backdrop_window_ = backdrop_->GetNativeWindow(); backdrop_window_->SetProperty(kHideInOverviewKey, true); // The backdrop window in always on top container can be reparented without
diff --git a/ash/wm/workspace/multi_window_resize_controller.cc b/ash/wm/workspace/multi_window_resize_controller.cc index e1162e743..c4672cb 100644 --- a/ash/wm/workspace/multi_window_resize_controller.cc +++ b/ash/wm/workspace/multi_window_resize_controller.cc
@@ -462,7 +462,7 @@ kShellWindowId_AlwaysOnTopContainer); ResizeView* view = new ResizeView(this, windows_.direction); resize_widget_->set_focus_on_creation(false); - resize_widget_->Init(params); + resize_widget_->Init(std::move(params)); ::wm::SetWindowVisibilityAnimationType( resize_widget_->GetNativeWindow(), ::wm::WINDOW_VISIBILITY_ANIMATION_TYPE_FADE);
diff --git a/ash/wm/workspace/multi_window_resize_controller_unittest.cc b/ash/wm/workspace/multi_window_resize_controller_unittest.cc index 3bdc949..efd20e2a 100644 --- a/ash/wm/workspace/multi_window_resize_controller_unittest.cc +++ b/ash/wm/workspace/multi_window_resize_controller_unittest.cc
@@ -142,7 +142,7 @@ params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params1.bounds = gfx::Rect(100, 200); params1.context = CurrentContext(); - w1->Init(params1); + w1->Init(std::move(params1)); w1->Show(); std::unique_ptr<views::Widget> w2(new views::Widget); @@ -151,7 +151,7 @@ params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params2.bounds = gfx::Rect(100, 0, 100, 100); params2.context = CurrentContext(); - w2->Init(params2); + w2->Init(std::move(params2)); w2->Show(); std::unique_ptr<views::Widget> w3(new views::Widget); @@ -160,7 +160,7 @@ params3.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params3.bounds = gfx::Rect(100, 100, 100, 100); params3.context = CurrentContext(); - w3->Init(params3); + w3->Init(std::move(params3)); w3->Show(); ui::test::EventGenerator* generator = GetEventGenerator();
diff --git a/ash/wm/workspace/phantom_window_controller.cc b/ash/wm/workspace/phantom_window_controller.cc index 6dda6f6..d1c17159 100644 --- a/ash/wm/workspace/phantom_window_controller.cc +++ b/ash/wm/workspace/phantom_window_controller.cc
@@ -81,7 +81,7 @@ params.shadow_elevation = ::wm::kShadowElevationActiveWindow; params.parent = root_window->GetChildById(kShellWindowId_ShelfContainer); phantom_widget->set_focus_on_creation(false); - phantom_widget->Init(params); + phantom_widget->Init(std::move(params)); phantom_widget->SetVisibilityChangedAnimationsEnabled(false); aura::Window* phantom_widget_window = phantom_widget->GetNativeWindow(); phantom_widget_window->set_id(kShellWindowId_PhantomWindow);
diff --git a/ash/wm/workspace/workspace_layout_manager_unittest.cc b/ash/wm/workspace/workspace_layout_manager_unittest.cc index d794336b..0cbd436 100644 --- a/ash/wm/workspace/workspace_layout_manager_unittest.cc +++ b/ash/wm/workspace/workspace_layout_manager_unittest.cc
@@ -293,7 +293,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = new MaximizeDelegateView(gfx::Rect(400, 0, 130, 40)); params.context = CurrentContext(); - w1->Init(params); + w1->Init(std::move(params)); EXPECT_EQ(root_windows[0], w1->GetNativeWindow()->GetRootWindow()); w1->Show(); EXPECT_TRUE(w1->IsMaximized());
diff --git a/base/BUILD.gn b/base/BUILD.gn index 4bc1db8..f757bba 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -3260,6 +3260,7 @@ "android/java/src/org/chromium/base/metrics/CachedMetrics.java", "android/java/src/org/chromium/base/metrics/RecordHistogram.java", "android/java/src/org/chromium/base/metrics/RecordUserAction.java", + "android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java", "android/java/src/org/chromium/base/metrics/StatisticsRecorderAndroid.java", "android/java/src/org/chromium/base/multidex/ChromiumMultiDexInstaller.java", "android/java/src/org/chromium/base/process_launcher/BindService.java",
diff --git a/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java b/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java new file mode 100644 index 0000000..a35a5dde --- /dev/null +++ b/base/android/java/src/org/chromium/base/metrics/ScopedSysTraceEvent.java
@@ -0,0 +1,42 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.base.metrics; + +import android.os.Trace; + +/** + * An alternative to @{TraceEvent} that allows us to trace events before native + * initialization. + * + * Note that TraceEvent / EarlyTraceEvent cannot be used before native initialization since + * it directly purges to the kernel debug message but that method does not allow tracing events + * to be written *after* the event occurrence. + */ +public class ScopedSysTraceEvent implements AutoCloseable { + /** + * Factory used to support the "try with resource" construct. + * Note that currently this is the only allowed pattern. However, this requires heap allocation + * so we may consider calling Trace.beginSection() / endSection() directly if it should be used + * repeatedly. + * + * @param name Trace event name. + * @return a {@ScopedSysTraceEvent}, or null if tracing is not enabled. + */ + public static ScopedSysTraceEvent scoped(String name) { + return new ScopedSysTraceEvent(name); + } + + /** + * Constructor used to support the "try with resource" construct. + */ + private ScopedSysTraceEvent(String name) { + Trace.beginSection(name); + } + + @Override + public void close() { + Trace.endSection(); + } +} \ No newline at end of file
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index 1d7bdd9..40889b6 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -1462,11 +1462,6 @@ for (const TestInfo& test_info : tests_) { std::string test_name = test_info.GetFullName(); - bool will_run_test = launcher_delegate_->WillRunTest( - test_info.test_case_name(), test_info.test_name()); - if (!will_run_test) - continue; - // Count tests in the binary, before we apply filter and sharding. test_found_count++;
diff --git a/base/test/launcher/test_launcher.h b/base/test/launcher/test_launcher.h index a884861..c6b0882 100644 --- a/base/test/launcher/test_launcher.h +++ b/base/test/launcher/test_launcher.h
@@ -49,11 +49,6 @@ // must put the result in |output| and return true on success. virtual bool GetTests(std::vector<TestIdentifier>* output) = 0; - // Called before a test is considered for running. This method must return - // true if either the delegate or the TestLauncher will run the test. - virtual bool WillRunTest(const std::string& test_case_name, - const std::string& test_name) = 0; - // Invoked after a child process finishes, reporting the process |exit_code|, // child process |elapsed_time|, whether or not the process was terminated as // a result of a timeout, and the output of the child (stdout and stderr
diff --git a/base/test/launcher/unit_test_launcher.cc b/base/test/launcher/unit_test_launcher.cc index da7675c..3e2f7d4 100644 --- a/base/test/launcher/unit_test_launcher.cc +++ b/base/test/launcher/unit_test_launcher.cc
@@ -462,14 +462,6 @@ return platform_delegate_->GetTests(output); } -bool UnitTestLauncherDelegate::WillRunTest(const std::string& test_case_name, - const std::string& test_name) { - DCHECK(thread_checker_.CalledOnValidThread()); - - // There is no additional logic to disable specific tests. - return true; -} - std::vector<TestResult> UnitTestLauncherDelegate::ProcessTestResults( const std::vector<std::string>& test_names, const base::FilePath& output_file,
diff --git a/base/test/launcher/unit_test_launcher.h b/base/test/launcher/unit_test_launcher.h index eb30fbf..2390fbf 100644 --- a/base/test/launcher/unit_test_launcher.h +++ b/base/test/launcher/unit_test_launcher.h
@@ -126,8 +126,6 @@ private: // TestLauncherDelegate: bool GetTests(std::vector<TestIdentifier>* output) override; - bool WillRunTest(const std::string& test_case_name, - const std::string& test_name) override; std::vector<TestResult> ProcessTestResults( const std::vector<std::string>& test_names,
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index f028f831..8b4192f0 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -3445,14 +3445,6 @@ # base module (optional). # base_module_target: Base module target of the bundle this module will be # added to (optional). Can only be specified for non-base modules. - # native_switches: Forwarded switches to decide how to assign native - # libraries and placeholders (optional). Its members are: - # * is_64_bit_browser - # * include_32_bit_webview - # loadable_modules_if_32_bit: Native libraries to use if the binary ABI is - # 32-bit (optional). - # loadable_modules_if_64_bit: Native libraries to use if the binary ABI is - # 64-bit (optional). template("android_app_bundle_module") { _is_base_module = defined(invoker.is_base_module) && invoker.is_base_module @@ -3504,10 +3496,12 @@ "jni_registration_header", "jni_sources_blacklist", "load_library_from_apk", + "loadable_modules", + "locale_config_java_packages", "manifest_package", "max_sdk_version", - "locale_config_java_packages", "min_sdk_version", + "native_lib_placeholders", "native_lib_version_arg", "native_lib_version_rule", "negative_main_dex_globs", @@ -3523,7 +3517,9 @@ "resource_blacklist_regex", "resource_ids_provider_dep", "resources_config_path", + "secondary_abi_loadable_modules", "secondary_abi_shared_libraries", + "secondary_native_lib_placeholders", "shared_libraries", "shared_resources", "shared_resources_whitelist_locales", @@ -3542,63 +3538,6 @@ "version_name", "write_asset_list", ]) - - # Specify native libraries and placeholders. - if (defined(invoker.native_switches)) { - _native_switches = invoker.native_switches - - assert(invoker.loadable_modules_if_32_bit != []) - assert(!_native_switches.is_64_bit_browser || - invoker.loadable_modules_if_64_bit != []) - - # Decision logic: Assign decision variables: - # loadable_modules_to_use: Either |loadable_modules_if_64_bit| or - # |loadable_modules_if_32_bit|. - # native_is_primary: Whether |loadable_modules_to_use| should be - # assigned as primary ABI or secondary ABI. - # native_need_placeholder: Whether a placeholder is needed for the - # complementary ABI to the library. - if (_native_switches.is_64_bit_browser) { - _loadable_modules_to_use = invoker.loadable_modules_if_64_bit - _native_is_primary = - !build_apk_secondary_abi || android_64bit_target_cpu - _native_need_placeholder = - build_apk_secondary_abi && _native_switches.include_32_bit_webview - } else { - if (defined(invoker.loadable_modules_if_64_bit)) { - not_needed(invoker, [ "loadable_modules_if_64_bit" ]) - } - _loadable_modules_to_use = invoker.loadable_modules_if_32_bit - _native_is_primary = - !build_apk_secondary_abi || !android_64bit_target_cpu - _native_need_placeholder = - build_apk_secondary_abi && android_64bit_target_cpu - } - - # Realization logic: Assign libraries and placeholders. - if (_native_is_primary) { - loadable_modules = _loadable_modules_to_use - if (_native_need_placeholder) { - secondary_native_lib_placeholders = [ "libdummy.so" ] - } - } else { - secondary_abi_loadable_modules = _loadable_modules_to_use - if (_native_need_placeholder) { - native_lib_placeholders = [ "libdummy.so" ] - } - } - } else { - assert(!defined(invoker.loadable_modules_if_32_bit)) - assert(!defined(invoker.loadable_modules_if_64_bit)) - forward_variables_from(invoker, - [ - "loadable_modules", - "native_lib_placeholders", - "secondary_abi_loadable_modules", - "secondary_native_lib_placeholders", - ]) - } - is_bundle_module = true generate_buildconfig_java = _is_base_module no_build_hooks = !_is_base_module
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 3077bb1e..1c685a7 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -8906336835909683200 \ No newline at end of file +8906307421479005200 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 50c35d1..df25e79c 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -8906340129486711056 \ No newline at end of file +8906307426525263280 \ No newline at end of file
diff --git a/cc/paint/image_transfer_cache_entry.cc b/cc/paint/image_transfer_cache_entry.cc index 964f532..da4c2d6 100644 --- a/cc/paint/image_transfer_cache_entry.cc +++ b/cc/paint/image_transfer_cache_entry.cc
@@ -376,14 +376,14 @@ PaintOp::DeserializeOptions options(nullptr, nullptr, nullptr, &scratch_buffer); PaintOpReader reader(data.data(), data.size(), options); - uint32_t image_is_yuv; + uint32_t image_is_yuv = 0; reader.Read(&image_is_yuv); if (!!image_is_yuv) { - uint32_t num_planes; + uint32_t num_planes = 0; reader.Read(&num_planes); - // YUV or YUVA + // TODO(crbug.com/910276): Allow for four planes if YUVA. // TODO(crbug.com/986575): consider serializing a YUVDecodeFormat. - if (num_planes != 3u && num_planes != 4u) + if (num_planes != 3u) return false; plane_images_format_ = num_planes == 3u ? YUVDecodeFormat::kYUV3 : YUVDecodeFormat::kYUVA4; @@ -400,9 +400,9 @@ auto gr_mips = has_mips_ ? GrMipMapped::kYes : GrMipMapped::kNo; // Read in each plane and reconstruct pixmaps. for (uint32_t i = 0; i < num_planes; i++) { - uint32_t plane_width; + uint32_t plane_width = 0; reader.Read(&plane_width); - uint32_t plane_height; + uint32_t plane_height = 0; reader.Read(&plane_height); // Because Skia does not support YUV rasterization from software planes, // we require that each pixmap fits in a GPU texture. In the @@ -412,7 +412,7 @@ // We compute this for each plane in case a malicious renderer tries to // send very large U or V planes. fits_on_gpu_ = plane_width <= max_size && plane_height <= max_size; - if (!fits_on_gpu_) + if (!fits_on_gpu_ || plane_width == 0 || plane_height == 0) return false; size_t plane_bytes;
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 9645811..e5868d0 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -2370,7 +2370,6 @@ "java/src/org/chromium/chrome/browser/SearchGeolocationDisclosureTabHelper.java", "java/src/org/chromium/chrome/browser/ServiceTabLauncher.java", "java/src/org/chromium/chrome/browser/ShortcutHelper.java", - "java/src/org/chromium/chrome/browser/SmsReceiverDialog.java", "java/src/org/chromium/chrome/browser/WarmupManager.java", "java/src/org/chromium/chrome/browser/WebContentsFactory.java", "java/src/org/chromium/chrome/browser/accessibility/FontSizePrefs.java", @@ -2601,6 +2600,7 @@ "java/src/org/chromium/chrome/browser/signin/SigninPromoUtil.java", "java/src/org/chromium/chrome/browser/signin/SigninUtils.java", "java/src/org/chromium/chrome/browser/signin/UnifiedConsentServiceBridge.java", + "java/src/org/chromium/chrome/browser/sms/SmsReceiverDialog.java", "java/src/org/chromium/chrome/browser/snackbar/smartlockautosignin/AutoSigninSnackbarController.java", "java/src/org/chromium/chrome/browser/ssl/CaptivePortalHelper.java", "java/src/org/chromium/chrome/browser/ssl/SecurityStateModel.java",
diff --git a/chrome/android/chrome_java_sources.gni b/chrome/android/chrome_java_sources.gni index acf75b0..bca0a06 100644 --- a/chrome/android/chrome_java_sources.gni +++ b/chrome/android/chrome_java_sources.gni
@@ -56,7 +56,6 @@ "java/src/org/chromium/chrome/browser/ServiceTabLauncher.java", "java/src/org/chromium/chrome/browser/ShortcutHelper.java", "java/src/org/chromium/chrome/browser/SingleTabActivity.java", - "java/src/org/chromium/chrome/browser/SmsReceiverDialog.java", "java/src/org/chromium/chrome/browser/SnackbarActivity.java", "java/src/org/chromium/chrome/browser/SwipeRefreshHandler.java", "java/src/org/chromium/chrome/browser/SynchronousInitializationActivity.java", @@ -1431,6 +1430,7 @@ "java/src/org/chromium/chrome/browser/signin/SigninView.java", "java/src/org/chromium/chrome/browser/signin/SyncPromoView.java", "java/src/org/chromium/chrome/browser/signin/UnifiedConsentServiceBridge.java", + "java/src/org/chromium/chrome/browser/sms/SmsReceiverDialog.java", "java/src/org/chromium/chrome/browser/snackbar/BottomContainer.java", "java/src/org/chromium/chrome/browser/snackbar/Snackbar.java", "java/src/org/chromium/chrome/browser/snackbar/SnackbarCollection.java",
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index f51954cba..1c5a57d 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -36,7 +36,6 @@ "javatests/src/org/chromium/chrome/browser/ServicificationBackgroundServiceTest.java", "javatests/src/org/chromium/chrome/browser/ShareIntentTest.java", "javatests/src/org/chromium/chrome/browser/SmartClipProviderTest.java", - "javatests/src/org/chromium/chrome/browser/SmsReceiverDialogTest.java", "javatests/src/org/chromium/chrome/browser/SubresourceFilterTest.java", "javatests/src/org/chromium/chrome/browser/TabCountLabelTest.java", "javatests/src/org/chromium/chrome/browser/TabObserverTest.java", @@ -427,6 +426,7 @@ "javatests/src/org/chromium/chrome/browser/signin/ProfileDataCacheRenderTest.java", "javatests/src/org/chromium/chrome/browser/signin/SigninHelperTest.java", "javatests/src/org/chromium/chrome/browser/signin/SigninTest.java", + "javatests/src/org/chromium/chrome/browser/sms/SmsReceiverDialogTest.java", "javatests/src/org/chromium/chrome/browser/snackbar/SnackbarTest.java", "javatests/src/org/chromium/chrome/browser/snackbar/undo/UndoBarControllerTest.java", "javatests/src/org/chromium/chrome/browser/ssl/CaptivePortalTest.java",
diff --git a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceLayoutTest.java b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceLayoutTest.java index b9ef0ebd..55e2cb2a 100644 --- a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceLayoutTest.java +++ b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/StartSurfaceLayoutTest.java
@@ -42,6 +42,7 @@ import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.content.TabContentManager; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tabmodel.TabSelectionType; import org.chromium.chrome.browser.tasks.tab_management.GridTabSwitcher; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -191,6 +192,7 @@ /** * Make Chrome have {@code numTabs} or Tabs with {@code url} loaded. + * @param numTabs The number of tabs we expect after finishing * @param url The URL to load. Skip loading when null, but the thumbnail for the NTP might not * be saved. */ @@ -209,14 +211,43 @@ .getCurrentModel() .getTabAt(i); - // TODO(wychen): missing thumbnail should not happen in web tabs, either, but checking - // it makes the tests too flaky. - if (previousTab.isNativePage()) checkThumbnailsExist(previousTab); + boolean fixPendingReadbacks = mActivityTestRule.getActivity() + .getTabContentManager() + .getPendingReadbacksForTesting() + != 0; + + // When there are pending readbacks due to detached Tabs, try to fix it by switching + // back to that tab. + if (fixPendingReadbacks) { + int lastIndex = i; + // clang-format off + TestThreadUtils.runOnUiThreadBlocking(() -> + mActivityTestRule.getActivity().getCurrentTabModel().setIndex( + lastIndex, TabSelectionType.FROM_USER) + ); + // clang-format on + } + checkThumbnailsExist(previousTab); + if (fixPendingReadbacks) { + int currentIndex = i + 1; + // clang-format off + TestThreadUtils.runOnUiThreadBlocking(() -> + mActivityTestRule.getActivity().getCurrentTabModel().setIndex( + currentIndex, TabSelectionType.FROM_USER) + ); + // clang-format on + } } ChromeTabUtils.waitForTabPageLoaded(mActivityTestRule.getActivity().getActivityTab(), null, null, WAIT_TIMEOUT_SECONDS * 10); assertEquals( numTabs, mActivityTestRule.getActivity().getTabModelSelector().getTotalTabCount()); + + // clang-format off + CriteriaHelper.pollUiThread(Criteria.equals(0, () -> + mActivityTestRule.getActivity().getTabContentManager().getPendingReadbacksForTesting() + )); + // clang-format on } private void testTabToGrid(String fromUrl) throws InterruptedException {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java index ed5d0967..2727ecc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/content/TabContentManager.java
@@ -489,6 +489,11 @@ nativeSetCaptureMinRequestTimeForTesting(mNativeTabContentManager, timeMs); } + @VisibleForTesting + public int getPendingReadbacksForTesting() { + return nativeGetPendingReadbacksForTesting(mNativeTabContentManager); + } + @CalledByNative protected void notifyListenersOfThumbnailChange(int tabId) { for (ThumbnailChangeListener listener : mListeners) { @@ -520,5 +525,6 @@ long nativeTabContentManager, int tabId, Callback<Bitmap> callback); private native void nativeSetCaptureMinRequestTimeForTesting( long nativeTabContentManager, int timeMs); + private native int nativeGetPendingReadbacksForTesting(long nativeTabContentManager); private static native void nativeDestroy(long nativeTabContentManager); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java index 6fcc079e..774ce8fc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/ChromeContextMenuItem.java
@@ -142,7 +142,7 @@ * @param item #Item Item ID. * @return Returns the string that describes the action of the item. */ - private static @StringRes int getStringID(@Item int item) { + private static @StringRes int getStringId(@Item int item) { assert STRING_IDS.length == Item.NUM_ENTRIES; if (FeatureUtilities.isTabGroupsAndroidEnabled() && item == Item.OPEN_IN_NEW_TAB) { @@ -164,19 +164,19 @@ case Item.OPEN_IN_BROWSER_ID: return DefaultBrowserInfo.getTitleOpenInDefaultBrowser(false); case Item.SEARCH_BY_IMAGE: - return context.getString(getStringID(mItem), + return context.getString(getStringId(mItem), TemplateUrlServiceFactory.get() .getDefaultSearchEngineTemplateUrl() .getShortName()); case Item.OPEN_IN_EPHEMERAL_TAB: case Item.OPEN_IMAGE_IN_EPHEMERAL_TAB: - return SpanApplier.applySpans(context.getString(getStringID(mItem)), + return SpanApplier.applySpans(context.getString(getStringId(mItem)), new SpanInfo("<new>", "</new>", new SuperscriptSpan(), new RelativeSizeSpan(0.75f), new ForegroundColorSpan(ApiCompatibilityUtils.getColor( context.getResources(), R.color.default_text_color_blue)))); default: - return context.getString(getStringID(mItem)); + return context.getString(getStringId(mItem)); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinator.java index b0bfe74..bf62c0e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinator.java
@@ -19,12 +19,13 @@ import org.chromium.chrome.browser.share.ShareHelper; import org.chromium.chrome.browser.share.ShareParams; import org.chromium.chrome.browser.widget.ContextMenuDialog; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.ModelListAdapter; import org.chromium.ui.modelutil.PropertyModel; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import java.util.ArrayList; import java.util.List; /** @@ -80,7 +81,10 @@ mHeaderCoordinator = new RevampedContextMenuHeaderCoordinator(activity, params); - ModelListAdapter adapter = new ModelListAdapter() { + // The Integer here specifies the {@link ListItemType}. + ModelList listItems = getItemList(activity, items, params); + + ModelListAdapter adapter = new ModelListAdapter(listItems) { @Override public boolean areAllItemsEnabled() { return false; @@ -96,8 +100,8 @@ public long getItemId(int position) { if (getItemViewType(position) == ListItemType.CONTEXT_MENU_ITEM || getItemViewType(position) == ListItemType.CONTEXT_MENU_SHARE_ITEM) { - return ((Pair<Integer, PropertyModel>) getItem(position)) - .second.get(RevampedContextMenuItemProperties.MENU_ID); + return ((ListItem) getItem(position)) + .model.get(RevampedContextMenuItemProperties.MENU_ID); } return INVALID_ITEM_ID; } @@ -129,10 +133,6 @@ RevampedContextMenuShareItemViewBinder::bind); // clang-format on - // The Integer here specifies the {@link ListItemType}. - List<Pair<Integer, PropertyModel>> itemList = getItemList(activity, items, params); - - adapter.updateModels(itemList); mListView.setOnItemClickListener((p, v, pos, id) -> { assert id != INVALID_ITEM_ID; @@ -166,17 +166,17 @@ } @VisibleForTesting - List<Pair<Integer, PropertyModel>> getItemList(Activity activity, - List<Pair<Integer, List<ContextMenuItem>>> items, ContextMenuParams params) { - List<Pair<Integer, PropertyModel>> itemList = new ArrayList<>(); + ModelList getItemList(Activity activity, List<Pair<Integer, List<ContextMenuItem>>> items, + ContextMenuParams params) { + ModelList itemList = new ModelList(); // TODO(sinansahin): We should be able to remove this conversion once we can get the items // in the desired format. - itemList.add(new Pair<>(ListItemType.HEADER, mHeaderCoordinator.getModel())); + itemList.add(new ListItem(ListItemType.HEADER, mHeaderCoordinator.getModel())); for (Pair<Integer, List<ContextMenuItem>> group : items) { // Add a divider - itemList.add(new Pair<>(ListItemType.DIVIDER, new PropertyModel())); + itemList.add(new ListItem(ListItemType.DIVIDER, new PropertyModel())); for (ContextMenuItem item : group.second) { PropertyModel itemModel; @@ -197,7 +197,7 @@ .with(RevampedContextMenuShareItemProperties.CLICK_LISTENER, getShareItemClickListener(activity, shareItem, params)) .build(); - itemList.add(new Pair<>(ListItemType.CONTEXT_MENU_SHARE_ITEM, itemModel)); + itemList.add(new ListItem(ListItemType.CONTEXT_MENU_SHARE_ITEM, itemModel)); } else { itemModel = new PropertyModel.Builder(RevampedContextMenuItemProperties.ALL_KEYS) @@ -206,7 +206,7 @@ .with(RevampedContextMenuItemProperties.TEXT, item.getTitle(activity)) .build(); - itemList.add(new Pair<>(ListItemType.CONTEXT_MENU_ITEM, itemModel)); + itemList.add(new ListItem(ListItemType.CONTEXT_MENU_ITEM, itemModel)); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java index 5dfc8a88..5f2b0a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadManagerService.java
@@ -39,6 +39,7 @@ import org.chromium.chrome.browser.download.DownloadMetrics.DownloadOpenSource; import org.chromium.chrome.browser.download.DownloadNotificationUmaHelper.UmaBackgroundDownload; import org.chromium.chrome.browser.download.DownloadNotificationUmaHelper.UmaDownloadResumption; +import org.chromium.chrome.browser.download.items.OfflineContentAggregatorFactory; import org.chromium.chrome.browser.download.ui.BackendProvider; import org.chromium.chrome.browser.externalnav.ExternalNavigationDelegateImpl; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; @@ -54,7 +55,11 @@ import org.chromium.components.offline_items_collection.ContentId; import org.chromium.components.offline_items_collection.FailState; import org.chromium.components.offline_items_collection.LegacyHelpers; +import org.chromium.components.offline_items_collection.OfflineContentProvider; +import org.chromium.components.offline_items_collection.OfflineItem; +import org.chromium.components.offline_items_collection.OfflineItemState; import org.chromium.components.offline_items_collection.PendingState; +import org.chromium.components.offline_items_collection.UpdateDelta; import org.chromium.content_public.browser.BrowserStartupController; import org.chromium.net.ConnectionType; import org.chromium.net.NetworkChangeNotifierAutoDetect; @@ -226,6 +231,44 @@ } } + private class BackgroundDownloadUmaRecorder implements OfflineContentProvider.Observer { + BackgroundDownloadUmaRecorder() { + OfflineContentAggregatorFactory.get().addObserver(this); + } + + @Override + public void onItemUpdated(OfflineItem item, UpdateDelta updateDelta) { + if (!LegacyHelpers.isLegacyDownload(item.id)) return; + switch (item.state) { + case OfflineItemState.COMPLETE: + maybeRecordBackgroundDownload(UmaBackgroundDownload.COMPLETED, item.id.id); + break; + case OfflineItemState.CANCELLED: + maybeRecordBackgroundDownload(UmaBackgroundDownload.CANCELLED, item.id.id); + break; + case OfflineItemState.INTERRUPTED: + maybeRecordBackgroundDownload(UmaBackgroundDownload.INTERRUPTED, item.id.id); + break; + case OfflineItemState.FAILED: + maybeRecordBackgroundDownload(UmaBackgroundDownload.FAILED, item.id.id); + break; + case OfflineItemState.PENDING: + case OfflineItemState.PAUSED: + case OfflineItemState.IN_PROGRESS: + default: + break; + } + } + + @Override + public void onItemsAdded(ArrayList<OfflineItem> items) {} + + @Override + public void onItemRemoved(ContentId id) {} + } + + private BackgroundDownloadUmaRecorder mBackgroundDownloadUmaRecorder; + /** * Creates DownloadManagerService. */ @@ -1978,6 +2021,9 @@ nativeRecordFirstBackgroundInterruptReason(getNativeDownloadManagerService(), mFirstBackgroundDownloadId, true /* downloadStarted */); } + if (ChromeFeatureList.isEnabled(ChromeFeatureList.DOWNLOAD_OFFLINE_CONTENT_PROVIDER)) { + mBackgroundDownloadUmaRecorder = new BackgroundDownloadUmaRecorder(); + } } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java b/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java index 0cbef9b..5a3376f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/service/DownloadBackgroundTask.java
@@ -37,9 +37,11 @@ int optimalBatteryPercentage = taskParameters.getExtras().getInt( DownloadTaskScheduler.EXTRA_OPTIMAL_BATTERY_PERCENTAGE); mCurrentTaskType = taskParameters.getExtras().getInt(DownloadTaskScheduler.EXTRA_TASK_TYPE); - // Return value from FeatureUtilities.shouldStartServiceManagerOnly() could change during - // native initialization, store it first. - mStartsServiceManagerOnly = FeatureUtilities.isServiceManagerForBackgroundPrefetchEnabled(); + // The feature value could change during native initialization, store it first. + mStartsServiceManagerOnly = + (mCurrentTaskType == DownloadTaskType.DOWNLOAD_AUTO_RESUMPTION_TASK) + ? FeatureUtilities.isServiceManagerForDownloadResumptionEnabled() + : FeatureUtilities.isServiceManagerForBackgroundPrefetchEnabled(); // Reschedule if minimum battery level is not satisfied. if (!requiresCharging && BatteryStatusListenerAndroid.getBatteryPercentage() < optimalBatteryPercentage) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java index 75cf12c..b0683eb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesIPH.java
@@ -5,11 +5,13 @@ package org.chromium.chrome.browser.explore_sites; import android.content.Context; +import android.graphics.Rect; import android.view.View; import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.widget.PulseDrawable; import org.chromium.chrome.browser.widget.ViewHighlighter; import org.chromium.chrome.browser.widget.textbubble.TextBubble; import org.chromium.chrome.browser.widget.tile.TileView; @@ -63,7 +65,23 @@ accessibilityString, true, rectProvider); textBubble.setDismissOnTouchInteraction(true); View foregroundView = tileView.findViewById(org.chromium.chrome.R.id.tile_view_highlight); - ViewHighlighter.turnOnHighlight(foregroundView, true); + if (foregroundView == null) return; + + PulseDrawable pulseDrawable = PulseDrawable.createCustomCircle( + foregroundView.getContext(), new PulseDrawable.Bounds() { + @Override + public float getMaxRadiusPx(Rect bounds) { + return Math.min(bounds.width(), bounds.height()) / 2.f; + } + @Override + public float getMinRadiusPx(Rect bounds) { + // Radius is half of the min of width and height, divided by 1.5. + // This simplifies to min of width and height divided by 3. + return Math.min(bounds.width(), bounds.height()) / 3.f; + } + }); + ViewHighlighter.attachViewAsHighlight(foregroundView, pulseDrawable); + textBubble.addOnDismissListener(() -> { ViewHighlighter.turnOffHighlight(foregroundView);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/AdsBlockedInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/AdsBlockedInfoBar.java index 472089b..b7f8ee3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/AdsBlockedInfoBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/AdsBlockedInfoBar.java
@@ -19,14 +19,15 @@ import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.DialogListItemProperties; +import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ListItemType; import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.text.NoUnderlineClickableSpan; import org.chromium.ui.widget.ButtonCompat; -import java.util.ArrayList; - /** * This infobar appears when ads are being blocked on the page. This occurs after proceeding through * an interstitial warning that the site shows deceptive content, or when the site is known to show @@ -138,17 +139,18 @@ model.set(ModalDialogProperties.TITLE, res.getString(R.string.blocked_ads_prompt_title)); model.set(ModalDialogProperties.MESSAGE, res.getString(R.string.intrusive_ads_information)); - ArrayList<PropertyModel> options = new ArrayList<>(); - options.add(new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) - .with(DialogListItemProperties.TEXT, res.getString(R.string.learn_more)) - .with(DialogListItemProperties.CLICK_LISTENER, (v) -> onLinkClicked()) - .with(DialogListItemProperties.ICON, - ApiCompatibilityUtils.getDrawable( - res, R.drawable.ic_info_outline_grey)) - .build()); + ModelList listItems = new ModelList(); + listItems.add(new ListItem(ListItemType.DEFAULT, + new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) + .with(DialogListItemProperties.TEXT, res.getString(R.string.learn_more)) + .with(DialogListItemProperties.CLICK_LISTENER, (v) -> onLinkClicked()) + .with(DialogListItemProperties.ICON, + ApiCompatibilityUtils.getDrawable( + res, R.drawable.ic_info_outline_grey)) + .build())); // TODO(973601): We should have a better string for "always allow"; at least one that is // specific to this feature. - options.add( + listItems.add(new ListItem(ListItemType.DEFAULT, new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) .with(DialogListItemProperties.TEXT, res.getString(R.string.always_allow_redirects)) @@ -159,11 +161,9 @@ }) .with(DialogListItemProperties.ICON, ApiCompatibilityUtils.getDrawable(res, R.drawable.ic_check_circle)) - .build()); + .build())); - PropertyModel[] optionModels = new PropertyModel[options.size()]; - options.toArray(optionModels); - model.set(TouchlessDialogProperties.LIST_MODELS, optionModels); + model.set(TouchlessDialogProperties.LIST_MODELS, listItems); // The alt action matches cancel but with a different name. model.get(TouchlessDialogProperties.ACTION_NAMES).alt = R.string.ok;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/ConfirmInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/ConfirmInfoBar.java index d0fc6d1..b8bd384e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/ConfirmInfoBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/ConfirmInfoBar.java
@@ -14,10 +14,11 @@ import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.DialogListItemProperties; +import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ListItemType; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; -import java.util.ArrayList; - /** * An infobar that presents the user with several buttons. * @@ -80,9 +81,9 @@ public PropertyModel createModel() { PropertyModel model = super.createModel(); - ArrayList<PropertyModel> options = new ArrayList<>(); + ModelList options = new ModelList(); if (!TextUtils.isEmpty(mPrimaryButtonText)) { - options.add( + options.add(new ListItem(ListItemType.DEFAULT, new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) .with(DialogListItemProperties.TEXT, mPrimaryButtonText) .with(DialogListItemProperties.CLICK_LISTENER, @@ -90,11 +91,11 @@ .with(DialogListItemProperties.ICON, ApiCompatibilityUtils.getDrawable(getContext().getResources(), R.drawable.ic_check_circle)) - .build()); + .build())); } if (!TextUtils.isEmpty(mSecondaryButtonText)) { - options.add( + options.add(new ListItem(ListItemType.DEFAULT, new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) .with(DialogListItemProperties.TEXT, mSecondaryButtonText) .with(DialogListItemProperties.CLICK_LISTENER, @@ -102,12 +103,10 @@ .with(DialogListItemProperties.ICON, ApiCompatibilityUtils.getDrawable(getContext().getResources(), R.drawable.ic_cancel_circle)) - .build()); + .build())); } - PropertyModel[] optionModels = new PropertyModel[options.size()]; - options.toArray(optionModels); - model.set(TouchlessDialogProperties.LIST_MODELS, optionModels); + model.set(TouchlessDialogProperties.LIST_MODELS, options); return model; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java index 77978656..39393a2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.media; +import android.annotation.SuppressLint; +import android.app.ActivityManager; import android.content.Context; import android.content.Intent; @@ -11,6 +13,10 @@ import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.NativeMethods; import org.chromium.chrome.browser.init.AsyncInitializationActivity; +import org.chromium.chrome.browser.tab.EmptyTabObserver; +import org.chromium.chrome.browser.tab.Tab; +import org.chromium.ui.base.ActivityWindowAndroid; +import org.chromium.ui.base.WindowAndroid; /** * A picture in picture activity which get created when requesting @@ -19,6 +25,41 @@ */ public class PictureInPictureActivity extends AsyncInitializationActivity { private static long sNativeOverlayWindowAndroid; + private static Tab sInitiatorTab; + private static int sInitiatorTabTaskID; + private static InitiatorTabObserver sTabObserver; + + private static class InitiatorTabObserver extends EmptyTabObserver { + private enum Status { OK, DESTROYED } + private PictureInPictureActivity mActivity; + private Status mStatus; + + InitiatorTabObserver() { + mStatus = Status.OK; + } + + public void setActivity(PictureInPictureActivity activity) { + mActivity = activity; + } + + public Status getStatus() { + return mStatus; + } + + @Override + public void onDestroyed(Tab tab) { + if (tab.isClosing() || !isInitiatorTabAlive()) { + mStatus = Status.DESTROYED; + if (mActivity != null) mActivity.finish(); + } + } + + @Override + public void onCrash(Tab tab) { + mStatus = Status.DESTROYED; + if (mActivity != null) mActivity.finish(); + } + } @Override protected void triggerLayoutInflation() { @@ -35,41 +76,66 @@ super.onStart(); enterPictureInPictureMode(); - // Finish the activity if OverlayWindowAndroid has already been destroyed. - if (sNativeOverlayWindowAndroid == 0) { + // Finish the activity if OverlayWindowAndroid has already been destroyed + // or InitiatorTab has been destroyed by user or crashed. + if (sNativeOverlayWindowAndroid == 0 + || sTabObserver.getStatus() == InitiatorTabObserver.Status.DESTROYED) { this.finish(); return; } - PictureInPictureActivityJni.get().onActivityStart(sNativeOverlayWindowAndroid, this); + sTabObserver.setActivity(this); + + PictureInPictureActivityJni.get().onActivityStart( + sNativeOverlayWindowAndroid, this, getWindowAndroid()); } @Override public void onDestroy() { super.onDestroy(); - - if (sNativeOverlayWindowAndroid == 0) return; - - PictureInPictureActivityJni.get().onActivityDestroy(sNativeOverlayWindowAndroid); sNativeOverlayWindowAndroid = 0; + sInitiatorTab.removeObserver(sTabObserver); + sInitiatorTab = null; + sTabObserver = null; + } + + @Override + protected ActivityWindowAndroid createWindowAndroid() { + return new ActivityWindowAndroid(this); + } + + @SuppressLint("NewApi") + private static boolean isInitiatorTabAlive() { + ActivityManager activityManager = + (ActivityManager) ContextUtils.getApplicationContext().getSystemService( + Context.ACTIVITY_SERVICE); + for (ActivityManager.AppTask appTask : activityManager.getAppTasks()) { + if (appTask.getTaskInfo().id == sInitiatorTabTaskID) return true; + } + + return false; } @CalledByNative private void close() { - sNativeOverlayWindowAndroid = 0; this.finish(); } @CalledByNative - private static void createActivity(long nativeOverlayWindowAndroid) { + private static void createActivity(long nativeOverlayWindowAndroid, Object initiatorTab) { Context context = ContextUtils.getApplicationContext(); Intent intent = new Intent(context, PictureInPictureActivity.class); // Dissociate OverlayWindowAndroid if there is one already. if (sNativeOverlayWindowAndroid != 0) - PictureInPictureActivityJni.get().onActivityDestroy(sNativeOverlayWindowAndroid); + PictureInPictureActivityJni.get().destroy(sNativeOverlayWindowAndroid); sNativeOverlayWindowAndroid = nativeOverlayWindowAndroid; + sInitiatorTab = (Tab) initiatorTab; + sInitiatorTabTaskID = sInitiatorTab.getActivity().getTaskId(); + + sTabObserver = new InitiatorTabObserver(); + sInitiatorTab.addObserver(sTabObserver); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); @@ -84,8 +150,9 @@ @NativeMethods interface Natives { - void onActivityStart(long nativeOverlayWindowAndroid, PictureInPictureActivity self); + void onActivityStart(long nativeOverlayWindowAndroid, PictureInPictureActivity self, + WindowAndroid window); - void onActivityDestroy(long nativeOverlayWindowAndroid); + void destroy(long nativeOverlayWindowAndroid); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteCoordinatorImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteCoordinatorImpl.java index e9848f2..338f720f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteCoordinatorImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteCoordinatorImpl.java
@@ -37,6 +37,7 @@ import org.chromium.ui.ViewProvider; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modelutil.LazyConstructionPropertyMcp; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.ModelListAdapter; import org.chromium.ui.modelutil.PropertyModel; @@ -68,7 +69,10 @@ listModel.set(SuggestionListProperties.EMBEDDER, listEmbedder); listModel.set(SuggestionListProperties.VISIBLE, false); - ViewProvider<SuggestionListViewHolder> viewProvider = createViewProvider(context); + ModelList listItems = new ModelList(); + listModel.set(SuggestionListProperties.SUGGESTION_MODELS, listItems); + ViewProvider<SuggestionListViewHolder> viewProvider = + createViewProvider(context, listItems); viewProvider.whenLoaded((holder) -> { mListView = holder.listView; }); LazyConstructionPropertyMcp.create(listModel, SuggestionListProperties.VISIBLE, viewProvider, SuggestionListViewBinder::bind); @@ -83,7 +87,8 @@ mMediator = null; } - private ViewProvider<SuggestionListViewHolder> createViewProvider(Context context) { + private ViewProvider<SuggestionListViewHolder> createViewProvider( + Context context, ModelList modelList) { return new ViewProvider<SuggestionListViewHolder>() { private List<Callback<SuggestionListViewHolder>> mCallbacks = new ArrayList<>(); private SuggestionListViewHolder mHolder; @@ -101,7 +106,7 @@ // Start with visibility GONE to ensure that show() is called. // http://crbug.com/517438 list.setVisibility(View.GONE); - ModelListAdapter adapter = new ModelListAdapter(); + ModelListAdapter adapter = new ModelListAdapter(modelList); list.setAdapter(adapter); list.setClipToPadding(false); @@ -131,7 +136,7 @@ EntitySuggestionViewBinder::bind); // clang-format on - mHolder = new SuggestionListViewHolder(container, list, adapter); + mHolder = new SuggestionListViewHolder(container, list); for (int i = 0; i < mCallbacks.size(); i++) { mCallbacks.get(i).onResult(mHolder);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java index 7e69594..a5098bd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java
@@ -12,7 +12,6 @@ import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.text.TextUtils; -import android.util.Pair; import android.view.View; import android.widget.TextView; @@ -48,6 +47,8 @@ import org.chromium.ui.modaldialog.DialogDismissalCause; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; import java.lang.annotation.Retention; @@ -231,12 +232,12 @@ @Override public void notifyPropertyModelsChanged() { if (mPreventSuggestionListPropertyChanges) return; - List<Pair<Integer, PropertyModel>> models = new ArrayList<>(mCurrentModels.size()); + ModelList suggestions = mListPropertyModel.get(SuggestionListProperties.SUGGESTION_MODELS); + suggestions.clear(); for (int i = 0; i < mCurrentModels.size(); i++) { PropertyModel model = mCurrentModels.get(i).model; - models.add(new Pair<>(mCurrentModels.get(i).processor.getViewTypeId(), model)); + suggestions.add(new ListItem(mCurrentModels.get(i).processor.getViewTypeId(), model)); } - mListPropertyModel.set(SuggestionListProperties.SUGGESTION_MODELS, models); } @Override @@ -244,7 +245,7 @@ return mDataProvider != null ? mDataProvider.getProfile() : null; } - /** + /**m * Sets the data provider for the toolbar. */ void setToolbarDataProvider(ToolbarDataProvider provider) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListProperties.java index 56530801..3df6431 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListProperties.java
@@ -4,15 +4,11 @@ package org.chromium.chrome.browser.omnibox.suggestions; -import android.util.Pair; - +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyKey; -import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModel.WritableBooleanPropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableObjectPropertyKey; -import java.util.List; - /** * The properties controlling the state of the list of suggestion items. */ @@ -24,9 +20,12 @@ public static final WritableObjectPropertyKey<OmniboxSuggestionListEmbedder> EMBEDDER = new WritableObjectPropertyKey<>(); - /** The list of models controlling the state of the suggestion items. */ - public static final WritableObjectPropertyKey<List<Pair<Integer, PropertyModel>>> - SUGGESTION_MODELS = new WritableObjectPropertyKey<>(true); + /** + * The list of models controlling the state of the suggestion items. This should never be + * bound to the same view more than once. + */ + public static final WritableObjectPropertyKey<ModelList> SUGGESTION_MODELS = + new WritableObjectPropertyKey<>(true); /** Whether the suggestion list should have a dark background. */ public static final WritableBooleanPropertyKey IS_INCOGNITO = new WritableBooleanPropertyKey();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListViewBinder.java index 7fa3738..6cb02f8b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/SuggestionListViewBinder.java
@@ -4,11 +4,12 @@ package org.chromium.chrome.browser.omnibox.suggestions; +import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import org.chromium.ui.UiUtils; -import org.chromium.ui.modelutil.ModelListAdapter; +import org.chromium.ui.modelutil.ListObservable; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -22,13 +23,10 @@ public static class SuggestionListViewHolder { public final ViewGroup container; public final OmniboxSuggestionsList listView; - public final ModelListAdapter adapter; - public SuggestionListViewHolder( - ViewGroup container, OmniboxSuggestionsList list, ModelListAdapter adapter) { + public SuggestionListViewHolder(ViewGroup container, OmniboxSuggestionsList list) { this.container = container; this.listView = list; - this.adapter = adapter; } } @@ -53,8 +51,15 @@ } else if (SuggestionListProperties.EMBEDDER.equals(propertyKey)) { view.listView.setEmbedder(model.get(SuggestionListProperties.EMBEDDER)); } else if (SuggestionListProperties.SUGGESTION_MODELS.equals(propertyKey)) { - view.adapter.updateModels(model.get(SuggestionListProperties.SUGGESTION_MODELS)); - view.listView.setSelection(0); + // This should only ever be bound once. + model.get(SuggestionListProperties.SUGGESTION_MODELS) + .addObserver(new ListObservable.ListObserver<Void>() { + @Override + public void onItemRangeChanged(ListObservable<Void> source, int index, + int count, @Nullable Void payload) { + view.listView.setSelection(0); + } + }); } else if (SuggestionListProperties.IS_INCOGNITO.equals(propertyKey)) { view.listView.refreshPopupBackground(model.get(SuggestionListProperties.IS_INCOGNITO)); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sms/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/sms/OWNERS new file mode 100644 index 0000000..39f063f --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/sms/OWNERS
@@ -0,0 +1,4 @@ +file://content/browser/sms/OWNERS + +# COMPONENT: Blink>SMS +# TEAM: fugu-dev@chromium.org
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/SmsReceiverDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/sms/SmsReceiverDialog.java similarity index 98% rename from chrome/android/java/src/org/chromium/chrome/browser/SmsReceiverDialog.java rename to chrome/android/java/src/org/chromium/chrome/browser/sms/SmsReceiverDialog.java index 72dedc7..4e6da50 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/SmsReceiverDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sms/SmsReceiverDialog.java
@@ -2,7 +2,7 @@ // 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; +package org.chromium.chrome.browser.sms; import android.app.Activity; import android.app.ProgressDialog;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/TouchlessAddToHomescreenDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/TouchlessAddToHomescreenDialog.java index cca7cf3..feec210 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/TouchlessAddToHomescreenDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/TouchlessAddToHomescreenDialog.java
@@ -22,6 +22,8 @@ import org.chromium.ui.modaldialog.DialogDismissalCause; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; /** A touchless variation of the {@link AddToHomescreenDialog}. */ @@ -30,6 +32,7 @@ private Delegate mDelegate; private ModalDialogManager mDialogManager; private PropertyModel mModel; + private PropertyModel mAddToHomescreenOption; public TouchlessAddToHomescreenDialog( Activity activity, ModalDialogManager dialogManager, Delegate delegate) { @@ -77,8 +80,19 @@ model.set(TouchlessDialogProperties.CANCEL_ACTION, (v) -> mDialogManager.dismissDialog(model, DialogDismissalCause.UNKNOWN)); - model.set(TouchlessDialogProperties.LIST_MODELS, - new PropertyModel[] {buildListItemModel("")}); + mAddToHomescreenOption = new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) + .with(DialogListItemProperties.TEXT, + res.getString(org.chromium.chrome.R.string.add)) + .with(DialogListItemProperties.ICON, + ApiCompatibilityUtils.getDrawable(res, + org.chromium.chrome.R.drawable.ic_add)) + .with(DialogListItemProperties.MULTI_CLICKABLE, false) + .with(DialogListItemProperties.CLICK_LISTENER, null) + .build(); + ModelList modelList = new ModelList(); + modelList.add(new ListItem( + TouchlessDialogProperties.ListItemType.DEFAULT, mAddToHomescreenOption)); + model.set(TouchlessDialogProperties.LIST_MODELS, modelList); model.set(ModalDialogProperties.CUSTOM_VIEW, mActivity.getLayoutInflater().inflate(R.layout.touchless_add_to_apps, null)); @@ -87,37 +101,6 @@ } /** - * Build the list item that adds the app or site to the home screen. - * @param title The title of the app or site. - * @return The list item for the dialog model. - */ - private PropertyModel buildListItemModel(final String title) { - Resources res = mActivity.getResources(); - return new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) - .with(DialogListItemProperties.TEXT, - res.getString(org.chromium.chrome.R.string.add)) - .with(DialogListItemProperties.ICON, - ApiCompatibilityUtils.getDrawable( - res, org.chromium.chrome.R.drawable.ic_add)) - .with(DialogListItemProperties.MULTI_CLICKABLE, false) - .with(DialogListItemProperties.CLICK_LISTENER, - (v) -> { - ViewGroup group = - (ViewGroup) mModel.get(ModalDialogProperties.CUSTOM_VIEW); - String customTitle = - ((AlertDialogEditText) group.findViewById(R.id.app_title)) - .getText() - .toString(); - if (TextUtils.isEmpty(customTitle)) customTitle = title; - - if (TextUtils.isEmpty(customTitle)) return; - mDelegate.addToHomescreen(customTitle); - mDialogManager.dismissDialog(mModel, DialogDismissalCause.UNKNOWN); - }) - .build(); - } - - /** * Update the custom view shown for the touchless dialog. This shows the name of the app, icon, * and site. */ @@ -139,8 +122,16 @@ @Override public void onUserTitleAvailable(String title, String url, boolean isWebapp) { updateModelCustomView(null, title, url); - mModel.set(TouchlessDialogProperties.LIST_MODELS, - new PropertyModel[] {buildListItemModel(title)}); + mAddToHomescreenOption.set(DialogListItemProperties.CLICK_LISTENER, (v) -> { + ViewGroup group = (ViewGroup) mModel.get(ModalDialogProperties.CUSTOM_VIEW); + String customTitle = + ((AlertDialogEditText) group.findViewById(R.id.app_title)).getText().toString(); + if (TextUtils.isEmpty(customTitle)) customTitle = title; + + if (TextUtils.isEmpty(customTitle)) return; + mDelegate.addToHomescreen(customTitle); + mDialogManager.dismissDialog(mModel, DialogDismissalCause.UNKNOWN); + }); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/PulseDrawable.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/PulseDrawable.java index 6ae271c..546be1fb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/PulseDrawable.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/PulseDrawable.java
@@ -62,6 +62,45 @@ } /** + * Interface for calculating the max and min bounds in a pulsing circle. + */ + public interface Bounds { + /** + * Calculates the maximum radius of a pulsing circle. + * @param bounds the bounds of the canvas. + * @return floating point maximum radius. + */ + float getMaxRadiusPx(Rect bounds); + + /** + * @param bounds the bounds of the canvas. + * @return floating point minimum radius. + */ + float getMinRadiusPx(Rect bounds); + } + + private static Painter createCirclePainter(Bounds boundsFn) { + return new PulseDrawable.Painter() { + @Override + public void modifyDrawable(PulseDrawable drawable, float interpolation) { + drawable.invalidateSelf(); + } + + @Override + public void draw( + PulseDrawable drawable, Paint paint, Canvas canvas, float interpolation) { + Rect bounds = drawable.getBounds(); + + float minRadiusPx = boundsFn.getMinRadiusPx(bounds); + float maxRadiusPx = boundsFn.getMaxRadiusPx(bounds); + float radius = MathUtils.interpolate(minRadiusPx, maxRadiusPx, interpolation); + + canvas.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), radius, paint); + } + }; + } + + /** * Creates a {@link PulseDrawable} that will fill the bounds with a pulsing color. * @param context The {@link Context} under which the drawable is created. * @return A new {@link PulseDrawable} instance. @@ -92,25 +131,28 @@ final int startingPulseRadiusPx = context.getResources().getDimensionPixelSize(R.dimen.iph_pulse_baseline_radius); - PulseDrawable.Painter painter = new PulseDrawable.Painter() { + return createCustomCircle(context, new Bounds() { @Override - public void modifyDrawable(PulseDrawable drawable, float interpolation) { - drawable.invalidateSelf(); + public float getMaxRadiusPx(Rect bounds) { + return Math.min(startingPulseRadiusPx * 1.2f, + Math.min(bounds.width(), bounds.height()) / 2.f); } - @Override - public void draw( - PulseDrawable drawable, Paint paint, Canvas canvas, float interpolation) { - Rect bounds = drawable.getBounds(); - float maxAvailRadiusPx = Math.min(bounds.width(), bounds.height()) / 2.f; - - float minRadiusPx = Math.min(startingPulseRadiusPx, maxAvailRadiusPx); - float maxRadiusPx = Math.min(startingPulseRadiusPx * 1.2f, maxAvailRadiusPx); - float radius = MathUtils.interpolate(minRadiusPx, maxRadiusPx, interpolation); - - canvas.drawCircle(bounds.exactCenterX(), bounds.exactCenterY(), radius, paint); + public float getMinRadiusPx(Rect bounds) { + return Math.min( + startingPulseRadiusPx, Math.min(bounds.width(), bounds.height()) / 2.f); } - }; + }); + } + + /** + * Creates a {@link PulseDrawable} that will draw a pulsing circle as large as possible inside + * the bounds. + * @param context The {@link Context} under which the drawable is created. + * @return A new {@link PulseDrawable} instance. + */ + public static PulseDrawable createCustomCircle(Context context, Bounds boundsfn) { + Painter painter = createCirclePainter(boundsfn); PulseDrawable drawable = new PulseDrawable( context, PathInterpolatorCompat.create(.8f, 0.f, .6f, 1.f), painter);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/ViewHighlighter.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/ViewHighlighter.java index 81ca0f440..3267efa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/ViewHighlighter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/ViewHighlighter.java
@@ -35,16 +35,28 @@ public static void turnOnHighlight(View view, boolean circular) { if (view == null) return; + PulseDrawable pulseDrawable = circular ? PulseDrawable.createCircle(view.getContext()) + : PulseDrawable.createHighlight(view.getContext()); + + attachViewAsHighlight(view, pulseDrawable); + } + + /** + * Attach a custom PulseDrawable as a highlight layer over the view. + * + * Will not highlight if the view is already highlighted. + * + * @param view The view to be highlighted. + * @param pulseDrawable The highlight. + */ + public static void attachViewAsHighlight(View view, PulseDrawable pulseDrawable) { boolean highlighted = view.getTag(R.id.highlight_state) != null ? (boolean) view.getTag(R.id.highlight_state) : false; if (highlighted) return; - PulseDrawable pulseDrawable = circular ? PulseDrawable.createCircle(view.getContext()) - : PulseDrawable.createHighlight(view.getContext()); - Resources resources = view.getContext().getResources(); - Drawable background = (Drawable) view.getBackground(); + Drawable background = view.getBackground(); if (background != null) { background = background.getConstantState().newDrawable(resources); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTest.java index 6748e331..d9ab113 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/ContextMenuTest.java
@@ -119,8 +119,6 @@ @Test @MediumTest @Feature({"Browser"}) - @RetryOnFailure - @DisabledTest(message = "https://crbug.com/959265") public void testCopyImageLinkCopiesLinkURL() throws Throwable { Tab tab = mDownloadTestRule.getActivity().getActivityTab(); ContextMenuUtils.selectContextMenuItem(InstrumentationRegistry.getInstrumentation(), @@ -415,8 +413,6 @@ @Test @SmallTest @Feature({"Browser", "ContextMenu"}) - @RetryOnFailure - @DisabledTest(message = "https://crbug.com/959265") public void testContextMenuRetrievesImageLinkOptions() throws TimeoutException, InterruptedException { Tab tab = mDownloadTestRule.getActivity().getActivityTab(); @@ -464,7 +460,18 @@ } } - Assert.assertThat(actualItems, Matchers.containsInAnyOrder(expectedItems)); + Assert.assertThat("Populated menu items were:" + getMenuTitles(menu), actualItems, + Matchers.containsInAnyOrder(expectedItems)); + } + + private String getMenuTitles(ContextMenu menu) { + StringBuilder items = new StringBuilder(); + for (int i = 0; i < menu.size(); i++) { + if (menu.getItem(i).isVisible()) { + items.append("\n").append(menu.getItem(i).getTitle()); + } + } + return items.toString(); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuRenderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuRenderTest.java index 9e6d45d1..839cf4a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuRenderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuRenderTest.java
@@ -28,6 +28,8 @@ import org.chromium.chrome.test.ui.DummyUiActivityTestCase; import org.chromium.chrome.test.util.RenderTestRule; import org.chromium.content_public.browser.test.util.TestThreadUtils; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.ModelListAdapter; import org.chromium.ui.modelutil.PropertyModel; @@ -49,6 +51,7 @@ public RenderTestRule mRenderTestRule = new RenderTestRule(); private ModelListAdapter mAdapter; + private ModelList mListItems; private View mView; private View mFrame; @@ -60,7 +63,8 @@ @Override public void setUpTest() throws Exception { super.setUpTest(); - mAdapter = new ModelListAdapter(); + mListItems = new ModelList(); + mAdapter = new ModelListAdapter(mListItems); TestThreadUtils.runOnUiThreadBlocking(() -> { getActivity().setContentView(R.layout.revamped_context_menu); mView = getActivity().findViewById(android.R.id.content); @@ -97,6 +101,7 @@ @Override public void tearDownTest() throws Exception { NightModeTestUtils.tearDownNightModeForDummyUiActivity(); + TestThreadUtils.runOnUiThreadBlocking(() -> mListItems.clear()); super.tearDownTest(); } @@ -105,20 +110,17 @@ @Feature({"RenderTest"}) public void testRevampedContextMenuViewWithLink() throws IOException { TestThreadUtils.runOnUiThreadBlocking(() -> { - List<Pair<Integer, PropertyModel>> itemList = new ArrayList<>(); - itemList.add( - new Pair<>(ListItemType.HEADER, getHeaderModel("", "www.google.com", false))); - itemList.add(new Pair<>(ListItemType.DIVIDER, new PropertyModel())); - itemList.add( - (new Pair<>(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in new tab")))); - itemList.add((new Pair<>( + mListItems.add( + new ListItem(ListItemType.HEADER, getHeaderModel("", "www.google.com", false))); + mListItems.add(new ListItem(ListItemType.DIVIDER, new PropertyModel())); + mListItems.add(( + new ListItem(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in new tab")))); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in incognito tab")))); - itemList.add(( - new Pair<>(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Copy link address")))); - itemList.add((new Pair<>( + mListItems.add((new ListItem( + ListItemType.CONTEXT_MENU_ITEM, getItemModel("Copy link address")))); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_SHARE_ITEM, getShareItemModel("Share link")))); - - mAdapter.updateModels(itemList); }); mRenderTestRule.render(mFrame, "revamped_context_menu_with_link"); } @@ -129,26 +131,25 @@ public void testRevampedContextMenuViewWithImageLink() throws IOException { TestThreadUtils.runOnUiThreadBlocking(() -> { List<Pair<Integer, PropertyModel>> itemList = new ArrayList<>(); - itemList.add(new Pair<>( + mListItems.add(new ListItem( ListItemType.HEADER, getHeaderModel("Capybara", "www.google.com", true))); - itemList.add(new Pair<>(ListItemType.DIVIDER, new PropertyModel())); - itemList.add( - (new Pair<>(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in new tab")))); - itemList.add((new Pair<>( + mListItems.add(new ListItem(ListItemType.DIVIDER, new PropertyModel())); + mListItems.add(( + new ListItem(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in new tab")))); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open in incognito tab")))); - itemList.add(( - new Pair<>(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Copy link address")))); - itemList.add((new Pair<>( + mListItems.add((new ListItem( + ListItemType.CONTEXT_MENU_ITEM, getItemModel("Copy link address")))); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_SHARE_ITEM, getShareItemModel("Share link")))); - itemList.add(new Pair<>(ListItemType.DIVIDER, new PropertyModel())); - itemList.add((new Pair<>( + mListItems.add(new ListItem(ListItemType.DIVIDER, new PropertyModel())); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_ITEM, getItemModel("Open image in new tab")))); - itemList.add( - (new Pair<>(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Download image")))); - itemList.add((new Pair<>( + mListItems.add( + (new ListItem(ListItemType.CONTEXT_MENU_ITEM, getItemModel("Download image")))); + mListItems.add((new ListItem( ListItemType.CONTEXT_MENU_SHARE_ITEM, getShareItemModel("Share image")))); - mAdapter.updateModels(itemList); }); mRenderTestRule.render(mFrame, "revamped_context_menu_with_image_link"); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/sms/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/sms/OWNERS new file mode 100644 index 0000000..39f063f --- /dev/null +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/sms/OWNERS
@@ -0,0 +1,4 @@ +file://content/browser/sms/OWNERS + +# COMPONENT: Blink>SMS +# TEAM: fugu-dev@chromium.org
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/SmsReceiverDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/sms/SmsReceiverDialogTest.java similarity index 96% rename from chrome/android/javatests/src/org/chromium/chrome/browser/SmsReceiverDialogTest.java rename to chrome/android/javatests/src/org/chromium/chrome/browser/sms/SmsReceiverDialogTest.java index 6ac2d0667..be75b1df 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/SmsReceiverDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/sms/SmsReceiverDialogTest.java
@@ -2,7 +2,7 @@ // 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; +package org.chromium.chrome.browser.sms; import android.app.ProgressDialog; import android.content.DialogInterface; @@ -19,6 +19,8 @@ import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.JniMocker; +import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.content_public.browser.test.util.TestThreadUtils;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebApkIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebApkIntegrationTest.java index e1ee2cc..5c0bdfa9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebApkIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/webapps/WebApkIntegrationTest.java
@@ -22,6 +22,7 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.ScalableTimeout; +import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.DeferredStartupHandler; @@ -30,6 +31,8 @@ import org.chromium.chrome.browser.customtabs.CustomTabIntentDataProvider; import org.chromium.chrome.browser.tab.TabWebContentsDelegateAndroid; import org.chromium.chrome.browser.test.MockCertVerifierRuleAndroid; +import org.chromium.chrome.browser.touchless.TouchlessDelegate; +import org.chromium.chrome.browser.util.FeatureUtilities; import org.chromium.chrome.browser.util.IntentUtils; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; @@ -143,7 +146,7 @@ mActivityTestRule.startActivityCompletely(intent); - WebApkActivity lastActivity = (WebApkActivity) mActivityTestRule.getActivity(); + WebApkActivity lastActivity = mActivityTestRule.getActivity(); Assert.assertEquals(pwaRocksUrl, lastActivity.getWebappInfo().uri().toString()); } @@ -157,7 +160,7 @@ public void testLaunchAndNavigateOffOrigin() throws Exception { startWebApkActivity("org.chromium.webapk.test", getUrlForHost("pwa.rocks")); waitUntilSplashscreenHides(); - WebApkActivity webApkActivity = (WebApkActivity) mActivityTestRule.getActivity(); + WebApkActivity webApkActivity = mActivityTestRule.getActivity(); WebappActivityTestRule.assertToolbarShowState(webApkActivity, false); // We navigate outside origin and expect CCT toolbar to show on top of WebApkActivity. @@ -281,15 +284,18 @@ startWebApkActivity("org.chromium.webapk.test", getUrlForHost("pwa.rocks")); waitUntilSplashscreenHides(); + Class<? extends ChromeActivity> mainClass = FeatureUtilities.isNoTouchModeEnabled() + ? TouchlessDelegate.getNoTouchActivityClass() + : ChromeTabbedActivity.class; + // Move WebAPK to the background by launching Chrome. - Intent intent = - new Intent(InstrumentationRegistry.getTargetContext(), ChromeTabbedActivity.class); + Intent intent = new Intent(InstrumentationRegistry.getTargetContext(), mainClass); intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK | ApiCompatibilityUtils.getActivityNewDocumentFlag()); InstrumentationRegistry.getTargetContext().startActivity(intent); - ChromeActivityTestRule.waitFor(ChromeTabbedActivity.class); + ChromeActivityTestRule.waitFor(mainClass); - WebApkActivity webApkActivity = (WebApkActivity) mActivityTestRule.getActivity(); + WebApkActivity webApkActivity = mActivityTestRule.getActivity(); TabWebContentsDelegateAndroid tabDelegate = webApkActivity.getActivityTab().getTabWebContentsDelegateAndroid(); tabDelegate.activateContents();
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java index 8b1ebf3..7580d65 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/contextmenu/RevampedContextMenuCoordinatorTest.java
@@ -21,7 +21,7 @@ import org.chromium.chrome.browser.contextmenu.ChromeContextMenuItem.Item; import org.chromium.chrome.browser.contextmenu.ChromeContextMenuPopulator.ContextMenuGroup; import org.chromium.chrome.browser.contextmenu.RevampedContextMenuCoordinator.ListItemType; -import org.chromium.ui.modelutil.PropertyModel; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import java.util.ArrayList; import java.util.List; @@ -62,19 +62,18 @@ rawItems.add(new Pair<>(ContextMenuGroup.IMAGE, groupTwo)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params); - List<Pair<Integer, PropertyModel>> itemList = - mCoordinator.getItemList(mActivity, rawItems, params); + ModelList itemList = mCoordinator.getItemList(mActivity, rawItems, params); - assertThat(itemList.get(0).first, equalTo(ListItemType.HEADER)); - assertThat(itemList.get(1).first, equalTo(ListItemType.DIVIDER)); - assertThat(itemList.get(2).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(3).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(4).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(5).first, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); - assertThat(itemList.get(6).first, equalTo(ListItemType.DIVIDER)); - assertThat(itemList.get(7).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(8).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(9).first, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); + assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); + assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); + assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(3).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(4).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(5).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); + assertThat(itemList.get(6).type, equalTo(ListItemType.DIVIDER)); + assertThat(itemList.get(7).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(8).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(9).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); } @Test @@ -96,15 +95,14 @@ rawItems.add(new Pair<>(ContextMenuGroup.LINK, groupOne)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params); - List<Pair<Integer, PropertyModel>> itemList = - mCoordinator.getItemList(mActivity, rawItems, params); + ModelList itemList = mCoordinator.getItemList(mActivity, rawItems, params); - assertThat(itemList.get(0).first, equalTo(ListItemType.HEADER)); - assertThat(itemList.get(1).first, equalTo(ListItemType.DIVIDER)); - assertThat(itemList.get(2).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(3).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(4).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); - assertThat(itemList.get(5).first, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); + assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); + assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); + assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(3).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(4).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(5).type, equalTo(ListItemType.CONTEXT_MENU_SHARE_ITEM)); } @Test @@ -118,11 +116,10 @@ rawItems.add(new Pair<>(ContextMenuGroup.LINK, groupOne)); mCoordinator.initializeHeaderCoordinatorForTesting(mActivity, params); - List<Pair<Integer, PropertyModel>> itemList = - mCoordinator.getItemList(mActivity, rawItems, params); + ModelList itemList = mCoordinator.getItemList(mActivity, rawItems, params); - assertThat(itemList.get(0).first, equalTo(ListItemType.HEADER)); - assertThat(itemList.get(1).first, equalTo(ListItemType.DIVIDER)); - assertThat(itemList.get(2).first, equalTo(ListItemType.CONTEXT_MENU_ITEM)); + assertThat(itemList.get(0).type, equalTo(ListItemType.HEADER)); + assertThat(itemList.get(1).type, equalTo(ListItemType.DIVIDER)); + assertThat(itemList.get(2).type, equalTo(ListItemType.CONTEXT_MENU_ITEM)); } }
diff --git a/chrome/android/modules/chrome_feature_module_tmpl.gni b/chrome/android/modules/chrome_feature_module_tmpl.gni index ed792f3e..ed1de3b 100644 --- a/chrome/android/modules/chrome_feature_module_tmpl.gni +++ b/chrome/android/modules/chrome_feature_module_tmpl.gni
@@ -19,7 +19,15 @@ # include_32_bit_webview: (Optional) Whether to include 32 bit code for # WebView. template("chrome_feature_module") { + assert(defined(invoker.module_desc)) + assert(defined(invoker.module_name_suffix)) _module_desc = invoker.module_desc + _is_monochrome_or_trichrome = defined(invoker.is_monochrome_or_trichrome) && + invoker.is_monochrome_or_trichrome + _is_64_bit_browser = + defined(invoker.is_64_bit_browser) && invoker.is_64_bit_browser + _include_32_bit_webview = + defined(invoker.include_32_bit_webview) && invoker.include_32_bit_webview android_app_bundle_module(target_name) { forward_variables_from(invoker, @@ -63,14 +71,11 @@ } if (defined(_module_desc.native_deps) && _module_desc.native_deps != []) { - _is_monochrome_or_trichrome = - defined(invoker.is_monochrome_or_trichrome) && - invoker.is_monochrome_or_trichrome _arch = "" _toolchain = "" _root_out_dir = root_out_dir if (android_64bit_target_cpu && _is_monochrome_or_trichrome) { - if (defined(invoker.is_64_bit_browser) && invoker.is_64_bit_browser) { + if (_is_64_bit_browser) { _arch = "_64" } else { _toolchain = "($android_secondary_abi_toolchain)" @@ -92,8 +97,8 @@ # for the other architecture if required. _loadable_modules_32_bit += [ _native_library ] _loadable_modules_64_bit += [ _native_library ] - } else if (defined(invoker.is_monochrome_or_trichrome)) { - not_needed(invoker, [ "is_monochrome_or_trichrome" ]) + } else { + not_needed([ "_is_monochrome_or_trichrome" ]) } if (defined(_module_desc.loadable_module_dep)) { @@ -115,21 +120,53 @@ } } + # Specify native libraries and placeholders. if (_loadable_modules_32_bit != [] || _loadable_modules_64_bit != []) { - # TODO(tiborg): Move loadable module selection logic here. - native_switches = { - is_64_bit_browser = invoker.is_64_bit_browser - include_32_bit_webview = invoker.include_32_bit_webview + # Decision logic: Assign decision variables: + # _loadable_modules_to_use: Either |_loadable_modules_64_bit| or + # |_loadable_modules_32_bit|. + # _native_is_primary: Whether |_loadable_modules_to_use| should be + # assigned as primary ABI or secondary ABI. + # _native_need_placeholder: Whether a placeholder is needed for the + # complementary ABI to the library. + if (_is_64_bit_browser) { + assert(_loadable_modules_64_bit != []) + not_needed([ "_loadable_modules_32_bit" ]) + _loadable_modules_to_use = _loadable_modules_64_bit + _native_is_primary = + !build_apk_secondary_abi || android_64bit_target_cpu + _native_need_placeholder = + build_apk_secondary_abi && _include_32_bit_webview + } else { + assert(_loadable_modules_32_bit != []) + not_needed([ + "_loadable_modules_64_bit", + "_include_32_bit_webview", + ]) + _loadable_modules_to_use = _loadable_modules_32_bit + _native_is_primary = + !build_apk_secondary_abi || !android_64bit_target_cpu + _native_need_placeholder = + build_apk_secondary_abi && android_64bit_target_cpu } - loadable_modules_if_32_bit = _loadable_modules_32_bit - loadable_modules_if_64_bit = _loadable_modules_64_bit + + # Realization logic: Assign libraries and placeholders. + if (_native_is_primary) { + loadable_modules = _loadable_modules_to_use + if (_native_need_placeholder) { + secondary_native_lib_placeholders = [ "libdummy.so" ] + } + } else { + secondary_abi_loadable_modules = _loadable_modules_to_use + if (_native_need_placeholder) { + native_lib_placeholders = [ "libdummy.so" ] + } + } } else { - if (defined(invoker.is_64_bit_browser)) { - not_needed(invoker, [ "is_64_bit_browser" ]) - } - if (defined(invoker.include_32_bit_webview)) { - not_needed(invoker, [ "include_32_bit_webview" ]) - } + not_needed([ + "_is_64_bit_browser", + "_include_32_bit_webview", + ]) } } }
diff --git a/chrome/android/modules/chrome_feature_modules.gni b/chrome/android/modules/chrome_feature_modules.gni index 765f7a6..22ef6f3 100644 --- a/chrome/android/modules/chrome_feature_modules.gni +++ b/chrome/android/modules/chrome_feature_modules.gni
@@ -41,9 +41,9 @@ # feature module library. # proguard_async: (Optional) Whether to proguard the module asynchronously. # loadable_modules_32_bit: (Optional) List of additional 32-bit shared -# library files going into module. +# library files going into module if the module is executed in 32 bit. # loadable_modules_64_bit: (Optional) List of additional 64-bit shared -# library files going into module. +# library files going into module if the module is executed in 64 bit. # Each new module needs to add a desc to one of the lists below. # Modules shipped in Chrome Modern (Android L+).
diff --git a/chrome/android/touchless/fallback/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java b/chrome/android/touchless/fallback/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java index 3593283..f91c2f0 100644 --- a/chrome/android/touchless/fallback/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java +++ b/chrome/android/touchless/fallback/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java
@@ -34,7 +34,7 @@ return null; } - public static Class<?> getNoTouchActivityClass() { + public static Class<? extends ChromeActivity> getNoTouchActivityClass() { return null; }
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessContextMenuManager.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessContextMenuManager.java index ceaf2212..5d41f80b 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessContextMenuManager.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessContextMenuManager.java
@@ -17,13 +17,14 @@ import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ActionNames; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.DialogListItemProperties; +import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ListItemType; import org.chromium.chrome.touchless.R; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; -import java.util.ArrayList; - /** * Handles context menu creation for native pages on touchless devices. Utilizes functionality in * ContextMenuManager and Delegate to select items to show and lookup their labels. @@ -90,7 +91,7 @@ return; } - ArrayList<PropertyModel> menuItems = new ArrayList<>(); + ModelList menuItems = new ModelList(); for (@ContextMenuItemId int itemId = 0; itemId < ContextMenuItemId.NUM_ENTRIES; itemId++) { if (!shouldShowItem(itemId, delegate)) continue; @@ -98,13 +99,11 @@ // itemId of this item is maintained. PropertyModel menuItem = buildMenuItem(itemId, new TouchlessItemClickListener(delegate, itemId)); - menuItems.add(menuItem); + menuItems.add(new ListItem(ListItemType.DEFAULT, menuItem)); } if (menuItems.size() == 0) return; - PropertyModel[] menuItemsArray = new PropertyModel[menuItems.size()]; - menuItemsArray = menuItems.toArray(menuItemsArray); - mTouchlessMenuModel = buildMenuModel(delegate.getContextMenuTitle(), menuItemsArray); + mTouchlessMenuModel = buildMenuModel(delegate.getContextMenuTitle(), menuItems); mModalDialogManager = modalDialogManager; mModalDialogManager.showDialog(mTouchlessMenuModel, ModalDialogManager.ModalDialogType.APP); @@ -187,7 +186,7 @@ } /** Builds PropertyModel for context menu from list of PropertyModels for individual items. */ - private PropertyModel buildMenuModel(String title, PropertyModel[] menuItems) { + private PropertyModel buildMenuModel(String title, ModelList menuItems) { PropertyModel.Builder builder = new PropertyModel.Builder(TouchlessDialogProperties.ALL_DIALOG_KEYS); ActionNames names = new ActionNames();
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java index 9ed6f47b..1aae05b 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessDelegate.java
@@ -35,7 +35,7 @@ return new TouchlessExploreSitesPage(activity, host); } - public static Class<?> getNoTouchActivityClass() { + public static Class<? extends ChromeActivity> getNoTouchActivityClass() { return NoTouchActivity.class; }
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java index a780da24..9774482 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java
@@ -68,7 +68,7 @@ TraceEvent.begin(TAG); mModalDialogManager = activity.getModalDialogManager(); - mTab = activity.getActivityTab(); + mTab = nativePageHost.getActiveTab(); Profile profile = mTab.getProfile(); mTitle = activity.getResources().getString(R.string.button_new_tab);
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogPresenter.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogPresenter.java index ce538138..732c3b4 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogPresenter.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogPresenter.java
@@ -7,7 +7,6 @@ import android.app.Dialog; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; -import android.util.Pair; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -31,8 +30,6 @@ import org.chromium.ui.modelutil.PropertyModelChangeProcessor; import org.chromium.ui.widget.ChromeImageView; -import java.util.ArrayList; - /** A modal dialog presenter that is specific to touchless dialogs. */ public class TouchlessDialogPresenter extends Presenter { /** An activity to attach dialogs to. */ @@ -43,8 +40,8 @@ private Dialog mDialog; /** The model change processor for the currently shown dialog. */ - private PropertyModelChangeProcessor<PropertyModel, Pair<ViewGroup, ModelListAdapter>, - PropertyKey> mModelChangeProcessor; + private PropertyModelChangeProcessor<PropertyModel, ViewGroup, PropertyKey> + mModelChangeProcessor; public TouchlessDialogPresenter( ChromeActivity activity, TouchlessModelCoordinator modelCoordinator) { @@ -92,15 +89,18 @@ }); ViewGroup dialogView = (ViewGroup) LayoutInflater.from(mDialog.getContext()) .inflate(R.layout.touchless_dialog_view, null); - ModelListAdapter adapter = new ModelListAdapter(); - adapter.registerType(ListItemType.DEFAULT, - () -> LayoutInflater.from(mActivity).inflate(R.layout.dialog_list_item, null), - TouchlessDialogPresenter::bindListItem); - ListView dialogOptions = dialogView.findViewById(R.id.touchless_dialog_option_list); - dialogOptions.setAdapter(adapter); - dialogOptions.setItemsCanFocus(true); + if (model.get(TouchlessDialogProperties.LIST_MODELS) != null) { + ModelListAdapter adapter = + new ModelListAdapter(model.get(TouchlessDialogProperties.LIST_MODELS)); + adapter.registerType(ListItemType.DEFAULT, + () -> LayoutInflater.from(mActivity).inflate(R.layout.dialog_list_item, null), + TouchlessDialogPresenter::bindListItem); + ListView dialogOptions = dialogView.findViewById(R.id.touchless_dialog_option_list); + dialogOptions.setAdapter(adapter); + dialogOptions.setItemsCanFocus(true); + } mModelChangeProcessor = PropertyModelChangeProcessor.create( - model, Pair.create(dialogView, adapter), TouchlessDialogPresenter::bind); + model, dialogView, TouchlessDialogPresenter::bind); mDialog.setContentView(dialogView); // If the modal dialog is not specified to be fullscreen, wrap content and place at the @@ -143,10 +143,7 @@ * @param view The view to apply the model to. * @param propertyKey The property that changed. */ - private static void bind( - PropertyModel model, Pair<ViewGroup, ModelListAdapter> view, PropertyKey propertyKey) { - ViewGroup dialogView = view.first; - ModelListAdapter optionsAdapter = view.second; + private static void bind(PropertyModel model, ViewGroup view, PropertyKey propertyKey) { assert !model.get(ModalDialogProperties.FILTER_TOUCH_FOR_SECURITY); assert propertyKey != ModalDialogProperties.FILTER_TOUCH_FOR_SECURITY; // TODO(mdjones): If the default buttons are used assert no list items and convert the @@ -154,38 +151,31 @@ if (TouchlessDialogProperties.IS_FULLSCREEN == propertyKey) { // TODO(mdjones): Implement fullscreen/non-fullscreen modes. } else if (ModalDialogProperties.TITLE_ICON == propertyKey) { - ChromeImageView imageView = dialogView.findViewById(R.id.touchless_dialog_icon); + ChromeImageView imageView = view.findViewById(R.id.touchless_dialog_icon); imageView.setImageDrawable(model.get(ModalDialogProperties.TITLE_ICON)); imageView.setVisibility(View.VISIBLE); } else if (ModalDialogProperties.TITLE == propertyKey) { - TextView textView = dialogView.findViewById(R.id.touchless_dialog_title); + TextView textView = view.findViewById(R.id.touchless_dialog_title); textView.setText(model.get(ModalDialogProperties.TITLE)); textView.setVisibility(View.VISIBLE); } else if (ModalDialogProperties.MESSAGE == propertyKey) { - TextView textView = dialogView.findViewById(R.id.touchless_dialog_description); + TextView textView = view.findViewById(R.id.touchless_dialog_description); textView.setText(model.get(ModalDialogProperties.MESSAGE)); textView.setVisibility(View.VISIBLE); } else if (ModalDialogProperties.CUSTOM_VIEW == propertyKey) { - ViewGroup customGroup = dialogView.findViewById(R.id.custom); + ViewGroup customGroup = view.findViewById(R.id.custom); customGroup.addView(model.get(ModalDialogProperties.CUSTOM_VIEW)); customGroup.setVisibility(View.VISIBLE); - } else if (TouchlessDialogProperties.LIST_MODELS == propertyKey) { - PropertyModel[] models = model.get(TouchlessDialogProperties.LIST_MODELS); - ArrayList<Pair<Integer, PropertyModel>> modelPairs = new ArrayList<>(); - for (int i = 0; i < models.length; i++) { - modelPairs.add(Pair.create(0, models[i])); - } - optionsAdapter.updateModels(modelPairs); } else if (TouchlessDialogProperties.FORCE_SINGLE_LINE_TITLE == propertyKey) { - TextView textView = dialogView.findViewById(R.id.touchless_dialog_title); + TextView textView = view.findViewById(R.id.touchless_dialog_title); textView.setMaxLines(model.get(TouchlessDialogProperties.FORCE_SINGLE_LINE_TITLE) ? 1 : Integer.MAX_VALUE); } else if (TouchlessDialogProperties.TITLE_DIRECTION == propertyKey) { - TextView textView = dialogView.findViewById(R.id.touchless_dialog_title); + TextView textView = view.findViewById(R.id.touchless_dialog_title); textView.setTextDirection(model.get(TouchlessDialogProperties.TITLE_DIRECTION)); } else if (TouchlessDialogProperties.TITLE_ELLIPSIZE == propertyKey) { - TextView textView = dialogView.findViewById(R.id.touchless_dialog_title); + TextView textView = view.findViewById(R.id.touchless_dialog_title); textView.setEllipsize(model.get(TouchlessDialogProperties.TITLE_ELLIPSIZE)); } }
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogProperties.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogProperties.java index fea5cba..be15cff 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogProperties.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogProperties.java
@@ -13,6 +13,7 @@ import android.widget.TextView; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.modelutil.PropertyModel.ReadableBooleanPropertyKey; @@ -93,7 +94,7 @@ * The list of options to be displayed in the dialog. These models should be using the * {@link DialogListItemProperties} properties. */ - public static final WritableObjectPropertyKey<PropertyModel[]> LIST_MODELS = + public static final WritableObjectPropertyKey<ModelList> LIST_MODELS = new WritableObjectPropertyKey<>(); /** The names for the Actions. */
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/permissions/TouchlessPermissionDialogModel.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/permissions/TouchlessPermissionDialogModel.java index 32c98f3c..c72c4e7 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/permissions/TouchlessPermissionDialogModel.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/permissions/TouchlessPermissionDialogModel.java
@@ -16,9 +16,12 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.permissions.PermissionDialogDelegate; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties; +import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ListItemType; import org.chromium.ui.UiUtils; import org.chromium.ui.modaldialog.DialogDismissalCause; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; /** @@ -53,29 +56,33 @@ .with(ModalDialogProperties.CONTENT_DESCRIPTION, delegate.getMessageText()) .build(); - PropertyModel[] items = new PropertyModel[]{ + ModelList items = new ModelList(); + items.add(new ListItem(ListItemType.DEFAULT, new PropertyModel .Builder(TouchlessDialogProperties.DialogListItemProperties.ALL_KEYS) .with(TouchlessDialogProperties.DialogListItemProperties.TEXT, delegate.getPrimaryButtonText()) .with(TouchlessDialogProperties.DialogListItemProperties.CLICK_LISTENER, - (v) -> controller.onClick(model, - ModalDialogProperties.ButtonType.POSITIVE)) + (v) + -> controller.onClick( + model, ModalDialogProperties.ButtonType.POSITIVE)) .with(TouchlessDialogProperties.DialogListItemProperties.ICON, ApiCompatibilityUtils.getDrawable( resources, R.drawable.ic_check_circle)) - .build(), + .build())); + items.add(new ListItem(ListItemType.DEFAULT, new PropertyModel .Builder(TouchlessDialogProperties.DialogListItemProperties.ALL_KEYS) .with(TouchlessDialogProperties.DialogListItemProperties.TEXT, delegate.getSecondaryButtonText()) .with(TouchlessDialogProperties.DialogListItemProperties.CLICK_LISTENER, - (v) -> controller.onClick(model, - ModalDialogProperties.ButtonType.NEGATIVE)) + (v) + -> controller.onClick( + model, ModalDialogProperties.ButtonType.NEGATIVE)) .with(TouchlessDialogProperties.DialogListItemProperties.ICON, ApiCompatibilityUtils.getDrawable( resources, R.drawable.ic_cancel_circle)) - .build()}; + .build())); model.set(TouchlessDialogProperties.LIST_MODELS, items); model.set(TouchlessDialogProperties.CANCEL_ACTION, @@ -103,20 +110,20 @@ .with(TouchlessDialogProperties.ACTION_NAMES, names) .with(TouchlessDialogProperties.ALT_ACTION, null) .build(); - model.set(TouchlessDialogProperties.LIST_MODELS, - new PropertyModel[] { - new PropertyModel - .Builder( - TouchlessDialogProperties.DialogListItemProperties.ALL_KEYS) - .with(TouchlessDialogProperties.DialogListItemProperties.TEXT, - resources, R.string.infobar_update_permissions_button_text) - .with(TouchlessDialogProperties.DialogListItemProperties.ICON, - context, R.drawable.ic_check_circle) - .with(TouchlessDialogProperties.DialogListItemProperties - .CLICK_LISTENER, - (v) -> controller.onClick(model, - ModalDialogProperties.ButtonType.POSITIVE)) - .build()}); + ModelList items = new ModelList(); + items.add(new ListItem(ListItemType.DEFAULT, + new PropertyModel + .Builder(TouchlessDialogProperties.DialogListItemProperties.ALL_KEYS) + .with(TouchlessDialogProperties.DialogListItemProperties.TEXT, resources, + R.string.infobar_update_permissions_button_text) + .with(TouchlessDialogProperties.DialogListItemProperties.ICON, context, + R.drawable.ic_check_circle) + .with(TouchlessDialogProperties.DialogListItemProperties.CLICK_LISTENER, + (v) + -> controller.onClick( + model, ModalDialogProperties.ButtonType.POSITIVE)) + .build())); + model.set(TouchlessDialogProperties.LIST_MODELS, items); return model; } }
diff --git a/chrome/android/touchless/javatests/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogTestUtils.java b/chrome/android/touchless/javatests/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogTestUtils.java index 0111a6b8..8bbc84a2 100644 --- a/chrome/android/touchless/javatests/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogTestUtils.java +++ b/chrome/android/touchless/javatests/src/org/chromium/chrome/browser/touchless/dialog/TouchlessDialogTestUtils.java
@@ -7,9 +7,12 @@ import android.view.View; import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.DialogListItemProperties; +import org.chromium.chrome.browser.touchless.dialog.TouchlessDialogProperties.ListItemType; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; +import org.chromium.ui.modelutil.MVCListAdapter.ListItem; +import org.chromium.ui.modelutil.MVCListAdapter.ModelList; import org.chromium.ui.modelutil.PropertyModel; import java.util.concurrent.ExecutionException; @@ -57,14 +60,15 @@ }); } - private static PropertyModel[] generateItems( + private static ModelList generateItems( String[] itemTitles, View.OnClickListener[] itemListeners) { - PropertyModel[] items = new PropertyModel[itemTitles.length]; - for (int i = 0; i < items.length; i++) { - items[i] = new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) - .with(DialogListItemProperties.TEXT, itemTitles[i]) - .with(DialogListItemProperties.CLICK_LISTENER, itemListeners[i]) - .build(); + ModelList items = new ModelList(); + for (int i = 0; i < itemTitles.length; i++) { + items.add(new ListItem(ListItemType.DEFAULT, + new PropertyModel.Builder(DialogListItemProperties.ALL_KEYS) + .with(DialogListItemProperties.TEXT, itemTitles[i]) + .with(DialogListItemProperties.CLICK_LISTENER, itemListeners[i]) + .build())); } return items; }
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index ca1f8193..e83104c 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -4311,6 +4311,12 @@ <message name="IDS_EXTENSIONS_MENU_CONTEXT_MENU_TOOLTIP" desc="Title of the context menu for individual extensions in the Extensions Menu"> More actions </message> + <message name="IDS_EXTENSIONS_MENU_PIN_BUTTON_TOOLTIP" desc="The tooltip for the pinning button for individual extensions in the Extensions Menu"> + Pin extension + </message> + <message name="IDS_EXTENSIONS_MENU_UNPIN_BUTTON_TOOLTIP" desc="The tooltip for the pinning button for individual extensions in the Extensions Menu"> + Unpin extension + </message> <message name="IDS_EXTENSIONS_MENU_ACCESSING_SITE_DATA" desc="Header for section of extensions that are able to access the current site's data"> Accessing this site's data </message>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 2c4cebe2..86fe1c3 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -329,6 +329,8 @@ "component_updater/recovery_improved_component_installer.h", "component_updater/safety_tips_component_installer.cc", "component_updater/safety_tips_component_installer.h", + "component_updater/ssl_error_assistant_component_installer.cc", + "component_updater/ssl_error_assistant_component_installer.h", "component_updater/sth_set_component_remover.cc", "component_updater/sth_set_component_remover.h", "component_updater/subresource_filter_component_installer.cc", @@ -529,8 +531,6 @@ "geolocation/geolocation_permission_context_extensions.h", "global_keyboard_shortcuts_mac.h", "global_keyboard_shortcuts_mac.mm", - "google/chrome_google_url_tracker_client.cc", - "google/chrome_google_url_tracker_client.h", "google/did_run_updater_win.cc", "google/did_run_updater_win.h", "google/google_brand.cc", @@ -539,8 +539,6 @@ "google/google_search_domain_mixing_metrics_emitter.h", "google/google_search_domain_mixing_metrics_emitter_factory.cc", "google/google_search_domain_mixing_metrics_emitter_factory.h", - "google/google_url_tracker_factory.cc", - "google/google_url_tracker_factory.h", "gpu/gpu_mode_manager.cc", "gpu/gpu_mode_manager.h", "hang_monitor/hang_crash_dump.h", @@ -1053,6 +1051,7 @@ "performance_manager/decorators/page_almost_idle_decorator.cc", "performance_manager/decorators/page_almost_idle_decorator.h", "performance_manager/frame_priority/frame_priority.cc", + "performance_manager/frame_priority/override_vote_aggregator.cc", "performance_manager/graph/frame_node.cc", "performance_manager/graph/frame_node_impl.cc", "performance_manager/graph/frame_node_impl.h", @@ -1134,6 +1133,7 @@ "performance_manager/persistence/site_data/site_data_writer.h", "performance_manager/persistence/site_data/tab_visibility.h", "performance_manager/public/frame_priority/frame_priority.h", + "performance_manager/public/frame_priority/override_vote_aggregator.h", "performance_manager/public/graph/frame_node.h", "performance_manager/public/graph/graph.h", "performance_manager/public/graph/graph_operations.h", @@ -4245,8 +4245,6 @@ "captive_portal/captive_portal_tab_helper.h", "captive_portal/captive_portal_tab_reloader.cc", "captive_portal/captive_portal_tab_reloader.h", - "component_updater/ssl_error_assistant_component_installer.cc", - "component_updater/ssl_error_assistant_component_installer.h", "ssl/captive_portal_metrics_recorder.cc", "ssl/captive_portal_metrics_recorder.h", ] @@ -4821,7 +4819,7 @@ ] public_deps += [ - "//components/google/core/browser", + "//components/google/core/common", "//components/rlz", "//rlz:rlz_lib", ]
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 1198f7f5..1c5a794 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3097,12 +3097,6 @@ FEATURE_VALUE_TYPE(chrome_pdf::features::kSaveEditedPDFForm)}, #endif // BUILDFLAG(ENABLE_PDF) -#if BUILDFLAG(ENABLE_PLUGINS) - {"pdf-isolation", flag_descriptions::kPdfIsolationName, - flag_descriptions::kPdfIsolationDescription, kOsDesktop, - FEATURE_VALUE_TYPE(features::kPdfIsolation)}, -#endif // BUILDFLAG(ENABLE_PLUGINS) - #if BUILDFLAG(ENABLE_PRINTING) {"use-pdf-compositor-service-for-print", flag_descriptions::kUsePdfCompositorServiceName, @@ -3495,8 +3489,7 @@ #if defined(OS_CHROMEOS) {"enable-vaapi-jpeg-image-decode-acceleration", flag_descriptions::kVaapiJpegImageDecodeAccelerationName, - flag_descriptions::kVaapiJpegImageDecodeAccelerationDescription, - kOsCrOS | kExpireM77, + flag_descriptions::kVaapiJpegImageDecodeAccelerationDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kVaapiJpegImageDecodeAcceleration)}, {"enable-vaapi-webp-image-decode-acceleration",
diff --git a/chrome/browser/android/bookmarks/bookmark_bridge.cc b/chrome/browser/android/bookmarks/bookmark_bridge.cc index 96fd4143..8968534 100644 --- a/chrome/browser/android/bookmarks/bookmark_bridge.cc +++ b/chrome/browser/android/bookmarks/bookmark_bridge.cc
@@ -638,7 +638,14 @@ long bookmark_id = JavaBookmarkIdGetId(env, j_bookmark_id_obj); int type = JavaBookmarkIdGetType(env, j_bookmark_id_obj); const BookmarkNode* node = GetNodeByID(bookmark_id, type); - DCHECK(IsEditable(node)); + + // TODO(twellington): Switch back to a DCHECK after debugging + // why this is called with an uneditable node. + // See https://crbug.com/981172. + if (!IsEditable(node)) { + NOTREACHED(); + return; + } if (partner_bookmarks_shim_->IsPartnerBookmark(node)) partner_bookmarks_shim_->RemoveBookmark(node);
diff --git a/chrome/browser/android/compositor/tab_content_manager.cc b/chrome/browser/android/compositor/tab_content_manager.cc index 8b55817..8478551 100644 --- a/chrome/browser/android/compositor/tab_content_manager.cc +++ b/chrome/browser/android/compositor/tab_content_manager.cc
@@ -412,6 +412,12 @@ thumbnail_cache_->SetCaptureMinRequestTimeForTesting(timeMs); } +jint TabContentManager::GetPendingReadbacksForTesting( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj) { + return pending_tab_readbacks_.size(); +} + // ---------------------------------------------------------------------------- // Native JNI methods // ----------------------------------------------------------------------------
diff --git a/chrome/browser/android/compositor/tab_content_manager.h b/chrome/browser/android/compositor/tab_content_manager.h index 46633da0..4613aaf8 100644 --- a/chrome/browser/android/compositor/tab_content_manager.h +++ b/chrome/browser/android/compositor/tab_content_manager.h
@@ -115,6 +115,9 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jint timeMs); + jint GetPendingReadbacksForTesting( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); // ThumbnailCacheObserver implementation; void OnFinishedThumbnailRead(TabId tab_id) override;
diff --git a/chrome/browser/android/locale/locale_template_url_loader_unittest.cc b/chrome/browser/android/locale/locale_template_url_loader_unittest.cc index 6249dda..d41a7ce8 100644 --- a/chrome/browser/android/locale/locale_template_url_loader_unittest.cc +++ b/chrome/browser/android/locale/locale_template_url_loader_unittest.cc
@@ -127,24 +127,3 @@ ASSERT_EQ(TemplateURLPrepopulateData::google.id, model()->GetDefaultSearchProvider()->prepopulate_id()); } - -TEST_F(LocaleTemplateUrlLoaderTest, ChangedGoogleBaseURL) { - test_util()->VerifyLoad(); - auto google_keyword = base::ASCIIToUTF16("google.com"); - ASSERT_THAT(model()->GetTemplateURLForKeyword(google_keyword), - testing::NotNull()); - test_util()->SetGoogleBaseURL(GURL("http://google.de")); - - // After changing the base URL, the previous google keyword will no longer - // match. - ASSERT_EQ(nullptr, model()->GetTemplateURLForKeyword(google_keyword)); - - ASSERT_TRUE(loader()->LoadTemplateUrls(nullptr)); - - auto template_urls = model()->GetTemplateURLs(); - ASSERT_EQ(1, std::count_if(template_urls.begin(), template_urls.end(), - [](TemplateURL* template_url) { - return template_url->prepopulate_id() == - TemplateURLPrepopulateData::google.id; - })); -}
diff --git a/chrome/browser/android/search_permissions/search_geolocation_disclosure_tab_helper.cc b/chrome/browser/android/search_permissions/search_geolocation_disclosure_tab_helper.cc index 23491cd2b..86c9482f 100644 --- a/chrome/browser/android/search_permissions/search_geolocation_disclosure_tab_helper.cc +++ b/chrome/browser/android/search_permissions/search_geolocation_disclosure_tab_helper.cc
@@ -202,8 +202,7 @@ const TemplateURL* template_url = template_url_service->GetDefaultSearchProvider(); return template_url && - template_url->HasGoogleBaseURLs( - UIThreadSearchTermsData(GetProfile())) && + template_url->HasGoogleBaseURLs(UIThreadSearchTermsData()) && template_url_service->IsSearchResultsPageFromDefaultSearchProvider( gurl); }
diff --git a/chrome/browser/android/vr/arcore_device/OWNERS b/chrome/browser/android/vr/arcore_device/OWNERS index efd7758..784b0cd 100644 --- a/chrome/browser/android/vr/arcore_device/OWNERS +++ b/chrome/browser/android/vr/arcore_device/OWNERS
@@ -1,5 +1,4 @@ bialpio@chromium.org -billorr@chromium.org ddorwin@chromium.org klausw@chromium.org
diff --git a/chrome/browser/autocomplete/shortcuts_backend_factory.cc b/chrome/browser/autocomplete/shortcuts_backend_factory.cc index 6a103df..5d1d2f1 100644 --- a/chrome/browser/autocomplete/shortcuts_backend_factory.cc +++ b/chrome/browser/autocomplete/shortcuts_backend_factory.cc
@@ -92,7 +92,7 @@ bool suppress_db) { scoped_refptr<ShortcutsBackend> backend(new ShortcutsBackend( TemplateURLServiceFactory::GetForProfile(profile), - std::make_unique<UIThreadSearchTermsData>(profile), + std::make_unique<UIThreadSearchTermsData>(), HistoryServiceFactory::GetForProfile(profile, ServiceAccessType::EXPLICIT_ACCESS), profile->GetPath().Append(kShortcutsDatabaseName), suppress_db));
diff --git a/chrome/browser/autofill/autofill_uitest.cc b/chrome/browser/autofill/autofill_uitest.cc index 17876bd..6c2fe45 100644 --- a/chrome/browser/autofill/autofill_uitest.cc +++ b/chrome/browser/autofill/autofill_uitest.cc
@@ -91,7 +91,9 @@ void AutofillUiTest::TearDownOnMainThread() { // Make sure to close any showing popups prior to tearing down the UI. - GetAutofillManager()->client()->HideAutofillPopup(); + AutofillManager* autofill_manager = GetAutofillManager(); + if (autofill_manager) + autofill_manager->client()->HideAutofillPopup(); test::ReenableSystemServices(); } @@ -222,9 +224,15 @@ } AutofillManager* AutofillUiTest::GetAutofillManager() { - return ContentAutofillDriverFactory::FromWebContents(GetWebContents()) - ->DriverForFrame(current_main_rfh_) - ->autofill_manager(); + ContentAutofillDriver* driver = + ContentAutofillDriverFactory::FromWebContents(GetWebContents()) + ->DriverForFrame(current_main_rfh_); + // ContentAutofillDriver will be null if the current RenderFrameHost + // is not owned by the current WebContents. This state appears to occur + // when there is a web page popup during teardown + if (!driver) + return nullptr; + return driver->autofill_manager(); } void AutofillUiTest::RenderFrameHostChanged( @@ -233,7 +241,9 @@ if (current_main_rfh_ != old_frame) return; current_main_rfh_ = new_frame; - GetAutofillManager()->SetTestDelegate(test_delegate()); + AutofillManager* autofill_manager = GetAutofillManager(); + if (autofill_manager) + autofill_manager->SetTestDelegate(test_delegate()); } } // namespace autofill
diff --git a/chrome/browser/availability/availability_prober.cc b/chrome/browser/availability/availability_prober.cc index d51b9b8c..22df74e 100644 --- a/chrome/browser/availability/availability_prober.cc +++ b/chrome/browser/availability/availability_prober.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/availability/availability_prober.h" #include <math.h> + #include <cmath> #include "base/base64.h" @@ -347,6 +348,19 @@ CreateAndStartURLLoader(); } +void AvailabilityProber::RepeatedlyProbe(base::TimeDelta interval, + bool send_only_in_foreground) { + repeating_timer_ = std::make_unique<base::RepeatingTimer>(tick_clock_); + // base::Unretained is safe here because |repeating_timer_| is owned by + // |this|. + repeating_timer_->Start( + FROM_HERE, interval, + base::BindRepeating(&AvailabilityProber::SendNowIfInactive, + base::Unretained(this), send_only_in_foreground)); + + SendNowIfInactive(send_only_in_foreground); +} + #if defined(OS_ANDROID) void AvailabilityProber::OnApplicationStateChange( base::android::ApplicationState new_state) {
diff --git a/chrome/browser/availability/availability_prober.h b/chrome/browser/availability/availability_prober.h index 43706f06..d71636db 100644 --- a/chrome/browser/availability/availability_prober.h +++ b/chrome/browser/availability/availability_prober.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_AVAILABILITY_AVAILABILITY_PROBER_H_ #include <stdint.h> + #include <memory> #include <string> @@ -156,6 +157,12 @@ // is in the foreground (work on Android only). void SendNowIfInactive(bool send_only_in_foreground); + // Calls |SendNowIfInactive| immediately with |send_only_in_foreground| and + // repeats every |interval|. Calling this multiple times with different + // |interval| will change the interval to the most recently provided value. + // Only stops when |this| is deleted. + void RepeatedlyProbe(base::TimeDelta interval, bool send_only_in_foreground); + // Returns the successfulness of the last probe, if there was one. If the last // probe status was cached and needs to be revalidated, this may activate the // prober. @@ -254,6 +261,9 @@ // If a probe is being attempted, this will be running until the TTL. std::unique_ptr<base::OneShotTimer> timeout_timer_; + // If we are repeatedly probing, this will be running. + std::unique_ptr<base::RepeatingTimer> repeating_timer_; + // Caches past probe results in a mapping of one tuple to another: // (network_id, url_) -> (last_probe_status, last_modification_time). // No more than |max_cache_entries_| will be kept in this dictionary.
diff --git a/chrome/browser/availability/availability_prober_unittest.cc b/chrome/browser/availability/availability_prober_unittest.cc index dbe56dd..05c5aad2 100644 --- a/chrome/browser/availability/availability_prober_unittest.cc +++ b/chrome/browser/availability/availability_prober_unittest.cc
@@ -851,3 +851,24 @@ histogram_tester.ExpectTotalCount( "Availability.Prober.CacheEntryAge.Litepages", 2); } + +TEST_F(AvailabilityProberTest, Repeating) { + base::HistogramTester histogram_tester; + + std::unique_ptr<AvailabilityProber> prober = NewProber(); + EXPECT_EQ(prober->LastProbeWasSuccessful(), base::nullopt); + + prober->RepeatedlyProbe(base::TimeDelta::FromSeconds(1), false); + VerifyRequest(); + MakeResponseAndWait(net::HTTP_OK, net::OK); + EXPECT_TRUE(prober->LastProbeWasSuccessful().value()); + EXPECT_FALSE(prober->is_active()); + + FastForward(base::TimeDelta::FromSeconds(1)); + EXPECT_TRUE(prober->is_active()); + + VerifyRequest(); + MakeResponseAndWait(net::HTTP_OK, net::OK); + EXPECT_TRUE(prober->LastProbeWasSuccessful().value()); + EXPECT_FALSE(prober->is_active()); +}
diff --git a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc index 8593d1f..bd70b83 100644 --- a/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/cache_counter_browsertest.cc
@@ -174,8 +174,8 @@ EXPECT_EQ(0u, GetResult()); } -// TODO(crbug.com/985131): Test is flaky in Linux component builds. -#if defined(OS_LINUX) && defined(COMPONENT_BUILD) +// TODO(crbug.com/985131): Test is flaky in Linux, Win and ChromeOS. +#if defined(OS_LINUX) || defined(OS_WIN) || defined(OS_CHROMEOS) #define MAYBE_PrefChanged DISABLED_PrefChanged #else #define MAYBE_PrefChanged PrefChanged
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index 3f4cf14d..084f7416 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -62,6 +62,7 @@ #include "chrome/browser/component_updater/origin_trials_component_installer.h" #include "chrome/browser/component_updater/pepper_flash_component_installer.h" #include "chrome/browser/component_updater/safety_tips_component_installer.h" +#include "chrome/browser/component_updater/ssl_error_assistant_component_installer.h" #include "chrome/browser/component_updater/sth_set_component_remover.h" #include "chrome/browser/component_updater/subresource_filter_component_installer.h" #include "chrome/browser/defaults.h" @@ -275,10 +276,6 @@ #include "chrome/browser/background/background_mode_manager.h" #endif // BUILDFLAG(ENABLE_BACKGROUND_MODE) -#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION) -#include "chrome/browser/component_updater/ssl_error_assistant_component_installer.h" -#endif // BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION) - #if BUILDFLAG(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/startup_helper.h" #include "extensions/browser/extension_protocols.h" @@ -525,9 +522,7 @@ RegisterFileTypePoliciesComponent(cus, path); -#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION) RegisterSSLErrorAssistantComponent(cus, path); -#endif } RegisterMediaEngagementPreloadComponent(cus, base::OnceClosure());
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index fd1d0ba..95a7177b 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -477,10 +477,14 @@ "arc/boot_phase_monitor/arc_instance_throttle.h", "arc/cast_receiver/arc_cast_receiver_service.cc", "arc/cast_receiver/arc_cast_receiver_service.h", - "arc/enterprise/arc_cert_store_bridge.cc", - "arc/enterprise/arc_cert_store_bridge.h", "arc/enterprise/arc_enterprise_reporting_service.cc", "arc/enterprise/arc_enterprise_reporting_service.h", + "arc/enterprise/cert_store/arc_cert_installer.cc", + "arc/enterprise/cert_store/arc_cert_installer.h", + "arc/enterprise/cert_store/arc_cert_installer_utils.cc", + "arc/enterprise/cert_store/arc_cert_installer_utils.h", + "arc/enterprise/cert_store/arc_cert_store_bridge.cc", + "arc/enterprise/cert_store/arc_cert_store_bridge.h", "arc/extensions/arc_support_message_host.cc", "arc/extensions/arc_support_message_host.h", "arc/file_system_watcher/arc_file_system_watcher_service.cc", @@ -1964,6 +1968,8 @@ "settings/stats_reporting_controller.h", "settings/stub_cros_settings_provider.cc", "settings/stub_cros_settings_provider.h", + "settings/supervised_user_cros_settings_provider.cc", + "settings/supervised_user_cros_settings_provider.h", "settings/token_encryptor.cc", "settings/token_encryptor.h", "smb_client/discovery/host_locator.h", @@ -2343,6 +2349,8 @@ "arc/bluetooth/arc_bluetooth_bridge_unittest.cc", "arc/bluetooth/arc_bluetooth_task_queue_unittest.cc", "arc/boot_phase_monitor/arc_boot_phase_monitor_bridge_unittest.cc", + "arc/enterprise/cert_store/arc_cert_installer_unittest.cc", + "arc/enterprise/cert_store/arc_cert_installer_utils_unittest.cc", "arc/extensions/arc_support_message_host_unittest.cc", "arc/file_system_watcher/arc_file_system_watcher_service_unittest.cc", "arc/fileapi/arc_content_file_system_async_file_util_unittest.cc",
diff --git a/chrome/browser/chromeos/accessibility/accessibility_panel.cc b/chrome/browser/chromeos/accessibility/accessibility_panel.cc index ee41339..d4bc7328 100644 --- a/chrome/browser/chromeos/accessibility/accessibility_panel.cc +++ b/chrome/browser/chromeos/accessibility/accessibility_panel.cc
@@ -67,7 +67,7 @@ params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; params.name = widget_name; params.shadow_elevation = wm::kShadowElevationInactiveWindow; - widget_->Init(params); + widget_->Init(std::move(params)); } AccessibilityPanel::~AccessibilityPanel() = default;
diff --git a/chrome/browser/chromeos/arc/arc_service_launcher.cc b/chrome/browser/chromeos/arc/arc_service_launcher.cc index ea89dbe..b97db77 100644 --- a/chrome/browser/chromeos/arc/arc_service_launcher.cc +++ b/chrome/browser/chromeos/arc/arc_service_launcher.cc
@@ -21,8 +21,8 @@ #include "chrome/browser/chromeos/arc/bluetooth/arc_bluetooth_bridge.h" #include "chrome/browser/chromeos/arc/boot_phase_monitor/arc_boot_phase_monitor_bridge.h" #include "chrome/browser/chromeos/arc/cast_receiver/arc_cast_receiver_service.h" -#include "chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h" #include "chrome/browser/chromeos/arc/enterprise/arc_enterprise_reporting_service.h" +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h" #include "chrome/browser/chromeos/arc/file_system_watcher/arc_file_system_watcher_service.h" #include "chrome/browser/chromeos/arc/fileapi/arc_file_system_bridge.h" #include "chrome/browser/chromeos/arc/fileapi/arc_file_system_mounter.h"
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.cc new file mode 100644 index 0000000..b8b898f --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.cc
@@ -0,0 +1,155 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.h" + +#include <cert.h> + +#include <utility> + +#include "base/base64.h" +#include "base/bind.h" +#include "base/callback.h" +#include "base/logging.h" +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h" +#include "chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h" +#include "chrome/browser/net/nss_context.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/common/net/x509_certificate_model_nss.h" +#include "net/cert/x509_util_nss.h" + +namespace arc { + +ArcCertInstaller::ArcCertInstaller(content::BrowserContext* context) + : ArcCertInstaller(Profile::FromBrowserContext(context), + std::make_unique<policy::RemoteCommandsQueue>()) {} + +ArcCertInstaller::ArcCertInstaller( + Profile* profile, + std::unique_ptr<policy::RemoteCommandsQueue> queue) + : profile_(profile), queue_(std::move(queue)), weak_ptr_factory_(this) { + VLOG(1) << "ArcCertInstaller::ArcCertInstaller"; + + queue_->AddObserver(this); +} + +ArcCertInstaller::~ArcCertInstaller() { + VLOG(1) << "ArcCertInstaller::~ArcCertInstaller"; + + queue_->RemoveObserver(this); +} + +void ArcCertInstaller::InstallArcCerts( + const std::vector<net::ScopedCERTCertificate>& certificates, + InstallArcCertsCallback callback) { + VLOG(1) << "ArcCertInstaller::InstallArcCerts"; + + if (callback_) { + LOG(WARNING) << "The last ARC cert installation has not finished before " + << "starting a new one."; + std::move(callback_).Run(false /* result */); + pending_status_ = true; + } + + required_cert_names_.clear(); + callback_ = std::move(callback); + + for (const auto& nss_cert : certificates) { + if (!nss_cert) { + LOG(ERROR) + << "An invalid certificate has been passed to ArcCertInstaller"; + continue; + } + + std::string cert_name = + x509_certificate_model::GetCertNameOrNickname(nss_cert.get()); + + InstallArcCert(cert_name, nss_cert); + } + + // Cleanup |known_cert_names_| according to |required_cert_names_|. + for (auto it = known_cert_names_.begin(); it != known_cert_names_.end();) { + auto cert_name = it++; + if (!required_cert_names_.count(*cert_name)) + known_cert_names_.erase(cert_name); + } + + if (pending_commands_.empty() && callback_) { + std::move(callback_).Run(pending_status_); + pending_status_ = true; + } +} + +void ArcCertInstaller::InstallArcCert( + const std::string& name, + const net::ScopedCERTCertificate& nss_cert) { + VLOG(1) << "ArcCertInstaller::InstallArcCert " << name; + required_cert_names_.insert(name); + + // Do not install certificate if already exists. + if (known_cert_names_.count(name)) + return; + + std::string der_cert; + if (!net::x509_util::GetDEREncoded(nss_cert.get(), &der_cert)) { + LOG(ERROR) << "Certificate encoding error: " << name; + return; + } + known_cert_names_.insert(name); + + // Install certificate. + std::unique_ptr<policy::RemoteCommandJob> job = + std::make_unique<policy::UserCommandArcJob>(profile_); + enterprise_management::RemoteCommand command_proto; + command_proto.set_type( + enterprise_management::RemoteCommand_Type_USER_ARC_COMMAND); + + command_proto.set_command_id(next_id_); + command_proto.set_age_of_command(0); + + std::string der_cert64; + base::Base64Encode(der_cert, &der_cert64); + command_proto.set_payload(base::StringPrintf( + "{\"type\":\"INSTALL_KEY_PAIR\"," + "\"payload\":\"{" + "\\\"key\\\"=\\\"%s\\\"," + "\\\"alias\\\":\\\"%s\\\"," + "\\\"certs\\\":[\\\"%s\\\"]}\"}", + CreatePkcs12FromBlob(name).c_str(), name.c_str(), der_cert64.c_str())); + if (!job || !job->Init(queue_->GetNowTicks(), command_proto)) { + LOG(ERROR) << "Initialization of remote command failed"; + known_cert_names_.erase(name); + } else { + pending_commands_[next_id_++] = name; + queue_->AddJob(std::move(job)); + } +} + +void ArcCertInstaller::OnJobFinished(policy::RemoteCommandJob* command) { + if (!pending_commands_.count(command->unique_id())) { + LOG(ERROR) << "Received invalid ARC remote command with unrecognized " + << "unique_id = " << command->unique_id(); + return; + } + + // If the cert installation is failed, save the status and remove from the + // |known_cert_names_| to be able to re-try the installation when the + // |Refresh| is called again. + if (command->status() != policy::RemoteCommandJob::Status::SUCCEEDED) { + LOG(ERROR) << "Failed to install certificate " + << pending_commands_[command->unique_id()]; + if (known_cert_names_.count(pending_commands_[command->unique_id()])) { + known_cert_names_.erase(pending_commands_[command->unique_id()]); + pending_status_ = false; + } + } + pending_commands_.erase(command->unique_id()); + + if (pending_commands_.empty() && callback_) { + std::move(callback_).Run(pending_status_); + pending_status_ = true; + } +} + +} // namespace arc
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.h b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.h new file mode 100644 index 0000000..01021379 --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.h
@@ -0,0 +1,89 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_H_ +#define CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_H_ + +#include <map> +#include <set> +#include <string> + +#include "base/memory/weak_ptr.h" +#include "components/policy/core/common/remote_commands/remote_command_job.h" +#include "components/policy/core/common/remote_commands/remote_commands_queue.h" +#include "net/cert/scoped_nss_types.h" + +class Profile; + +namespace content { + +class BrowserContext; + +} // namespace content + +namespace arc { + +// This class manages the certificates, available to ARC. +// It keeps track of the certificates and installs missing ones via +// ARC remote commands. +class ArcCertInstaller : public policy::RemoteCommandsQueue::Observer { + public: + ArcCertInstaller(content::BrowserContext* context); + + // This constructor should be used only for testing. + ArcCertInstaller(Profile* profile, + std::unique_ptr<policy::RemoteCommandsQueue> queue); + ~ArcCertInstaller() override; + + using InstallArcCertsCallback = base::OnceCallback<void(bool result)>; + + // Install missing certificates via ARC remote commands. + // Return false via |callback| in case of any error, and true otherwise. + void InstallArcCerts(const std::vector<net::ScopedCERTCertificate>& certs, + InstallArcCertsCallback callback); + + private: + // Install ARC certificate if not installed yet. + void InstallArcCert(const std::string& name, + const net::ScopedCERTCertificate& nss_cert); + + // RemoteCommandsQueue::Observer overrides: + void OnJobStarted(policy::RemoteCommandJob* command) override {} + void OnJobFinished(policy::RemoteCommandJob* command) override; + + Profile* profile_; // not owned + + // A valid callback when the caller of |InstallArcCerts| method is awaiting + // for a response. + InstallArcCertsCallback callback_; + + // Status of a pending certificate installation query. + // True by default. + // False if the installation failed. + // The |pending_status_| is returned via |callback_|. + bool pending_status_ = true; + + // Names of certificates required to be installed on ARC. + std::set<std::string> required_cert_names_; + + // Names of certificates installed or pending to be installed on ARC. + std::set<std::string> known_cert_names_; + + // Map from unique_id of the remote command to the corresponding cert name. + std::map<int, std::string> pending_commands_; + + // Remote commands queue. + std::unique_ptr<policy::RemoteCommandsQueue> queue_; + + // The next remote command unique id. Should be increased after every usage. + int next_id_ = 1; + + base::WeakPtrFactory<ArcCertInstaller> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(ArcCertInstaller); +}; + +} // namespace arc + +#endif // CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_H_
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_unittest.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_unittest.cc new file mode 100644 index 0000000..2fcc785 --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_unittest.cc
@@ -0,0 +1,329 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer.h" + +#include <string> +#include <vector> + +#include "base/run_loop.h" +#include "base/strings/stringprintf.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/time/time.h" +#include "chrome/browser/chromeos/arc/policy/arc_policy_bridge.h" +#include "chrome/test/base/testing_profile.h" +#include "components/arc/arc_service_manager.h" +#include "components/arc/common/policy.mojom.h" +#include "components/arc/session/arc_bridge_service.h" +#include "components/arc/test/fake_policy_instance.h" +#include "components/policy/core/common/remote_commands/remote_commands_queue.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "crypto/rsa_private_key.h" +#include "net/cert/scoped_nss_types.h" +#include "net/cert/x509_util.h" +#include "net/cert/x509_util_nss.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace arc { + +using testing::_; +using testing::Invoke; +using testing::StrictMock; +using testing::WithArg; + +namespace { + +MATCHER_P(IsCommandPayloadForName, name, "") { + constexpr char kAliasFormat[] = "\\\"alias\\\":\\\"%s\\\""; + return arg.find(base::StringPrintf(kAliasFormat, name.c_str())) != + std::string::npos; +} + +MATCHER_P(IsCommandWithStatus, status, "") { + return arg->status() == status; +} + +constexpr char kCNFormat[] = "CN=%s"; +constexpr char kFakeName1[] = "fake1"; +constexpr char kFakeName2[] = "fake2"; +constexpr char kFakeName3[] = "fake3"; + +class MockRemoteCommandsQueueObserver + : public StrictMock<policy::RemoteCommandsQueue::Observer> { + public: + MOCK_METHOD1(OnJobStarted, void(policy::RemoteCommandJob* command)); + MOCK_METHOD1(OnJobFinished, void(policy::RemoteCommandJob* command)); +}; + +class MockPolicyInstance : public FakePolicyInstance { + public: + MOCK_METHOD2(OnCommandReceived, + void(const std::string& command, + OnCommandReceivedCallback callback)); +}; + +void AddCert(const std::string& cn, + std::vector<net::ScopedCERTCertificate>* certs) { + std::string der_cert; + net::ScopedCERTCertificate cert; + std::unique_ptr<crypto::RSAPrivateKey> key( + crypto::RSAPrivateKey::Create(1024)); + + ASSERT_TRUE(net::x509_util::CreateSelfSignedCert( + key->key(), net::x509_util::DIGEST_SHA256, cn, 1, base::Time::UnixEpoch(), + base::Time::UnixEpoch(), {}, &der_cert)); + cert = net::x509_util::CreateCERTCertificateFromBytes( + reinterpret_cast<const uint8_t*>(der_cert.data()), der_cert.size()); + ASSERT_TRUE(cert); + certs->push_back(std::move(cert)); +} + +} // namespace + +class ArcCertInstallerTest : public testing::Test { + public: + ArcCertInstallerTest() + : arc_service_manager_(std::make_unique<arc::ArcServiceManager>()), + profile_(std::make_unique<TestingProfile>()), + arc_policy_bridge_(arc::ArcPolicyBridge::GetForBrowserContextForTesting( + profile_.get())), + policy_instance_(std::make_unique<arc::MockPolicyInstance>()) { + arc_service_manager_->arc_bridge_service()->policy()->SetInstance( + policy_instance_.get()); + } + + ~ArcCertInstallerTest() override { + arc_service_manager_->arc_bridge_service()->policy()->CloseInstance( + policy_instance_.get()); + } + + void SetUp() override { + auto mock_queue = std::make_unique<policy::RemoteCommandsQueue>(); + queue_ = mock_queue.get(); + installer_ = + std::make_unique<ArcCertInstaller>(profile(), std::move(mock_queue)); + queue_->AddObserver(&observer_); + } + + void TearDown() override { + queue_->RemoveObserver(&observer_); + installer_.reset(); + queue_ = nullptr; + } + + void ExpectArcCommandForName(const std::string& name, + mojom::CommandResultType status) { + EXPECT_CALL(*policy_instance_.get(), + OnCommandReceived(IsCommandPayloadForName(name), _)) + .WillOnce(WithArg<1>(Invoke( + [status](FakePolicyInstance::OnCommandReceivedCallback callback) { + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), status)); + }))); + } + + Profile* profile() { return profile_.get(); } + ArcCertInstaller* installer() { return installer_.get(); } + MockRemoteCommandsQueueObserver* observer() { return &observer_; } + + private: + content::TestBrowserThreadBundle browser_thread_bundle_; + + // ArcServiceManager needs to be created before ArcPolicyBridge (since the + // Bridge depends on the Manager), and it needs to be destroyed after Profile + // (because BrowserContextKeyedServices are destroyed together with Profile, + // and ArcPolicyBridge is such a service). + const std::unique_ptr<arc::ArcServiceManager> arc_service_manager_; + const std::unique_ptr<TestingProfile> profile_; + arc::ArcPolicyBridge* const arc_policy_bridge_; + const std::unique_ptr<arc::MockPolicyInstance> policy_instance_; + + policy::RemoteCommandsQueue* queue_; + std::unique_ptr<ArcCertInstaller> installer_; + MockRemoteCommandsQueueObserver observer_; + + DISALLOW_COPY_AND_ASSIGN(ArcCertInstallerTest); +}; + +// Tests that installation of an empty cert list completes successfully. +TEST_F(ArcCertInstallerTest, NoCertsTest) { + installer()->InstallArcCerts( + std::vector<net::ScopedCERTCertificate>(), + base::BindOnce([](bool result) { EXPECT_TRUE(result); })); +} + +// Tests that installing certs completes successfully if there are two certs +// available. +TEST_F(ArcCertInstallerTest, BasicCertTest) { + std::vector<net::ScopedCERTCertificate> certs; + + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + AddCert(base::StringPrintf(kCNFormat, kFakeName2), &certs); + + ExpectArcCommandForName(kFakeName1, mojom::CommandResultType::SUCCESS); + ExpectArcCommandForName(kFakeName2, mojom::CommandResultType::SUCCESS); + EXPECT_CALL(*observer(), OnJobStarted(IsCommandWithStatus( + policy::RemoteCommandJob::Status::RUNNING))) + .Times(2); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::SUCCEEDED))) + .Times(2); + + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_TRUE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); +} + +// Tests that consequent calls complete successfully and install each cert once +// (3 times in total for 3 distinct certs). +TEST_F(ArcCertInstallerTest, ConsequentInstallTest) { + ExpectArcCommandForName(kFakeName1, mojom::CommandResultType::SUCCESS); + ExpectArcCommandForName(kFakeName2, mojom::CommandResultType::SUCCESS); + EXPECT_CALL(*observer(), OnJobStarted(IsCommandWithStatus( + policy::RemoteCommandJob::Status::RUNNING))) + .Times(3); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::SUCCEEDED))) + .Times(3); + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + AddCert(base::StringPrintf(kCNFormat, kFakeName2), &certs); + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_TRUE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + } + + ExpectArcCommandForName(kFakeName3, mojom::CommandResultType::SUCCESS); + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + AddCert(base::StringPrintf(kCNFormat, kFakeName3), &certs); + + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_TRUE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + } +} + +// Tests that starting the second cert installation before finishing the +// first one fails. +TEST_F(ArcCertInstallerTest, FailureIncompleteInstallationTest) { + ExpectArcCommandForName(kFakeName1, mojom::CommandResultType::SUCCESS); + EXPECT_CALL(*observer(), OnJobStarted(IsCommandWithStatus( + policy::RemoteCommandJob::Status::RUNNING))); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::SUCCEEDED))); + + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + + installer()->InstallArcCerts(std::move(certs), + base::BindOnce([](bool result) { + // The first installation has not finished + // before the second started. + EXPECT_FALSE(result); + })); + } + + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_TRUE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + } +} + +// Tests the failed certificate installation. +TEST_F(ArcCertInstallerTest, FailedRequiredSmartCardTest) { + ExpectArcCommandForName(kFakeName1, mojom::CommandResultType::FAILURE); + EXPECT_CALL(*observer(), OnJobStarted(IsCommandWithStatus( + policy::RemoteCommandJob::Status::RUNNING))); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::FAILED))); + + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_FALSE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); +} + +// Tests that the failed installation does not fail the consequent operation +// if the cert is no longer required. +TEST_F(ArcCertInstallerTest, FailiedNotRequiredSmartCardTest) { + EXPECT_CALL(*observer(), OnJobStarted(IsCommandWithStatus( + policy::RemoteCommandJob::Status::RUNNING))) + .Times(2); + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName1), &certs); + + installer()->InstallArcCerts(std::move(certs), + base::BindOnce([](bool result) { + // The first installation has not finished + // before the second started. + EXPECT_FALSE(result); + })); + } + + ExpectArcCommandForName(kFakeName1, mojom::CommandResultType::FAILURE); + ExpectArcCommandForName(kFakeName2, mojom::CommandResultType::SUCCESS); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::SUCCEEDED))); + EXPECT_CALL(*observer(), OnJobFinished(IsCommandWithStatus( + policy::RemoteCommandJob::Status::FAILED))); + + { + std::vector<net::ScopedCERTCertificate> certs; + AddCert(base::StringPrintf(kCNFormat, kFakeName2), &certs); + + base::RunLoop run_loop; + installer()->InstallArcCerts(std::move(certs), + base::BindOnce( + [](base::RunLoop* run_loop, bool result) { + EXPECT_TRUE(result); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + } +} + +} // namespace arc
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.cc new file mode 100644 index 0000000..80766dd --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.cc
@@ -0,0 +1,185 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h" + +#include "base/base64.h" +#include "base/logging.h" +#include "base/strings/string_piece.h" +#include "third_party/boringssl/src/include/openssl/bn.h" +#include "third_party/boringssl/src/include/openssl/evp.h" +#include "third_party/boringssl/src/include/openssl/mem.h" +#include "third_party/boringssl/src/include/openssl/pkcs8.h" + +namespace arc { + +// Creates a fake, but recognized as valid, RSA private key: +// * q = |blob| + 3 + { 4, 3, 2 } so that q % 3 = 1 +// * p = 3 +// * n = p * q +// * e = 1 +// * d = (q - 1) * (p - 1) + 1 so that d % (p - 1) * (q - 1) = 1 +// * dmp1 = 1 +// * dmq1 = 1 +// * iqmp = 1 +RSA* CreateRsaPrivateKeyFromBlob(const std::string& blob) { + const uint8_t* ptr = (const uint8_t*)blob.data(); + BIGNUM* q = BN_bin2bn(ptr, blob.size(), nullptr); + int mod3; + if (!q || !BN_add_word(q, 3) || (mod3 = BN_mod_word(q, 3)) >= 3 || + !BN_add_word(q, 4 - mod3)) { + BN_free(q); + VLOG(1) << "Failed to create q for " << blob; + return nullptr; + } + + BIGNUM* p = BN_new(); + if (!p || !BN_set_word(p, 3)) { + BN_free(q); + BN_free(p); + VLOG(1) << "Failed to create p for " << blob; + return nullptr; + } + + BIGNUM* n = BN_new(); + bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new()); + if (!n || !BN_mul(n, p, q, ctx.get())) { + BN_free(q); + BN_free(p); + BN_free(n); + VLOG(1) << "Failed to create n for " << blob; + return nullptr; + } + + BIGNUM* e = BN_new(); + if (!e || !BN_one(e)) { + BN_free(q); + BN_free(p); + BN_free(n); + BN_free(e); + VLOG(1) << "Failed to create e for " << blob; + return nullptr; + } + + BIGNUM* d = BN_new(); + if (!d || !BN_sub(d, q, BN_value_one()) || !BN_mul_word(d, 2) || + !BN_add_word(d, 1)) { + BN_free(q); + BN_free(p); + BN_free(n); + BN_free(e); + BN_free(d); + VLOG(1) << "Failed to create d for " << blob; + return nullptr; + } + + BIGNUM* dmp1 = BN_new(); + BIGNUM* dmq1 = BN_new(); + BIGNUM* iqmp = BN_new(); + if (!dmp1 || !BN_one(dmp1) || !dmq1 || !BN_one(dmq1) || !iqmp || + !BN_one(iqmp)) { + BN_free(q); + BN_free(p); + BN_free(n); + BN_free(e); + BN_free(d); + BN_free(dmp1); + BN_free(dmq1); + BN_free(iqmp); + VLOG(1) << "Failed to create dmp1 or dmq1 or iqmp for " << blob; + return nullptr; + } + + RSA* rsa = RSA_new(); + if (!rsa) { + BN_free(q); + BN_free(p); + BN_free(n); + BN_free(e); + BN_free(d); + BN_free(dmp1); + BN_free(dmq1); + BN_free(iqmp); + VLOG(1) << "Failed to create RSA key."; + return nullptr; + } + + if (!RSA_set0_key(rsa, n, e, d)) { + BN_free(q); + BN_free(p); + BN_free(n); + BN_free(e); + BN_free(d); + BN_free(dmp1); + BN_free(dmq1); + BN_free(iqmp); + RSA_free(rsa); + VLOG(1) << "Failed to set n to RSA for " << blob; + return nullptr; + } + + if (!RSA_set0_factors(rsa, p, q)) { + BN_free(q); + BN_free(p); + BN_free(dmp1); + BN_free(dmq1); + BN_free(iqmp); + RSA_free(rsa); + VLOG(1) << "Failed to set factors to RSA for " << blob; + return nullptr; + } + + if (!RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp)) { + BN_free(dmp1); + BN_free(dmq1); + BN_free(iqmp); + RSA_free(rsa); + VLOG(1) << "Failed to set crt params for " << blob; + return nullptr; + } + return rsa; +} + +std::string CreatePkcs12FromBlob(const std::string& blob) { + bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new()); + + if (!pkey) { + VLOG(1) << "Failed to generate RSA for " << blob; + return ""; + } + + RSA* rsa = CreateRsaPrivateKeyFromBlob(blob); + if (!rsa) { + return ""; + } + + if (!EVP_PKEY_assign_RSA(pkey.get(), rsa)) { + RSA_free(rsa); + VLOG(1) << "Failed to assign RSA for " << blob; + return ""; + } + + // Make a PKCS#12 blob. + bssl::UniquePtr<PKCS12> pkcs12(PKCS12_create( + nullptr, blob.c_str(), pkey.get(), nullptr, nullptr, 0, 0, 0, 0, 0)); + if (!pkcs12) { + VLOG(1) << "Failed to create PKCS12 object from pkey for " << blob; + return ""; + } + + uint8_t* key = nullptr; + int key_len; + if (!(key_len = i2d_PKCS12(pkcs12.get(), &key))) { + VLOG(1) << "Failed to translate PKCS12 to byte array for " << blob; + return ""; + } + + bssl::UniquePtr<uint8_t> free_key(key); + + std::string encoded_key; + base::Base64Encode(base::StringPiece((char*)key, key_len), &encoded_key); + return encoded_key; +} + +} // namespace arc
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h new file mode 100644 index 0000000..bd0c3f2 --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h
@@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_UTILS_H_ +#define CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_UTILS_H_ + +#include <string> + +#include "third_party/boringssl/src/include/openssl/rsa.h" + +namespace arc { + +// Creates a PKCS12 container with RSA private key, generated with p = |blob|, +// to be able to extract |blob| value from a private key material later. +// Returns empty string in case of any error. +std::string CreatePkcs12FromBlob(const std::string& blob); + +// Helper function that creates the RSA private key with p = |blob| to +// be able to extract |blob| value from a private key material later. +// Returns nullptr in case of any error. +// Should be used only for testing. +RSA* CreateRsaPrivateKeyFromBlob(const std::string& blob); + +} // namespace arc + +#endif // CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_INSTALLER_UTILS_H_
diff --git a/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils_unittest.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils_unittest.cc new file mode 100644 index 0000000..b1078c8 --- /dev/null +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils_unittest.cc
@@ -0,0 +1,155 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <string> + +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_installer_utils.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/boringssl/src/include/openssl/evp.h" +#include "third_party/boringssl/src/include/openssl/mem.h" +#include "third_party/boringssl/src/include/openssl/pkcs8.h" +#include "third_party/boringssl/src/include/openssl/rsa.h" + +namespace arc { + +namespace { + +// Keep in sync with external/boringssl/src/crypto/fipsmodule/rsa/rsa.c +int checkRsaKey(const RSA* key) { + BIGNUM n, pm1, qm1, lcm, gcd, de, dmp1, dmq1, iqmp_times_q; + BN_CTX* ctx; + int ok = 0, has_crt_values; + + if (RSA_is_opaque(key)) { + // Opaque keys can't be checked. + return 1; + } + + if ((key->p != nullptr) != (key->q != nullptr)) { + OPENSSL_PUT_ERROR(RSA, RSA_R_ONLY_ONE_OF_P_Q_GIVEN); + return 0; + } + + if (!key->n || !key->e) { + OPENSSL_PUT_ERROR(RSA, RSA_R_VALUE_MISSING); + return 0; + } + + if (!key->d || !key->p) { + // For a public key, or without p and q, there's nothing that can be + // checked. + return 1; + } + + ctx = BN_CTX_new(); + if (ctx == nullptr) { + OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE); + return 0; + } + + BN_init(&n); + BN_init(&pm1); + BN_init(&qm1); + BN_init(&lcm); + BN_init(&gcd); + BN_init(&de); + BN_init(&dmp1); + BN_init(&dmq1); + BN_init(&iqmp_times_q); + + if (!BN_mul(&n, key->p, key->q, ctx) || + // lcm = lcm(p, q) + !BN_sub(&pm1, key->p, BN_value_one()) || + !BN_sub(&qm1, key->q, BN_value_one()) || !BN_mul(&lcm, &pm1, &qm1, ctx) || + !BN_gcd(&gcd, &pm1, &qm1, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + goto out; + } + + if (!BN_div(&lcm, nullptr, &lcm, &gcd, ctx) || + !BN_gcd(&gcd, &pm1, &qm1, ctx) || + // de = d*e mod lcm(p, q). + !BN_mod_mul(&de, key->d, key->e, &lcm, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + goto out; + } + + if (BN_cmp(&n, key->n) != 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_N_NOT_EQUAL_P_Q); + goto out; + } + + if (!BN_is_one(&de)) { + OPENSSL_PUT_ERROR(RSA, RSA_R_D_E_NOT_CONGRUENT_TO_1); + goto out; + } + + has_crt_values = key->dmp1 != nullptr; + + if (has_crt_values != (key->dmq1 != nullptr) || + has_crt_values != (key->iqmp != nullptr)) { + OPENSSL_PUT_ERROR(RSA, RSA_R_INCONSISTENT_SET_OF_CRT_VALUES); + goto out; + } + + if (has_crt_values) { + if ( // dmp1 = d mod (p-1) + !BN_mod(&dmp1, key->d, &pm1, ctx) || + // dmq1 = d mod (q-1) + !BN_mod(&dmq1, key->d, &qm1, ctx) || + // iqmp = q^-1 mod p + !BN_mod_mul(&iqmp_times_q, key->iqmp, key->q, key->p, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); + goto out; + } + + if (BN_cmp(&dmp1, key->dmp1) != 0 || BN_cmp(&dmq1, key->dmq1) != 0 || + BN_cmp(key->iqmp, key->p) >= 0 || !BN_is_one(&iqmp_times_q)) { + OPENSSL_PUT_ERROR(RSA, RSA_R_CRT_VALUES_INCORRECT); + goto out; + } + } + + ok = 1; + +out: + BN_free(&n); + BN_free(&pm1); + BN_free(&qm1); + BN_free(&lcm); + BN_free(&gcd); + BN_free(&de); + BN_free(&dmp1); + BN_free(&dmq1); + BN_free(&iqmp_times_q); + BN_CTX_free(ctx); + + return ok; +} + +} // namespace + +class ArcCertInstallerUtilsTest + : public testing::Test, + public testing::WithParamInterface<std::string> {}; + +// Test that CreatePkcs12FromBlob returns non-empty PKCS12 blob with a valid +// RSA private key. +TEST_P(ArcCertInstallerUtilsTest, Pkcs12) { + const std::string name = GetParam(); + EXPECT_FALSE(CreatePkcs12FromBlob(name).empty()); + + RSA* rsa = CreateRsaPrivateKeyFromBlob(name); + ASSERT_TRUE(rsa); + EXPECT_TRUE(checkRsaKey(rsa)); + RSA_free(rsa); +} + +INSTANTIATE_TEST_SUITE_P(, + ArcCertInstallerUtilsTest, + testing::Values("", + "name of the smart card", + std::string("A", 2048))); + +} // namespace arc
diff --git a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.cc similarity index 99% rename from chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.cc rename to chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.cc index 3d1fd02c..d2a56c6 100644 --- a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.cc +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h" +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h" #include <cert.h>
diff --git a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h similarity index 92% rename from chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h rename to chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h index 7e0eed6..83e73cb 100644 --- a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_ARC_CERT_STORE_BRIDGE_H_ -#define CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_ARC_CERT_STORE_BRIDGE_H_ +#ifndef CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_STORE_BRIDGE_H_ +#define CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_STORE_BRIDGE_H_ #include <string> #include <vector> @@ -90,4 +90,4 @@ } // namespace arc -#endif // CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_ARC_CERT_STORE_BRIDGE_H_ +#endif // CHROME_BROWSER_CHROMEOS_ARC_ENTERPRISE_CERT_STORE_ARC_CERT_STORE_BRIDGE_H_
diff --git a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge_browsertest.cc similarity index 99% rename from chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc rename to chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge_browsertest.cc index 3ebbbdec..bb83cd4 100644 --- a/chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc +++ b/chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge_browsertest.cc
@@ -13,7 +13,7 @@ #include "base/run_loop.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/chromeos/arc/arc_service_launcher.h" -#include "chrome/browser/chromeos/arc/enterprise/arc_cert_store_bridge.h" +#include "chrome/browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge.h" #include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/login/test/local_policy_test_server_mixin.h" #include "chrome/browser/chromeos/platform_keys/key_permissions.h"
diff --git a/chrome/browser/chromeos/arc/print/OWNERS b/chrome/browser/chromeos/arc/print/OWNERS index bb65116..d5fefd8 100644 --- a/chrome/browser/chromeos/arc/print/OWNERS +++ b/chrome/browser/chromeos/arc/print/OWNERS
@@ -1,2 +1,2 @@ -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/chrome/browser/chromeos/arc/print/arc_print_service.cc b/chrome/browser/chromeos/arc/print/arc_print_service.cc index 687e5fa..21904aa2 100644 --- a/chrome/browser/chromeos/arc/print/arc_print_service.cc +++ b/chrome/browser/chromeos/arc/print/arc_print_service.cc
@@ -30,6 +30,7 @@ #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" +#include "components/arc/common/print_common.mojom.h" #include "components/arc/session/arc_bridge_service.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/browser_task_traits.h"
diff --git a/chrome/browser/chromeos/arc/print/print_struct_traits.cc b/chrome/browser/chromeos/arc/print/print_mojom_traits.cc similarity index 98% rename from chrome/browser/chromeos/arc/print/print_struct_traits.cc rename to chrome/browser/chromeos/arc/print/print_mojom_traits.cc index 7b6baa4..d5c93e2 100644 --- a/chrome/browser/chromeos/arc/print/print_struct_traits.cc +++ b/chrome/browser/chromeos/arc/print/print_mojom_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 "chrome/browser/chromeos/arc/print/print_struct_traits.h" +#include "chrome/browser/chromeos/arc/print/print_mojom_traits.h" #include "base/strings/stringprintf.h" #include "printing/units.h"
diff --git a/chrome/browser/chromeos/arc/print/print_struct_traits.h b/chrome/browser/chromeos/arc/print/print_mojom_traits.h similarity index 90% rename from chrome/browser/chromeos/arc/print/print_struct_traits.h rename to chrome/browser/chromeos/arc/print/print_mojom_traits.h index 52dab60..a228f169 100644 --- a/chrome/browser/chromeos/arc/print/print_struct_traits.h +++ b/chrome/browser/chromeos/arc/print/print_mojom_traits.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 CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_STRUCT_TRAITS_H_ -#define CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_STRUCT_TRAITS_H_ +#ifndef CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_MOJOM_TRAITS_H_ +#define CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_MOJOM_TRAITS_H_ #include <string> #include <vector> -#include "components/arc/common/print.mojom.h" +#include "components/arc/common/print_common.mojom.h" #include "printing/backend/print_backend.h" #include "printing/page_range.h" #include "ui/gfx/geometry/size.h" @@ -76,4 +76,4 @@ } // namespace mojo -#endif // CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_STRUCT_TRAITS_H_ +#endif // CHROME_BROWSER_CHROMEOS_ARC_PRINT_PRINT_MOJOM_TRAITS_H_
diff --git a/chrome/browser/chromeos/arc/tracing/arc_app_performance_tracing_unittest.cc b/chrome/browser/chromeos/arc/tracing/arc_app_performance_tracing_unittest.cc index 4f7bdc40..9926dc826 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_app_performance_tracing_unittest.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_app_performance_tracing_unittest.cc
@@ -39,7 +39,7 @@ params.bounds = gfx::Rect(5, 5, 20, 20); params.context = nullptr; views::Widget* widget = new views::Widget(); - widget->Init(params); + widget->Init(std::move(params)); // Set ARC id before showing the window to be recognized in // ArcAppWindowLauncherController. exo::SetShellApplicationId(widget->GetNativeWindow(), window_app_id);
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow.cc b/chrome/browser/chromeos/attestation/platform_verification_flow.cc index 1bccf14..285c842 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow.cc
@@ -49,8 +49,6 @@ "ChromeOS.PlatformVerification.Result"; const char kAttestationAvailableHistogram[] = "ChromeOS.PlatformVerification.Available"; -const char kAttestationExpiryHistogram[] = - "ChromeOS.PlatformVerification.ExpiryStatus"; const int kOpportunisticRenewalThresholdInDays = 30; // A callback method to handle DBus errors. @@ -74,12 +72,6 @@ callback.Run(error, std::string(), std::string(), std::string()); } -// A helper to report expiry status to UMA. -void ReportExpiryStatus(PlatformVerificationFlow::ExpiryStatus status) { - UMA_HISTOGRAM_ENUMERATION(kAttestationExpiryHistogram, status, - PlatformVerificationFlow::EXPIRY_STATUS_MAX); -} - } // namespace namespace chromeos { @@ -300,7 +292,6 @@ return; } ExpiryStatus expiry_status = CheckExpiry(certificate_chain); - ReportExpiryStatus(expiry_status); if (expiry_status == EXPIRY_STATUS_EXPIRED) { GetCertificate(context, account_id, true /* Force a new key */); return;
diff --git a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc index 050ce77..43fe3c9a 100644 --- a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc +++ b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.cc
@@ -71,8 +71,9 @@ if (!active_pin_dialog_->IsLocked()) return RequestPinResult::kDialogDisplayedAlready; - // Set the new callback to be used by the view. - active_pin_dialog_->SetCallback(std::move(callback)); + DCHECK(!active_request_pin_callback_); + active_request_pin_callback_ = std::move(callback); + active_pin_dialog_->SetDialogParameters(code_type, error_type, attempts_left, accept_input); active_pin_dialog_->DialogModelChanged(); @@ -88,9 +89,16 @@ if (current_time - sign_request_times_[key] > kSignRequestIdTimeout) return RequestPinResult::kInvalidId; + DCHECK(!active_request_pin_callback_); + active_request_pin_callback_ = std::move(callback); + active_dialog_extension_id_ = extension_id; - active_pin_dialog_ = new RequestPinView( - extension_name, code_type, attempts_left, std::move(callback), this); + active_pin_dialog_ = + new RequestPinView(extension_name, code_type, attempts_left, + base::BindRepeating(&PinDialogManager::OnPinEntered, + weak_factory_.GetWeakPtr()), + base::BindOnce(&PinDialogManager::OnViewDestroyed, + weak_factory_.GetWeakPtr())); const gfx::NativeWindow parent = GetBrowserParentWindow(); // If there is no parent, falls back to the root window for new windows. @@ -101,18 +109,6 @@ return RequestPinResult::kSuccess; } -void PinDialogManager::OnPinDialogInput() { - last_response_closed_[active_dialog_extension_id_] = false; -} - -void PinDialogManager::OnPinDialogClosed() { - last_response_closed_[active_dialog_extension_id_] = true; - // |active_pin_dialog_| is managed by |active_window_|. This local copy of - // the pointer is reset here to allow a new dialog to be created when a new - // request comes. - active_pin_dialog_ = nullptr; -} - PinDialogManager::StopPinRequestResult PinDialogManager::StopPinRequestWithError( const std::string& extension_id, @@ -126,12 +122,8 @@ if (!active_pin_dialog_->IsLocked()) return StopPinRequestResult::kNoUserInput; - active_pin_dialog_->SetCallback(base::BindOnce( - [](StopPinRequestCallback callback, const std::string& user_input) { - DCHECK(user_input.empty()); - std::move(callback).Run(); - }, - std::move(callback))); + DCHECK(!active_stop_pin_request_callback_); + active_stop_pin_request_callback_ = std::move(callback); active_pin_dialog_->SetDialogParameters( RequestPinView::RequestPinCodeType::UNCHANGED, error_type, /*attempts_left=*/-1, @@ -154,10 +146,13 @@ return false; } - // Close the window. |active_pin_dialog_| gets deleted inside Close(). + // The view destruction may happen asynchronously after the Close() call. For + // simplicity, clear our state and execute the callback immediately. active_window_->Close(); - active_pin_dialog_ = nullptr; - + if (active_pin_dialog_) { + weak_factory_.InvalidateWeakPtrs(); + OnPinDialogClosed(); + } return true; } @@ -176,4 +171,29 @@ } } +void PinDialogManager::OnPinEntered(const std::string& user_input) { + DCHECK(!active_stop_pin_request_callback_); + last_response_closed_[active_dialog_extension_id_] = false; + if (active_request_pin_callback_) + std::move(active_request_pin_callback_).Run(user_input); +} + +void PinDialogManager::OnViewDestroyed() { + OnPinDialogClosed(); +} + +void PinDialogManager::OnPinDialogClosed() { + DCHECK(active_pin_dialog_); + DCHECK(!active_request_pin_callback_ || !active_stop_pin_request_callback_); + + active_pin_dialog_ = nullptr; + active_window_ = nullptr; + last_response_closed_[active_dialog_extension_id_] = true; + active_dialog_extension_id_.clear(); + if (active_request_pin_callback_) + std::move(active_request_pin_callback_).Run(/*user_input=*/std::string()); + if (active_stop_pin_request_callback_) + std::move(active_stop_pin_request_callback_).Run(); +} + } // namespace chromeos
diff --git a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h index 184cf4b..29976ea 100644 --- a/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h +++ b/chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h
@@ -21,7 +21,7 @@ // Manages the state of the dialog that requests the PIN from user. Used by the // extensions that need to request the PIN. Implemented as requirement for // crbug.com/612886 -class PinDialogManager final : RequestPinView::Delegate { +class PinDialogManager final { public: enum class RequestPinResult { kSuccess, @@ -75,10 +75,6 @@ int attempts_left, RequestPinCallback callback); - // chromeos::RequestPinView::Delegate overrides. - void OnPinDialogInput() override; - void OnPinDialogClosed() override; - // Updates the existing dialog with new error message. Runs |callback| when // user closes the dialog. Returns whether the provided |extension_id| matches // the extension owning the active dialog. @@ -105,6 +101,16 @@ private: using ExtensionNameRequestIdPair = std::pair<std::string, int>; + // The callback that gets invoked once the user sends some input into the PIN + // dialog. + void OnPinEntered(const std::string& user_input); + // The callback that gets invoked once the PIN dialog's view gets destroyed. + void OnViewDestroyed(); + + // Called when the PIN dialog is closed. Cleans up the internal state and runs + // the needed callbacks. + void OnPinDialogClosed(); + // Tells whether user closed the last request PIN dialog issued by an // extension. The extension_id is the key and value is true if user closed the // dialog. Used to determine if the limit of dialogs rejected by the user has @@ -120,6 +126,8 @@ RequestPinView* active_pin_dialog_ = nullptr; std::string active_dialog_extension_id_; views::Widget* active_window_ = nullptr; + RequestPinCallback active_request_pin_callback_; + StopPinRequestCallback active_stop_pin_request_callback_; base::WeakPtrFactory<PinDialogManager> weak_factory_{this}; };
diff --git a/chrome/browser/chromeos/first_run/first_run_controller.cc b/chrome/browser/chromeos/first_run/first_run_controller.cc index 9eb47e2..bad2351 100644 --- a/chrome/browser/chromeos/first_run/first_run_controller.cc +++ b/chrome/browser/chromeos/first_run/first_run_controller.cc
@@ -49,7 +49,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash::kShellWindowId_OverlayContainer); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/chrome/browser/chromeos/lock_screen_apps/toast_dialog_view.cc b/chrome/browser/chromeos/lock_screen_apps/toast_dialog_view.cc index 527df369..7ef913e 100644 --- a/chrome/browser/chromeos/lock_screen_apps/toast_dialog_view.cc +++ b/chrome/browser/chromeos/lock_screen_apps/toast_dialog_view.cc
@@ -80,7 +80,7 @@ ¶ms, ash::kShellWindowId_SettingBubbleContainer); views::Widget* widget = new views::Widget; // owned by native widget - widget->Init(params); + widget->Init(std::move(params)); widget->AddObserver(this); widget->Show(); }
diff --git a/chrome/browser/chromeos/login/ui/captive_portal_window_proxy.cc b/chrome/browser/chromeos/login/ui/captive_portal_window_proxy.cc index 46180fcf..b99f13ab4 100644 --- a/chrome/browser/chromeos/login/ui/captive_portal_window_proxy.cc +++ b/chrome/browser/chromeos/login/ui/captive_portal_window_proxy.cc
@@ -28,7 +28,7 @@ params.parent = parent; params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc index fa413ef..f952dbe 100644 --- a/chrome/browser/chromeos/login/ui/login_display_host_webui.cc +++ b/chrome/browser/chromeos/login/ui/login_display_host_webui.cc
@@ -870,7 +870,7 @@ ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash::kShellWindowId_LockScreenContainer); login_window_ = new views::Widget; - login_window_->Init(params); + login_window_->Init(std::move(params)); login_view_ = new WebUILoginView(WebUILoginView::WebViewSettings()); login_view_->Init();
diff --git a/chrome/browser/chromeos/login/ui/login_screen_extension_ui/login_screen_extension_ui_window.cc b/chrome/browser/chromeos/login/ui/login_screen_extension_ui/login_screen_extension_ui_window.cc index e20a8e4..3964e779 100644 --- a/chrome/browser/chromeos/login/ui/login_screen_extension_ui/login_screen_extension_ui_window.cc +++ b/chrome/browser/chromeos/login/ui/login_screen_extension_ui/login_screen_extension_ui_window.cc
@@ -40,7 +40,7 @@ params.delegate = dialog_view_; ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash::kShellWindowId_LockScreenContainer); - dialog_widget_->Init(params); + dialog_widget_->Init(std::move(params)); dialog_widget_->set_movement_disabled(true); dialog_delegate_->set_native_window(dialog_widget_->GetNativeWindow()); dialog_widget_->Show();
diff --git a/chrome/browser/chromeos/login/ui/oobe_ui_dialog_delegate.cc b/chrome/browser/chromeos/login/ui/oobe_ui_dialog_delegate.cc index 475910f..2ef6566 100644 --- a/chrome/browser/chromeos/login/ui/oobe_ui_dialog_delegate.cc +++ b/chrome/browser/chromeos/login/ui/oobe_ui_dialog_delegate.cc
@@ -108,7 +108,7 @@ ¶ms, ash::kShellWindowId_LockSystemModalContainer); widget_ = new views::Widget; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetBounds(display::Screen::GetScreen() ->GetDisplayNearestWindow(widget_->GetNativeWindow()) .work_area()); @@ -231,7 +231,7 @@ ¶ms, ash::kShellWindowId_LockScreenContainer); dialog_widget_ = new views::Widget; - dialog_widget_->Init(params); + dialog_widget_->Init(std::move(params)); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( dialog_view_->web_contents());
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index 6196b9f..70bcb39f 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -1282,17 +1282,6 @@ } bool ChromeUserManagerImpl::IsGuestSessionAllowed() const { - const AccountId& owner_account_id = GetOwnerAccountId(); - if (owner_account_id.is_valid()) { - // Some Autotest policy tests appear to wipe the user list in Local State - // but preserve a policy file referencing an owner: https://crbug.com/850139 - const user_manager::User* owner_user = FindUser(owner_account_id); - if (owner_user && - owner_user->GetType() == user_manager::UserType::USER_TYPE_CHILD) { - return false; - } - } - // In tests CrosSettings might not be initialized. if (!cros_settings_) return false;
diff --git a/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.cc b/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.cc index 8db88f4..f67493a 100644 --- a/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.cc +++ b/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.cc
@@ -12,6 +12,7 @@ #include "base/single_thread_task_runner.h" #include "base/syslog_logging.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/time.h" #include "chrome/browser/chromeos/arc/policy/arc_policy_bridge.h" #include "chrome/browser/profiles/profile.h" #include "components/arc/common/policy.mojom.h" @@ -19,6 +20,13 @@ namespace policy { +namespace { + +constexpr base::TimeDelta kDefaultCommandTimeout = + base::TimeDelta::FromMinutes(2); + +} // namespace + UserCommandArcJob::UserCommandArcJob(Profile* profile) : profile_(profile) {} UserCommandArcJob::~UserCommandArcJob() = default; @@ -27,6 +35,10 @@ return enterprise_management::RemoteCommand_Type_USER_ARC_COMMAND; } +base::TimeDelta UserCommandArcJob::GetCommandTimeout() const { + return kDefaultCommandTimeout; +} + bool UserCommandArcJob::ParseCommandPayload( const std::string& command_payload) { command_payload_ = command_payload;
diff --git a/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h b/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h index 4997ecb..37b3fdbd 100644 --- a/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h +++ b/chrome/browser/chromeos/policy/remote_commands/user_command_arc_job.h
@@ -21,6 +21,7 @@ // RemoteCommandJob: enterprise_management::RemoteCommand_Type GetType() const override; + base::TimeDelta GetCommandTimeout() const override; protected: // RemoteCommandJob:
diff --git a/chrome/browser/chromeos/settings/cros_settings.cc b/chrome/browser/chromeos/settings/cros_settings.cc index 56676a03..59be592 100644 --- a/chrome/browser/chromeos/settings/cros_settings.cc +++ b/chrome/browser/chromeos/settings/cros_settings.cc
@@ -13,6 +13,7 @@ #include "base/values.h" #include "chrome/browser/chromeos/settings/device_settings_provider.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" +#include "chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/settings/system_settings_provider.h" @@ -97,6 +98,11 @@ // This is safe since |this| is never deleted. base::Unretained(this))); + auto supervised_user_cros_provider = + std::make_unique<SupervisedUserCrosSettingsProvider>(notify_cb); + supervised_user_cros_settings_provider_ = supervised_user_cros_provider.get(); + + AddSettingsProvider(std::move(supervised_user_cros_provider)); AddSettingsProvider(std::make_unique<DeviceSettingsProvider>( notify_cb, device_settings_service, local_state)); AddSettingsProvider(std::make_unique<SystemSettingsProvider>(notify_cb));
diff --git a/chrome/browser/chromeos/settings/cros_settings.h b/chrome/browser/chromeos/settings/cros_settings.h index 9ee2a226..20045148 100644 --- a/chrome/browser/chromeos/settings/cros_settings.h +++ b/chrome/browser/chromeos/settings/cros_settings.h
@@ -23,11 +23,12 @@ class DictionaryValue; class ListValue; class Value; -} +} // namespace base namespace chromeos { class DeviceSettingsService; +class SupervisedUserCrosSettingsProvider; // This class manages per-device/global settings. class CrosSettings { @@ -121,6 +122,11 @@ // Returns the provider that handles settings with the |path| or prefix. CrosSettingsProvider* GetProvider(const std::string& path) const; + const SupervisedUserCrosSettingsProvider* + supervised_user_cros_settings_provider() const { + return supervised_user_cros_settings_provider_; + } + private: friend class CrosSettingsTest; @@ -130,6 +136,9 @@ // List of ChromeOS system settings providers. std::vector<std::unique_ptr<CrosSettingsProvider>> providers_; + // Owner unique pointer in |providers_|. + SupervisedUserCrosSettingsProvider* supervised_user_cros_settings_provider_; + // A map from settings names to a list of observers. Observers get fired in // the order they are added. std::map<std::string, std::unique_ptr<base::CallbackList<void(void)>>>
diff --git a/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.cc b/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.cc new file mode 100644 index 0000000..ec7cad70 --- /dev/null +++ b/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.cc
@@ -0,0 +1,61 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h" + +#include "base/logging.h" +#include "base/stl_util.h" +#include "base/values.h" +#include "chromeos/settings/cros_settings_names.h" +#include "components/account_id/account_id.h" +#include "components/user_manager/user_manager.h" + +namespace chromeos { + +SupervisedUserCrosSettingsProvider::SupervisedUserCrosSettingsProvider( + const CrosSettingsProvider::NotifyObserversCallback& notify_cb) + : CrosSettingsProvider(notify_cb) { + child_user_restrictions_[chromeos::kAccountsPrefAllowGuest] = + base::Value(false); + child_user_restrictions_[chromeos::kAccountsPrefShowUserNamesOnSignIn] = + base::Value(true); + child_user_restrictions_[chromeos::kAccountsPrefAllowNewUser] = + base::Value(true); +} + +SupervisedUserCrosSettingsProvider::~SupervisedUserCrosSettingsProvider() = + default; + +const base::Value* SupervisedUserCrosSettingsProvider::Get( + const std::string& path) const { + DCHECK(HandlesSetting(path)); + auto iter = child_user_restrictions_.find(path); + return &(iter->second); +} + +CrosSettingsProvider::TrustedStatus +SupervisedUserCrosSettingsProvider::PrepareTrustedValues( + const base::Closure& callback) { + return CrosSettingsProvider::TrustedStatus::TRUSTED; +} + +bool SupervisedUserCrosSettingsProvider::HandlesSetting( + const std::string& path) const { + if (!user_manager::UserManager::IsInitialized()) + return false; + auto* user_manager = user_manager::UserManager::Get(); + if (user_manager->GetUsers().empty()) + return false; + + auto* device_owner = + user_manager->FindUser(user_manager->GetOwnerAccountId()); + + if (device_owner && device_owner->IsChild()) { + return base::Contains(child_user_restrictions_, path); + } + + return false; +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h b/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h new file mode 100644 index 0000000..030afc7 --- /dev/null +++ b/chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h
@@ -0,0 +1,41 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_SETTINGS_SUPERVISED_USER_CROS_SETTINGS_PROVIDER_H_ +#define CHROME_BROWSER_CHROMEOS_SETTINGS_SUPERVISED_USER_CROS_SETTINGS_PROVIDER_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "chromeos/settings/cros_settings_provider.h" + +namespace base { +class Value; +} + +namespace chromeos { + +class SupervisedUserCrosSettingsProvider : public CrosSettingsProvider { + public: + explicit SupervisedUserCrosSettingsProvider( + const CrosSettingsProvider::NotifyObserversCallback& notify_cb); + ~SupervisedUserCrosSettingsProvider() override; + + // CrosSettingsProvider: + const base::Value* Get(const std::string& path) const override; + CrosSettingsProvider::TrustedStatus PrepareTrustedValues( + const base::Closure& callback) override; + bool HandlesSetting(const std::string& path) const override; + + private: + // Cros pref name to pref value. + std::map<std::string, base::Value> child_user_restrictions_; + + DISALLOW_COPY_AND_ASSIGN(SupervisedUserCrosSettingsProvider); +}; + +} // namespace chromeos + +#endif // CHROME_BROWSER_CHROMEOS_SETTINGS_SUPERVISED_USER_CROS_SETTINGS_PROVIDER_H_
diff --git a/chrome/browser/chromeos/ui/idle_app_name_notification_view.cc b/chrome/browser/chromeos/ui/idle_app_name_notification_view.cc index c9990e06..b72b5032 100644 --- a/chrome/browser/chromeos/ui/idle_app_name_notification_view.cc +++ b/chrome/browser/chromeos/ui/idle_app_name_notification_view.cc
@@ -71,7 +71,7 @@ ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash::kShellWindowId_SettingBubbleContainer); views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); gfx::NativeView native_view = widget->GetNativeView(); native_view->SetName("KioskIdleAppNameNotification");
diff --git a/chrome/browser/chromeos/ui/kiosk_external_update_notification.cc b/chrome/browser/chromeos/ui/kiosk_external_update_notification.cc index 3fc79b8..15986446 100644 --- a/chrome/browser/chromeos/ui/kiosk_external_update_notification.cc +++ b/chrome/browser/chromeos/ui/kiosk_external_update_notification.cc
@@ -140,7 +140,7 @@ ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash::kShellWindowId_SettingBubbleContainer); views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); gfx::NativeView native_view = widget->GetNativeView(); native_view->SetName("KioskExternalUpdateNotification"); widget->Show();
diff --git a/chrome/browser/chromeos/ui/request_pin_view.cc b/chrome/browser/chromeos/ui/request_pin_view.cc index 784ad55..4bd914c 100644 --- a/chrome/browser/chromeos/ui/request_pin_view.cc +++ b/chrome/browser/chromeos/ui/request_pin_view.cc
@@ -33,14 +33,15 @@ } // namespace -RequestPinView::RequestPinView(const std::string& extension_name, - RequestPinView::RequestPinCodeType code_type, - int attempts_left, - RequestPinCallback callback, - Delegate* delegate) - : callback_(std::move(callback)), delegate_(delegate) { +RequestPinView::RequestPinView( + const std::string& extension_name, + RequestPinView::RequestPinCodeType code_type, + int attempts_left, + const PinEnteredCallback& pin_entered_callback, + ViewDestructionCallback view_destruction_callback) + : pin_entered_callback_(pin_entered_callback), + view_destruction_callback_(std::move(view_destruction_callback)) { DCHECK_NE(code_type, RequestPinCodeType::UNCHANGED); - DCHECK(delegate); Init(); SetExtensionName(extension_name); const bool accept_input = (attempts_left != 0); @@ -49,13 +50,8 @@ chrome::RecordDialogCreation(chrome::DialogIdentifier::REQUEST_PIN); } -// When the parent window is closed while the dialog is active, this object is -// destroyed without triggering Accept or Cancel. If the callback_ wasn't called -// it needs to send the response. RequestPinView::~RequestPinView() { - if (callback_) - std::move(callback_).Run(/*user_input=*/std::string()); - delegate_->OnPinDialogClosed(); + std::move(view_destruction_callback_).Run(); } void RequestPinView::ContentsChanged(views::Textfield* sender, @@ -64,16 +60,15 @@ } bool RequestPinView::Cancel() { - // Destructor will be called after this which notifies the delegate. + // Destructor will be called after this which notifies the callback. return true; } bool RequestPinView::Accept() { - DCHECK(!callback_.is_null()); - if (!textfield_->GetEnabled()) return true; DCHECK(!textfield_->GetText().empty()); + DCHECK(!locked_); error_label_->SetVisible(true); error_label_->SetText( @@ -84,9 +79,9 @@ // The |textfield_| and OK button become disabled, but the user still can // close the dialog. SetAcceptInput(false); - std::move(callback_).Run(base::UTF16ToUTF8(textfield_->GetText())); + pin_entered_callback_.Run(base::UTF16ToUTF8(textfield_->GetText())); + locked_ = true; DialogModelChanged(); - delegate_->OnPinDialogInput(); return false; } @@ -96,7 +91,7 @@ case ui::DialogButton::DIALOG_BUTTON_CANCEL: return true; case ui::DialogButton::DIALOG_BUTTON_OK: - if (callback_.is_null()) + if (locked_) return false; // Not locked but the |textfield_| is not enabled. It's just a // notification to the user and [OK] button can be used to close the @@ -131,12 +126,7 @@ } bool RequestPinView::IsLocked() const { - return callback_.is_null(); -} - -void RequestPinView::SetCallback(RequestPinCallback callback) { - DCHECK(!callback_); - callback_ = std::move(callback); + return locked_; } void RequestPinView::SetDialogParameters( @@ -144,6 +134,7 @@ RequestPinView::RequestPinErrorType error_type, int attempts_left, bool accept_input) { + locked_ = false; SetErrorMessage(error_type, attempts_left); SetAcceptInput(accept_input);
diff --git a/chrome/browser/chromeos/ui/request_pin_view.h b/chrome/browser/chromeos/ui/request_pin_view.h index 118e397d2..b2158e0 100644 --- a/chrome/browser/chromeos/ui/request_pin_view.h +++ b/chrome/browser/chromeos/ui/request_pin_view.h
@@ -26,8 +26,8 @@ // A dialog box for requesting PIN code. Instances of this class are managed by // PinDialogManager. -class RequestPinView : public views::DialogDelegateView, - public views::TextfieldController { +class RequestPinView final : public views::DialogDelegateView, + public views::TextfieldController { public: enum RequestPinCodeType { PIN, PUK, UNCHANGED }; @@ -39,19 +39,9 @@ UNKNOWN_ERROR }; - class Delegate { - public: - // Notification when user closes the PIN dialog. - virtual void OnPinDialogClosed() = 0; - - // Notification when the user provided input to dialog. - virtual void OnPinDialogInput() = 0; - }; - - // Used to send the PIN/PUK entered by the user in the textfield to the - // extension that asked for the code. - using RequestPinCallback = - base::OnceCallback<void(const std::string& user_input)>; + using PinEnteredCallback = + base::RepeatingCallback<void(const std::string& user_input)>; + using ViewDestructionCallback = base::OnceClosure; // Creates the view to be embeded in the dialog that requests the PIN/PUK. // |extension_name| - the name of the extension making the request. Displayed @@ -62,13 +52,13 @@ // zero the textfield is disabled and user cannot provide any input. When // -1 the user is allowed to provide the input and no information about // the attepts left is displayed in the view. - // |callback| - used to send the value of the PIN/PUK the user entered. - // |delegate| - used to notify that dialog was closed. Cannot be null. + // |pin_entered_callback| - called every time the user submits the input. + // |view_destruction_callback| - called by the destructor. RequestPinView(const std::string& extension_name, RequestPinCodeType code_type, int attempts_left, - RequestPinCallback callback, - Delegate* delegate); + const PinEnteredCallback& pin_entered_callback, + ViewDestructionCallback view_destruction_callback); RequestPinView(const RequestPinView&) = delete; RequestPinView& operator=(const RequestPinView&) = delete; ~RequestPinView() override; @@ -92,10 +82,6 @@ // the user input data. bool IsLocked() const; - // Set the new callback to be used when user will provide the input. The old - // callback must be used and reset to null at this point. - void SetCallback(RequestPinCallback callback); - // |code_type| - specifies whether the user is asked to enter PIN or PUK. If // UNCHANGED value is provided, the dialog displays the same value that // was last set. @@ -126,14 +112,12 @@ // |window_title_| and |code_type_|. void UpdateHeaderText(); - // Used to send the input when the view is not locked. If user closes the - // view, the provided input is empty. The |callback_| must be reset to null - // after being used, allowing to check that it was used when a new callback is - // set. - RequestPinCallback callback_; + const PinEnteredCallback pin_entered_callback_; + ViewDestructionCallback view_destruction_callback_; - // Owned by the caller. - Delegate* delegate_ = nullptr; + // Whether the UI is locked, disallowing the user to input any data, while the + // caller processes the previously entered PIN/PUK. + bool locked_ = false; base::string16 window_title_; views::Label* header_label_ = nullptr;
diff --git a/chrome/browser/extensions/activity_log/activity_log.cc b/chrome/browser/extensions/activity_log/activity_log.cc index 3eebfcb..f61bad9 100644 --- a/chrome/browser/extensions/activity_log/activity_log.cc +++ b/chrome/browser/extensions/activity_log/activity_log.cc
@@ -438,7 +438,7 @@ state.IsWhitelistedId(extension_id)) return; if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&LogApiActivityOnUI, browser_context, extension_id, activity_name, args.CreateDeepCopy(), type)); @@ -499,11 +499,10 @@ state.IsWhitelistedId(extension_id)) return; if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&LogWebRequestActivityOnUI, browser_context, - extension_id, url, is_incognito, api_call, - std::move(details))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&LogWebRequestActivityOnUI, browser_context, + extension_id, url, is_incognito, api_call, + std::move(details))); return; } LogWebRequestActivityOnUI(browser_context, extension_id, url, is_incognito,
diff --git a/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc b/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc index 42b5813..89b0d75 100644 --- a/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc +++ b/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc
@@ -244,7 +244,6 @@ DCHECK(service); Respond(NoArguments()); - service->pin_dialog_manager()->OnPinDialogClosed(); } CertificateProviderRequestPinFunction::
diff --git a/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc b/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc index 3d9892b..ed9c0d5 100644 --- a/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc +++ b/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc
@@ -190,7 +190,7 @@ std::string new_tab_url_ext = ext_turl.new_tab_url_ref().ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(base::string16()), - UIThreadSearchTermsData(profile)); + UIThreadSearchTermsData()); EXPECT_EQ(new_tab_url_ext, search::GetNewTabPageURL(profile).spec());
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index be9a335..6ac4a7e 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -50,11 +50,10 @@ #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" +#include "chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h" #include "chrome/browser/chromeos/system/timezone_util.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h" -#include "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/settings/cros_settings_names.h" @@ -83,8 +82,9 @@ if (!profile->IsChild()) return false; - return SupervisedUserServiceFactory::GetForProfile(profile) - ->IsRestrictedCrosSettingForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->HandlesSetting(pref_name); } const base::Value* GetRestrictedCrosSettingValueForChildUser( @@ -94,8 +94,9 @@ // pre-set. DCHECK(IsRestrictedCrosSettingForChildUser(profile, pref_name)); - return SupervisedUserServiceFactory::GetForProfile(profile) - ->GetRestrictedCrosSettingValueForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->Get(pref_name); } #endif
diff --git a/chrome/browser/extensions/api/tabs/tabs_api.cc b/chrome/browser/extensions/api/tabs/tabs_api.cc index 1e8ca806..c63a132 100644 --- a/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chrome/browser/extensions/api/tabs/tabs_api.cc
@@ -592,6 +592,14 @@ bool set_self_as_opener = create_data->set_self_as_opener && // present? *create_data->set_self_as_opener; // set to true? if (set_self_as_opener) { + if (is_from_service_worker()) { + // TODO(crbug.com/984350): Add test for this. + return RespondNow( + Error("Cannot specify setSelfAsOpener Service Worker extension.")); + } + // TODO(crbug.com/984350): Add tests for checking opener SiteInstance + // behavior from a SW based extension's extension frame (e.g. from popup). + // See ExtensionApiTest.WindowsCreate* tests for details. navigate_params.opener = render_frame_host(); navigate_params.source_site_instance = render_frame_host()->GetSiteInstance();
diff --git a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc index 9d43155..3ed158c3 100644 --- a/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc
@@ -18,6 +18,16 @@ namespace extensions { +namespace { + +// TODO(lazyboy): Move this to some common place for reuse, e.g. +// ExtensionBrowserTest. +enum class ContextType { + kEventPage, + kServiceWorker, +}; +} // namespace + namespace keys = tabs_constants; namespace utils = extension_function_test_utils; @@ -117,8 +127,35 @@ } } -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCurrentWindow) { - ASSERT_TRUE(RunExtensionTest("tabs/current_window")) << message_; +class NonPersistentExtensionTabsTest + : public ExtensionApiTest, + public testing::WithParamInterface<ContextType> { + protected: + const Extension* LoadNonPersistentExtension(const char* relative_path) { + return LoadExtensionWithFlags(test_data_dir_.AppendASCII(relative_path), + GetParam() == ContextType::kEventPage + ? kFlagNone + : kFlagRunAsServiceWorkerBasedExtension); + } +}; + +// Tests chrome.windows.create. +// TODO(crbug.com/984350): Expand the test to verify that setSelfAsOpener +// param is ignored from Service Worker extension scripts. +IN_PROC_BROWSER_TEST_P(NonPersistentExtensionTabsTest, TabCurrentWindow) { + ASSERT_TRUE(RunExtensionTestWithFlags( + "tabs/current_window", GetParam() == ContextType::kServiceWorker + ? kFlagRunAsServiceWorkerBasedExtension + : kFlagNone)) + << message_; } +INSTANTIATE_TEST_SUITE_P(EventPage, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kEventPage)); + +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kServiceWorker)); + } // namespace extensions
diff --git a/chrome/browser/extensions/background_xhr_browsertest.cc b/chrome/browser/extensions/background_xhr_browsertest.cc index 42dca06..1a506089 100644 --- a/chrome/browser/extensions/background_xhr_browsertest.cc +++ b/chrome/browser/extensions/background_xhr_browsertest.cc
@@ -95,7 +95,7 @@ // Install a null ClientCertStore so the client auth prompt isn't bypassed due // to the system certificate store returning no certificates. base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&InstallNullCertStoreFactoryOnIOThread, browser()->profile()->GetResourceContext()),
diff --git a/chrome/browser/extensions/blacklist.cc b/chrome/browser/extensions/blacklist.cc index 3028f93..45d386d 100644 --- a/chrome/browser/extensions/blacklist.cc +++ b/chrome/browser/extensions/blacklist.cc
@@ -87,7 +87,7 @@ const OnResultCallback& callback) { auto safe_browsing_client = base::WrapRefCounted( new SafeBrowsingClientImpl(extension_ids, callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&SafeBrowsingClientImpl::StartCheck, safe_browsing_client, g_database_manager.Get().get(),
diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc index 218ccbb..9750858 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc
@@ -783,7 +783,7 @@ site_instance->GetProcess()->GetID(), site_instance->GetId()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&InfoMap::RegisterExtensionProcess, ExtensionSystem::Get(context)->info_map(), extension->id(), @@ -808,7 +808,7 @@ site_instance->GetProcess()->GetID(), site_instance->GetId()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&InfoMap::UnregisterExtensionProcess, ExtensionSystem::Get(context)->info_map(), extension->id(),
diff --git a/chrome/browser/extensions/chrome_content_verifier_delegate.cc b/chrome/browser/extensions/chrome_content_verifier_delegate.cc index 0b923c3..0c007d0 100644 --- a/chrome/browser/extensions/chrome_content_verifier_delegate.cc +++ b/chrome/browser/extensions/chrome_content_verifier_delegate.cc
@@ -135,6 +135,15 @@ ChromeContentVerifierDelegate::~ChromeContentVerifierDelegate() { } +bool ChromeContentVerifierDelegate::ShouldBeChecked( + const Extension& extension) { + // All policy-based extensions should have some checks. + return ShouldBeVerified(extension); + // TODO(crbug.com/958794): After all preparations enable content checking for + // all policy-based extension (even for self-hosted ones): + // || Manifest::IsPolicyLocation(extension.location()); +} + bool ChromeContentVerifierDelegate::ShouldBeVerified( const Extension& extension) { return GetVerifyMode(extension) != NONE;
diff --git a/chrome/browser/extensions/chrome_content_verifier_delegate.h b/chrome/browser/extensions/chrome_content_verifier_delegate.h index 703530ee..d6ee0026 100644 --- a/chrome/browser/extensions/chrome_content_verifier_delegate.h +++ b/chrome/browser/extensions/chrome_content_verifier_delegate.h
@@ -55,6 +55,7 @@ ~ChromeContentVerifierDelegate() override; // ContentVerifierDelegate: + bool ShouldBeChecked(const Extension& extension) override; bool ShouldBeVerified(const Extension& extension) override; ContentVerifierKey GetPublicKey() override; GURL GetSignatureFetchUrl(const std::string& extension_id,
diff --git a/chrome/browser/extensions/chrome_extension_cookies.cc b/chrome/browser/extensions/chrome_extension_cookies.cc index 9a3c122..fa5ec25 100644 --- a/chrome/browser/extensions/chrome_extension_cookies.cc +++ b/chrome/browser/extensions/chrome_extension_cookies.cc
@@ -68,11 +68,10 @@ return; // Safe since |io_data_| is non-null so no IOData deletion is queued. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&IOData::CreateRestrictedCookieManager, - base::Unretained(io_data_.get()), origin, - std::move(request))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&IOData::CreateRestrictedCookieManager, + base::Unretained(io_data_.get()), origin, + std::move(request))); } void ChromeExtensionCookies::ClearCookies(const GURL& origin) { @@ -81,10 +80,9 @@ return; // Safe since |io_data_| is non-null so no IOData deletion is queued. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&IOData::ClearCookies, base::Unretained(io_data_.get()), - origin)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&IOData::ClearCookies, + base::Unretained(io_data_.get()), origin)); } net::CookieStore* ChromeExtensionCookies::GetCookieStoreForTesting() { @@ -178,7 +176,7 @@ CONTENT_SETTINGS_TYPE_COOKIES, std::string(), &settings); // Safe since |io_data_| is non-null so no IOData deletion is queued. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOData::OnContentSettingChanged, base::Unretained(io_data_.get()), std::move(settings))); @@ -191,11 +189,10 @@ return; // Safe since |io_data_| is non-null so no IOData deletion is queued. - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&IOData::OnThirdPartyCookieBlockingChanged, - base::Unretained(io_data_.get()), - block_third_party_cookies)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&IOData::OnThirdPartyCookieBlockingChanged, + base::Unretained(io_data_.get()), + block_third_party_cookies)); } void ChromeExtensionCookies::Shutdown() {
diff --git a/chrome/browser/extensions/chrome_extensions_interface_registration.cc b/chrome/browser/extensions/chrome_extensions_interface_registration.cc index fd15825..0463e5f 100644 --- a/chrome/browser/extensions/chrome_extensions_interface_registration.cc +++ b/chrome/browser/extensions/chrome_extensions_interface_registration.cc
@@ -73,8 +73,8 @@ std::move(origin), source_id, std::move(callback)); }, salt, std::move(origin), source_id, std::move(callback)); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - std::move(callback_on_io_thread)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + std::move(callback_on_io_thread)); } void TriggerCameraIntent(content::BrowserContext* context,
diff --git a/chrome/browser/extensions/chrome_url_request_util.cc b/chrome/browser/extensions/chrome_url_request_util.cc index 5aafcd12..7766498 100644 --- a/chrome/browser/extensions/chrome_url_request_util.cc +++ b/chrome/browser/extensions/chrome_url_request_util.cc
@@ -145,8 +145,8 @@ auto data = GetResource(resource_id, request.url.host()); std::string* read_mime_type = new std::string; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&net::GetMimeTypeFromFile, filename, base::Unretained(read_mime_type)), base::BindOnce(&ResourceBundleFileLoader::OnMimeTypeRead,
diff --git a/chrome/browser/extensions/crx_installer.cc b/chrome/browser/extensions/crx_installer.cc index a48693b..d45553f6 100644 --- a/chrome/browser/extensions/crx_installer.cc +++ b/chrome/browser/extensions/crx_installer.cc
@@ -520,9 +520,8 @@ return; } - if (!base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CrxInstaller::CheckInstall, this))) + if (!base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CrxInstaller::CheckInstall, this))) NOTREACHED(); } @@ -866,10 +865,9 @@ void CrxInstaller::ReportFailureFromFileThread(const CrxInstallError& error) { DCHECK(installer_task_runner_->RunsTasksInCurrentSequence()); - if (!base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CrxInstaller::ReportFailureFromUIThread, this, - error))) { + if (!base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CrxInstaller::ReportFailureFromUIThread, + this, error))) { NOTREACHED(); } } @@ -911,7 +909,7 @@ if (install_cause() == extension_misc::INSTALL_CAUSE_USER_DOWNLOAD) UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionInstalled", 1, 2); - if (!base::PostTaskWithTraits( + if (!base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&CrxInstaller::ReportSuccessFromUIThread, this))) NOTREACHED(); @@ -1005,7 +1003,7 @@ ConfirmReEnable(); if (!installer_callback_.is_null() && - !base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}) + !base::CreateSingleThreadTaskRunner({BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(std::move(installer_callback_), error))) { NOTREACHED();
diff --git a/chrome/browser/extensions/event_router_forwarder.cc b/chrome/browser/extensions/event_router_forwarder.cc index 7a1d80ff..60f97cd 100644 --- a/chrome/browser/extensions/event_router_forwarder.cc +++ b/chrome/browser/extensions/event_router_forwarder.cc
@@ -60,7 +60,7 @@ bool use_profile_to_restrict_events, const GURL& event_url) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&EventRouterForwarder::HandleEvent, this, extension_id, histogram_value, event_name, std::move(event_args),
diff --git a/chrome/browser/extensions/event_router_forwarder_unittest.cc b/chrome/browser/extensions/event_router_forwarder_unittest.cc index ea57b956..f33be29 100644 --- a/chrome/browser/extensions/event_router_forwarder_unittest.cc +++ b/chrome/browser/extensions/event_router_forwarder_unittest.cc
@@ -153,14 +153,14 @@ kEventName, profile1_, url)); EXPECT_CALL(*event_router, CallEventRouter(profile2_, "", kHistogramValue, kEventName, profile2_, url)); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BroadcastEventToRenderers, - base::Unretained(event_router.get()), - kHistogramValue, kEventName, url)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BroadcastEventToRenderers, + base::Unretained(event_router.get()), + kHistogramValue, kEventName, url)); // Wait for IO thread's message loop to be processed scoped_refptr<base::ThreadTestHelper> helper(new base::ThreadTestHelper( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}).get())); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}).get())); ASSERT_TRUE(helper->Run()); base::RunLoop().RunUntilIdle();
diff --git a/chrome/browser/extensions/extension_assets_manager_chromeos.cc b/chrome/browser/extensions/extension_assets_manager_chromeos.cc index 29aa5b0..3ed8b9ca 100644 --- a/chrome/browser/extensions/extension_assets_manager_chromeos.cc +++ b/chrome/browser/extensions/extension_assets_manager_chromeos.cc
@@ -162,7 +162,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExtensionAssetsManagerChromeOS::CheckSharedExtension, extension->id(), extension->VersionString(), @@ -183,7 +183,7 @@ if (GetSharedInstallDir().IsParent(extension_root)) { // In some test extensions installed outside local_install_dir emulate // previous behavior that just do nothing in this case. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ExtensionAssetsManagerChromeOS::MarkSharedExtensionUnused, id, @@ -350,7 +350,7 @@ base::FilePath shared_install_dir = GetSharedInstallDir(); base::FilePath shared_version_dir = file_util::InstallExtension( unpacked_extension_root, id, version, shared_install_dir); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ExtensionAssetsManagerChromeOS::InstallSharedExtensionDone, id,
diff --git a/chrome/browser/extensions/extension_gcm_app_handler_unittest.cc b/chrome/browser/extensions/extension_gcm_app_handler_unittest.cc index cbd3d89..c5b88f6 100644 --- a/chrome/browser/extensions/extension_gcm_app_handler_unittest.cc +++ b/chrome/browser/extensions/extension_gcm_app_handler_unittest.cc
@@ -91,10 +91,9 @@ Profile* profile, base::WeakPtr<gcm::GCMProfileService> service, network::mojom::ProxyResolvingSocketFactoryRequest request) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, profile, - service, std::move(request))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&RequestProxyResolvingSocketFactoryOnUIThread, + profile, service, std::move(request))); } } // namespace @@ -122,7 +121,7 @@ // Runs until IO loop becomes idle. void PumpIOLoop() { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&Waiter::OnIOLoopPump, base::Unretained(this))); @@ -139,7 +138,7 @@ void OnIOLoopPump() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&Waiter::OnIOLoopPumpCompleted, base::Unretained(this))); } @@ -147,7 +146,7 @@ void OnIOLoopPumpCompleted() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&Waiter::PumpIOLoopCompleted, base::Unretained(this))); } @@ -222,14 +221,13 @@ content::BrowserContext* context) { Profile* profile = Profile::FromBrowserContext(context); scoped_refptr<base::SequencedTaskRunner> ui_thread = - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); scoped_refptr<base::SequencedTaskRunner> io_thread = - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}); scoped_refptr<base::SequencedTaskRunner> blocking_task_runner( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); return std::make_unique<gcm::GCMProfileService>( profile->GetPrefs(), profile->GetPath(), base::BindRepeating(&RequestProxyResolvingSocketFactory, profile),
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 8e931b2a..84e0ec8 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -1848,10 +1848,9 @@ } process_map->RemoveAllFromProcess(process->GetID()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&InfoMap::UnregisterAllExtensionsInProcess, - system_->info_map(), process->GetID())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&InfoMap::UnregisterAllExtensionsInProcess, + system_->info_map(), process->GetID())); break; } case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
diff --git a/chrome/browser/extensions/extension_special_storage_policy.cc b/chrome/browser/extensions/extension_special_storage_policy.cc index ceb0e41e..5a408101 100644 --- a/chrome/browser/extensions/extension_special_storage_policy.cc +++ b/chrome/browser/extensions/extension_special_storage_policy.cc
@@ -223,10 +223,9 @@ const GURL& origin, int change_flags) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ExtensionSpecialStoragePolicy::NotifyGranted, this, - origin, change_flags)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ExtensionSpecialStoragePolicy::NotifyGranted, + this, origin, change_flags)); return; } SpecialStoragePolicy::NotifyGranted(origin, change_flags); @@ -236,10 +235,9 @@ const GURL& origin, int change_flags) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ExtensionSpecialStoragePolicy::NotifyRevoked, this, - origin, change_flags)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ExtensionSpecialStoragePolicy::NotifyRevoked, + this, origin, change_flags)); return; } SpecialStoragePolicy::NotifyRevoked(origin, change_flags); @@ -247,7 +245,7 @@ void ExtensionSpecialStoragePolicy::NotifyCleared() { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ExtensionSpecialStoragePolicy::NotifyCleared, this)); return;
diff --git a/chrome/browser/extensions/extension_system_impl.cc b/chrome/browser/extensions/extension_system_impl.cc index 0ee6aea5..fbe84d7 100644 --- a/chrome/browser/extensions/extension_system_impl.cc +++ b/chrome/browser/extensions/extension_system_impl.cc
@@ -476,7 +476,7 @@ notifications_disabled = !notifier_state_tracker->IsNotifierEnabled(notifier_id); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&InfoMap::AddExtension, info_map(), base::RetainedRef(extension), install_time, @@ -487,9 +487,9 @@ void ExtensionSystemImpl::UnregisterExtensionWithRequestContexts( const std::string& extension_id, const UnloadedExtensionReason reason) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&InfoMap::RemoveExtension, info_map(), - extension_id, reason)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&InfoMap::RemoveExtension, info_map(), + extension_id, reason)); } } // namespace extensions
diff --git a/chrome/browser/extensions/external_pref_loader.cc b/chrome/browser/extensions/external_pref_loader.cc index 62b0203..f4b5108 100644 --- a/chrome/browser/extensions/external_pref_loader.cc +++ b/chrome/browser/extensions/external_pref_loader.cc
@@ -268,9 +268,9 @@ if (!prefs->empty()) CHECK(!base_path_.empty()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ExternalPrefLoader::LoadFinished, - this, std::move(prefs))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ExternalPrefLoader::LoadFinished, this, + std::move(prefs))); } void ExternalPrefLoader::ReadExternalExtensionPrefFile(
diff --git a/chrome/browser/extensions/external_pref_loader_unittest.cc b/chrome/browser/extensions/external_pref_loader_unittest.cc index c3ba3c03..abfd5af 100644 --- a/chrome/browser/extensions/external_pref_loader_unittest.cc +++ b/chrome/browser/extensions/external_pref_loader_unittest.cc
@@ -67,8 +67,8 @@ load_callback_(std::move(load_callback)) {} void LoadOnFileThread() override { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(load_callback_)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(load_callback_)); } private:
diff --git a/chrome/browser/extensions/external_registry_loader_win.cc b/chrome/browser/extensions/external_registry_loader_win.cc index 97ac4e57..eab86f4 100644 --- a/chrome/browser/extensions/external_registry_loader_win.cc +++ b/chrome/browser/extensions/external_registry_loader_win.cc
@@ -207,7 +207,7 @@ std::unique_ptr<base::DictionaryValue> prefs = LoadPrefsOnBlockingThread(); LOCAL_HISTOGRAM_TIMES("Extensions.ExternalRegistryLoaderWin", base::TimeTicks::Now() - start_time); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ExternalRegistryLoader::CompleteLoadAndStartWatchingRegistry, this, @@ -264,8 +264,8 @@ scoped_refptr<base::SequencedTaskRunner> ExternalRegistryLoader::GetOrCreateTaskRunner() { if (!task_runner_.get()) { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {// Requires I/O for registry. + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), // Requires I/O for registry. base::MayBlock(), // Inherit priority. @@ -282,9 +282,9 @@ std::unique_ptr<base::DictionaryValue> prefs = LoadPrefsOnBlockingThread(); LOCAL_HISTOGRAM_TIMES("Extensions.ExternalRegistryLoaderWinUpdate", base::TimeTicks::Now() - start_time); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ExternalRegistryLoader::OnUpdated, - this, base::Passed(&prefs))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ExternalRegistryLoader::OnUpdated, this, + base::Passed(&prefs))); } } // namespace extensions
diff --git a/chrome/browser/extensions/startup_helper.cc b/chrome/browser/extensions/startup_helper.cc index fc818d3..093de200 100644 --- a/chrome/browser/extensions/startup_helper.cc +++ b/chrome/browser/extensions/startup_helper.cc
@@ -112,18 +112,16 @@ const base::Optional<int>& dnr_ruleset_checksum) override { DCHECK(GetExtensionFileTaskRunner()->RunsTasksInCurrentSequence()); success_ = true; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ValidateCrxHelper::FinishOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ValidateCrxHelper::FinishOnUIThread, this)); } void OnUnpackFailure(const CrxInstallError& error) override { DCHECK(GetExtensionFileTaskRunner()->RunsTasksInCurrentSequence()); success_ = false; error_ = error.message(); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ValidateCrxHelper::FinishOnUIThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ValidateCrxHelper::FinishOnUIThread, this)); } void FinishOnUIThread() {
diff --git a/chrome/browser/extensions/unpacked_installer.cc b/chrome/browser/extensions/unpacked_installer.cc index 4eed279..8102059 100644 --- a/chrome/browser/extensions/unpacked_installer.cc +++ b/chrome/browser/extensions/unpacked_installer.cc
@@ -300,7 +300,7 @@ void UnpackedInstaller::GetAbsolutePath() { extension_path_ = base::MakeAbsoluteFilePath(extension_path_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&UnpackedInstaller::CheckExtensionFileAccess, this)); } @@ -323,16 +323,14 @@ void UnpackedInstaller::LoadWithFileAccess(int flags) { std::string error; if (!LoadExtension(Manifest::UNPACKED, flags, &error)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&UnpackedInstaller::ReportExtensionLoadError, this, - error)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&UnpackedInstaller::ReportExtensionLoadError, + this, error)); return; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&UnpackedInstaller::StartInstallChecks, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&UnpackedInstaller::StartInstallChecks, this)); } void UnpackedInstaller::ReportExtensionLoadError(const std::string &error) {
diff --git a/chrome/browser/extensions/updater/extension_cache_fake.cc b/chrome/browser/extensions/updater/extension_cache_fake.cc index 52fb42e..7046fe1 100644 --- a/chrome/browser/extensions/updater/extension_cache_fake.cc +++ b/chrome/browser/extensions/updater/extension_cache_fake.cc
@@ -19,11 +19,11 @@ } void ExtensionCacheFake::Start(const base::Closure& callback) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, callback); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, callback); } void ExtensionCacheFake::Shutdown(const base::Closure& callback) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, callback); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, callback); } void ExtensionCacheFake::AllowCaching(const std::string& id) { @@ -54,8 +54,8 @@ if (base::Contains(allowed_extensions_, id)) { cache_[id].first = version; cache_[id].second = file_path; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(callback, file_path, false)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(callback, file_path, false)); } else { callback.Run(file_path, true); }
diff --git a/chrome/browser/extensions/updater/extension_cache_impl.cc b/chrome/browser/extensions/updater/extension_cache_impl.cc index b00fe0d..70e3a69e 100644 --- a/chrome/browser/extensions/updater/extension_cache_impl.cc +++ b/chrome/browser/extensions/updater/extension_cache_impl.cc
@@ -33,8 +33,8 @@ delegate->GetCacheDir(), delegate->GetMaximumCacheSize(), delegate->GetMaximumCacheAge(), - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), task_priority, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), task_priority, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}))), weak_ptr_factory_(this) { notification_registrar_.Add(
diff --git a/chrome/browser/extensions/updater/extension_updater.cc b/chrome/browser/extensions/updater/extension_updater.cc index bfe575a..45ece00 100644 --- a/chrome/browser/extensions/updater/extension_updater.cc +++ b/chrome/browser/extensions/updater/extension_updater.cc
@@ -205,11 +205,11 @@ const double jitter_factor = RandDouble() * 0.4 + 0.8; base::TimeDelta delay = base::TimeDelta::FromMilliseconds( static_cast<int64_t>(frequency_.InMilliseconds() * jitter_factor)); - base::PostDelayedTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, BrowserThread::UI}, - base::BindOnce(&ExtensionUpdater::NextCheck, - weak_ptr_factory_.GetWeakPtr()), - delay); + base::PostDelayedTask(FROM_HERE, + {base::TaskPriority::BEST_EFFORT, BrowserThread::UI}, + base::BindOnce(&ExtensionUpdater::NextCheck, + weak_ptr_factory_.GetWeakPtr()), + delay); } void ExtensionUpdater::NextCheck() { @@ -223,10 +223,10 @@ DCHECK(alive_); if (will_check_soon_) return; - if (base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, BrowserThread::UI}, - base::BindOnce(&ExtensionUpdater::DoCheckSoon, - weak_ptr_factory_.GetWeakPtr()))) { + if (base::PostTask(FROM_HERE, + {base::TaskPriority::BEST_EFFORT, BrowserThread::UI}, + base::BindOnce(&ExtensionUpdater::DoCheckSoon, + weak_ptr_factory_.GetWeakPtr()))) { will_check_soon_ = true; } else { NOTREACHED();
diff --git a/chrome/browser/extensions/updater/local_extension_cache.cc b/chrome/browser/extensions/updater/local_extension_cache.cc index 4f791ac5..a02ec696 100644 --- a/chrome/browser/extensions/updater/local_extension_cache.cc +++ b/chrome/browser/extensions/updater/local_extension_cache.cc
@@ -277,10 +277,9 @@ } } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&LocalExtensionCache::OnCacheStatusChecked, local_cache, - exists, callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&LocalExtensionCache::OnCacheStatusChecked, + local_cache, exists, callback)); } void LocalExtensionCache::OnCacheStatusChecked(bool ready, @@ -293,7 +292,7 @@ if (ready) { CheckCacheContents(callback); } else { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LocalExtensionCache::CheckCacheStatus, weak_ptr_factory_.GetWeakPtr(), callback), @@ -316,7 +315,7 @@ const base::Closure& callback) { std::unique_ptr<CacheMap> cache_content(new CacheMap); BackendCheckCacheContentsInternal(cache_dir, cache_content.get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LocalExtensionCache::OnCacheContentsChecked, local_cache, std::move(cache_content), callback)); @@ -528,7 +527,7 @@ } } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&LocalExtensionCache::OnCacheEntryInstalled, local_cache, id,
diff --git a/chrome/browser/extensions/updater/local_extension_cache_unittest.cc b/chrome/browser/extensions/updater/local_extension_cache_unittest.cc index 6c96312f..5728447 100644 --- a/chrome/browser/extensions/updater/local_extension_cache_unittest.cc +++ b/chrome/browser/extensions/updater/local_extension_cache_unittest.cc
@@ -122,7 +122,7 @@ LocalExtensionCache cache( cache_dir, 1000, base::TimeDelta::FromDays(30), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()})); cache.SetCacheStatusPollingDelayForTests(base::TimeDelta()); bool initialized = false; @@ -170,7 +170,7 @@ LocalExtensionCache cache( cache_dir, 1000, base::TimeDelta::FromDays(30), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()})); cache.SetCacheStatusPollingDelayForTests(base::TimeDelta()); bool initialized = false; @@ -207,7 +207,7 @@ LocalExtensionCache cache( cache_dir, 1000, base::TimeDelta::FromDays(30), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()})); cache.SetCacheStatusPollingDelayForTests(base::TimeDelta()); bool initialized = false; @@ -243,7 +243,7 @@ LocalExtensionCache cache( cache_dir, 1000, base::TimeDelta::FromDays(30), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()})); cache.SetCacheStatusPollingDelayForTests(base::TimeDelta()); bool initialized = false; @@ -310,7 +310,7 @@ LocalExtensionCache cache( cache_dir, 1000, base::TimeDelta::FromDays(30), - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()})); cache.SetCacheStatusPollingDelayForTests(base::TimeDelta()); bool initialized = false;
diff --git a/chrome/browser/external_protocol/external_protocol_handler.cc b/chrome/browser/external_protocol/external_protocol_handler.cc index 2fa76ce8..1bf4b63 100644 --- a/chrome/browser/external_protocol/external_protocol_handler.cc +++ b/chrome/browser/external_protocol/external_protocol_handler.cc
@@ -112,7 +112,7 @@ platform_util::OpenExternal( Profile::FromBrowserContext(web_contents->GetBrowserContext()), url); -#if !defined(OS_ANDROID) +#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) // If the protocol navigation occurs in a new tab, close it. // Avoid calling CloseContents if the tab is not in this browser's tab strip // model; this can happen if the protocol was initiated by something
diff --git a/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc b/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc index cc4676f9..5a6c854 100644 --- a/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc +++ b/chrome/browser/external_protocol/external_protocol_handler_browsertest.cc
@@ -2,32 +2,73 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/scoped_observer.h" #include "build/build_config.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test_utils.h" +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + class ExternalProtocolHandlerBrowserTest : public InProcessBrowserTest {}; -const char kScript[] = - "new Promise(res => {" - " const tab = window.open('mailto:test@site.test', '_blank');" - " tab.addEventListener('unload', () => {" - " res(true);" - " });" - "});"; +// Observe that the tab is created then automatically closed. +class TabAddedRemovedObserver : public TabStripModelObserver { + public: + explicit TabAddedRemovedObserver(TabStripModel* tab_strip_model) + : scoped_observer_(this) { + scoped_observer_.Add(tab_strip_model); + } -// http://crbug.com/982234 -#if defined(OS_WIN) -#define MAYBE_AutoCloseTabOnNonWebProtocolNavigation \ - DISABLED_AutoCloseTabOnNonWebProtocolNavigation -#else -#define MAYBE_AutoCloseTabOnNonWebProtocolNavigation \ - AutoCloseTabOnNonWebProtocolNavigation -#endif + void OnTabStripModelChanged( + TabStripModel* tab_strip_model, + const TabStripModelChange& change, + const TabStripSelectionChange& selection) override { + if (change.type() == TabStripModelChange::kInserted) { + inserted_ = true; + return; + } + if (change.type() == TabStripModelChange::kRemoved) { + EXPECT_TRUE(inserted_); + removed_ = true; + loop_.Quit(); + return; + } + NOTREACHED(); + } + + void Wait() { + if (inserted_ && removed_) + return; + loop_.Run(); + } + + private: + bool inserted_ = false; + bool removed_ = false; + base::RunLoop loop_; + ScopedObserver<TabStripModel, TabAddedRemovedObserver> scoped_observer_; +}; + IN_PROC_BROWSER_TEST_F(ExternalProtocolHandlerBrowserTest, - MAYBE_AutoCloseTabOnNonWebProtocolNavigation) { + AutoCloseTabOnNonWebProtocolNavigation) { +#if defined(OS_WIN) + // On Win 7 the protocol is registered to be handled by Chrome and thus never + // reaches the ExternalProtocolHandler so we skip the test. For + // more info see installer/util/shell_util.cc:GetShellIntegrationEntries + if (base::win::GetVersion() < base::win::Version::WIN8) + return; +#endif + content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - EXPECT_EQ(true, EvalJs(web_contents, kScript)); + TabAddedRemovedObserver observer(browser()->tab_strip_model()); + ASSERT_EQ(browser()->tab_strip_model()->count(), 1); + ASSERT_TRUE( + ExecJs(web_contents, "window.open('mailto:test@site.test', '_blank');")); + observer.Wait(); + EXPECT_EQ(browser()->tab_strip_model()->count(), 1); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index d0c48cda..9fb248c 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1507,7 +1507,7 @@ { "name": "enable-query-in-omnibox", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "enable-quic", @@ -2498,12 +2498,12 @@ { "name": "omnibox-experimental-keyword-mode", "owners": [ "krb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "omnibox-group-suggestions-by-search-vs-url", "owners": [ "krb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 78 }, { "name": "omnibox-material-design-weather-icons", @@ -2523,11 +2523,11 @@ { "name": "omnibox-pedal-suggestions", "owners": [ "orinj", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "expiry_milestone": 80 }, { "name": "omnibox-reverse-answers", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { @@ -2537,8 +2537,8 @@ }, { "name": "omnibox-rich-entity-suggestions", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 80 }, { "name": "omnibox-search-engine-logo", @@ -2568,27 +2568,27 @@ { "name": "omnibox-ui-cues-for-search-history-matches", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 78 }, { "name": "omnibox-ui-hide-steady-state-url-path-query-and-ref", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-hide-steady-state-url-scheme", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-hide-steady-state-url-trivial-subdomains", - "owners": [ "chrome-omnibox-team@google.com" ], + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], "expiry_milestone": 76 }, { "name": "omnibox-ui-max-autocomplete-matches", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 76 + "owners": [ "jdonnelly", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 80 }, { "name": "omnibox-ui-one-click-unelide", @@ -2597,33 +2597,33 @@ }, { "name": "omnibox-ui-show-placeholder-when-caret-showing", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 76 }, { "name": "omnibox-ui-show-suggestion-favicons", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 76 }, { "name": "omnibox-ui-swap-title-and-url", - "owners": [ "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], + "expiry_milestone": 76 }, { "name": "omnibox-ui-vertical-margin", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 76 }, { "name": "omnibox-ui-vertical-margin-limit-to-non-touch-only", "owners": [ "tommycli", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 80 + "expiry_milestone": 76 }, { "name": "omnibox-wrap-popup-position", "owners": [ "krb", "chrome-omnibox-team@google.com" ], - "expiry_milestone": 81 + "expiry_milestone": 78 }, { "name": "omnibox-zero-suggestions-on-ntp",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 2b7af74..e311603 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3607,10 +3607,6 @@ const char kPdfFormSaveDescription[] = "Enable saving PDFs with filled form data."; -const char kPdfIsolationName[] = "PDF Isolation"; -const char kPdfIsolationDescription[] = - "Render PDF files from different origins in different plugin processes."; - #endif // BUILDFLAG(ENABLE_PLUGINS) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID)
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 0a0619f..30b0894 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2192,9 +2192,6 @@ extern const char kPdfFormSaveName[]; extern const char kPdfFormSaveDescription[]; -extern const char kPdfIsolationName[]; -extern const char kPdfIsolationDescription[]; - #endif // BUILDFLAG(ENABLE_PLUGINS) #if defined(TOOLKIT_VIEWS) || defined(OS_ANDROID)
diff --git a/chrome/browser/google/OWNERS b/chrome/browser/google/OWNERS index 558e5509..1461f9d 100644 --- a/chrome/browser/google/OWNERS +++ b/chrome/browser/google/OWNERS
@@ -2,3 +2,4 @@ pkasting@chromium.org # COMPONENT: Internals +# TEAM: chromium-dev@chromium.org
diff --git a/chrome/browser/google/chrome_google_url_tracker_client.cc b/chrome/browser/google/chrome_google_url_tracker_client.cc deleted file mode 100644 index 360869b..0000000 --- a/chrome/browser/google/chrome_google_url_tracker_client.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/google/chrome_google_url_tracker_client.h" - -#include "base/command_line.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/chrome_switches.h" -#include "content/public/browser/storage_partition.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" - -ChromeGoogleURLTrackerClient::ChromeGoogleURLTrackerClient(Profile* profile) - : profile_(profile) { -} - -ChromeGoogleURLTrackerClient::~ChromeGoogleURLTrackerClient() { -} - -bool ChromeGoogleURLTrackerClient::IsBackgroundNetworkingEnabled() { - return !base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDisableBackgroundNetworking); -} - -PrefService* ChromeGoogleURLTrackerClient::GetPrefs() { - return profile_->GetPrefs(); -} - -network::mojom::URLLoaderFactory* -ChromeGoogleURLTrackerClient::GetURLLoaderFactory() { - return content::BrowserContext::GetDefaultStoragePartition(profile_) - ->GetURLLoaderFactoryForBrowserProcess() - .get(); -}
diff --git a/chrome/browser/google/chrome_google_url_tracker_client.h b/chrome/browser/google/chrome_google_url_tracker_client.h deleted file mode 100644 index 74b0565..0000000 --- a/chrome/browser/google/chrome_google_url_tracker_client.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_GOOGLE_CHROME_GOOGLE_URL_TRACKER_CLIENT_H_ -#define CHROME_BROWSER_GOOGLE_CHROME_GOOGLE_URL_TRACKER_CLIENT_H_ - -#include "base/macros.h" -#include "components/google/core/browser/google_url_tracker_client.h" - -class Profile; - -class ChromeGoogleURLTrackerClient : public GoogleURLTrackerClient { - public: - explicit ChromeGoogleURLTrackerClient(Profile* profile); - ~ChromeGoogleURLTrackerClient() override; - - // GoogleURLTrackerClient: - bool IsBackgroundNetworkingEnabled() override; - PrefService* GetPrefs() override; - network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; - - private: - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(ChromeGoogleURLTrackerClient); -}; - -#endif // CHROME_BROWSER_GOOGLE_CHROME_GOOGLE_URL_TRACKER_CLIENT_H_
diff --git a/chrome/browser/google/google_url_tracker_factory.cc b/chrome/browser/google/google_url_tracker_factory.cc deleted file mode 100644 index 3cc8450..0000000 --- a/chrome/browser/google/google_url_tracker_factory.cc +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/google/google_url_tracker_factory.h" - -#include <utility> - -#include "base/bind.h" -#include "base/feature_list.h" -#include "chrome/browser/google/chrome_google_url_tracker_client.h" -#include "chrome/browser/profiles/incognito_helpers.h" -#include "chrome/browser/profiles/profile.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/browser/google_url_tracker.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/network_service_instance.h" - -// static -GoogleURLTracker* GoogleURLTrackerFactory::GetForProfile(Profile* profile) { - return static_cast<GoogleURLTracker*>( - GetInstance()->GetServiceForBrowserContext(profile, true)); -} - -// static -GoogleURLTrackerFactory* GoogleURLTrackerFactory::GetInstance() { - return base::Singleton<GoogleURLTrackerFactory>::get(); -} - -namespace { - -std::unique_ptr<KeyedService> BuildGoogleURLTracker( - content::BrowserContext* context) { - // Delete this now-unused pref. - // At some point in the future, this code can be removed entirely. - static_cast<Profile*>(context)->GetOriginalProfile()->GetPrefs()->ClearPref( - prefs::kLastPromptedGoogleURL); - - auto client = std::make_unique<ChromeGoogleURLTrackerClient>( - Profile::FromBrowserContext(context)); - return std::make_unique<GoogleURLTracker>( - std::move(client), GoogleURLTracker::ALWAYS_DOT_COM_MODE, - content::GetNetworkConnectionTracker()); -} - -} // namespace - -// static -BrowserContextKeyedServiceFactory::TestingFactory -GoogleURLTrackerFactory::GetDefaultFactory() { - return base::BindRepeating(&BuildGoogleURLTracker); -} - -GoogleURLTrackerFactory::GoogleURLTrackerFactory() - : BrowserContextKeyedServiceFactory( - "GoogleURLTracker", - BrowserContextDependencyManager::GetInstance()) { -} - -GoogleURLTrackerFactory::~GoogleURLTrackerFactory() { -} - -KeyedService* GoogleURLTrackerFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return BuildGoogleURLTracker(context).release(); -} - -void GoogleURLTrackerFactory::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* user_prefs) { - GoogleURLTracker::RegisterProfilePrefs(user_prefs); -} - -content::BrowserContext* GoogleURLTrackerFactory::GetBrowserContextToUse( - content::BrowserContext* context) const { - return chrome::GetBrowserContextRedirectedInIncognito(context); -} - -bool GoogleURLTrackerFactory::ServiceIsCreatedWithBrowserContext() const { - return true; -} - -bool GoogleURLTrackerFactory::ServiceIsNULLWhileTesting() const { - return true; -}
diff --git a/chrome/browser/google/google_url_tracker_factory.h b/chrome/browser/google/google_url_tracker_factory.h deleted file mode 100644 index cd71b7e3..0000000 --- a/chrome/browser/google/google_url_tracker_factory.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_ -#define CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_ - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class GoogleURLTracker; -class Profile; - -// Singleton that owns all GoogleURLTrackers and associates them with Profiles. -class GoogleURLTrackerFactory : public BrowserContextKeyedServiceFactory { - public: - // Returns the GoogleURLTracker for |profile|. This may return NULL for a - // testing profile. - static GoogleURLTracker* GetForProfile(Profile* profile); - - static GoogleURLTrackerFactory* GetInstance(); - - // Returns the default factory used to build GoogleURLTracker. Can be - // registered with SetTestingFactory to use a real GoogleURLTracker instance - // for testing. - static TestingFactory GetDefaultFactory(); - - private: - friend struct base::DefaultSingletonTraits<GoogleURLTrackerFactory>; - friend class GoogleURLTrackerFactoryTest; - - GoogleURLTrackerFactory(); - ~GoogleURLTrackerFactory() override; - - // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* profile) const override; - void RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - content::BrowserContext* GetBrowserContextToUse( - content::BrowserContext* context) const override; - bool ServiceIsCreatedWithBrowserContext() const override; - bool ServiceIsNULLWhileTesting() const override; - - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerFactory); -}; - -#endif // CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_
diff --git a/chrome/browser/google/google_url_tracker_factory_unittest.cc b/chrome/browser/google/google_url_tracker_factory_unittest.cc deleted file mode 100644 index 4a5c079d..0000000 --- a/chrome/browser/google/google_url_tracker_factory_unittest.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/google/google_url_tracker_factory.h" - -#include "base/test/scoped_feature_list.h" -#include "base/test/scoped_task_environment.h" -#include "chrome/test/base/testing_profile.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/browser/google_url_tracker.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -class GoogleURLTrackerFactoryTest : public testing::Test { - protected: - void SetUp() override { - // TestingProfile requires a testing factory to be set otherwise it - // registers a factory that returns nullptr. Here we simply use the real - // factory. - GoogleURLTrackerFactory::GetInstance()->SetTestingFactory( - &profile_, GoogleURLTrackerFactory::GetDefaultFactory()); - } - - // Required because GetForProfile() wants to run on the browser thread. - content::TestBrowserThreadBundle test_browser_thread_bundle_; - TestingProfile profile_; - base::test::ScopedFeatureList scoped_feature_list_; -}; - -TEST_F(GoogleURLTrackerFactoryTest, AlwaysUsesDotCom) { - profile_.GetPrefs()->SetString(prefs::kLastKnownGoogleURL, - "https://www.google.co.uk/"); - GoogleURLTracker* tracker = - GoogleURLTrackerFactory::GetInstance()->GetForProfile(&profile_); - - ASSERT_NE(nullptr, tracker); - EXPECT_EQ(GURL("https://www.google.com/"), tracker->google_url()); -}
diff --git a/chrome/browser/importer/in_process_importer_bridge.cc b/chrome/browser/importer/in_process_importer_bridge.cc index 46041364..28f9e9a 100644 --- a/chrome/browser/importer/in_process_importer_bridge.cc +++ b/chrome/browser/importer/in_process_importer_bridge.cc
@@ -116,9 +116,9 @@ auto default_turl = search_engine_for_url.end(); for (auto xml_iter = xml_data.begin(); xml_iter != xml_data.end(); ++xml_iter) { - std::unique_ptr<TemplateURL> template_url = TemplateURLParser::Parse( - UIThreadSearchTermsData(nullptr), xml_iter->data(), xml_iter->length(), - ¶m_filter); + std::unique_ptr<TemplateURL> template_url = + TemplateURLParser::Parse(UIThreadSearchTermsData(), xml_iter->data(), + xml_iter->length(), ¶m_filter); if (template_url) { auto iter = search_engine_for_url.find(template_url->url()); if (iter == search_engine_for_url.end()) {
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc index cff2e4e..c8cdddf 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.cc
@@ -41,7 +41,8 @@ using UserAction = LookalikeUrlInterstitialPage::UserAction; using NavigationSuggestionEvent = lookalikes::LookalikeUrlNavigationThrottle::NavigationSuggestionEvent; -using DomainInfo = lookalikes::DomainInfo; +using lookalikes::DomainInfo; +using url_formatter::TopDomainEntry; typedef content::NavigationThrottle::ThrottleCheckResult ThrottleCheckResult; @@ -68,9 +69,9 @@ // Top domains are only accessible through their skeletons, so query the top // domains trie for each skeleton of this domain. for (const std::string& skeleton : domain_info.skeletons) { - const std::string top_domain = + const TopDomainEntry top_domain = url_formatter::LookupSkeletonInTopDomains(skeleton); - if (domain_info.domain_and_registry == top_domain) { + if (domain_info.domain_and_registry == top_domain.domain) { return true; } } @@ -104,7 +105,8 @@ base::UTF8ToUTF16(navigated_skeleton), base::UTF8ToUTF16(top_domain_skeleton))) { const std::string top_domain = - url_formatter::LookupSkeletonInTopDomains(top_domain_skeleton); + url_formatter::LookupSkeletonInTopDomains(top_domain_skeleton) + .domain; DCHECK(!top_domain.empty()); // If the only difference between the navigated and top // domains is the registry part, this is unlikely to be a spoofing @@ -439,8 +441,16 @@ return content::NavigationThrottle::PROCEED; } + ukm::SourceId source_id = ukm::ConvertToSourceId( + navigation_handle()->GetNavigationId(), ukm::SourceIdType::NAVIGATION_ID); + + bool record_ukm; if (!GetMatchingDomain(navigated_domain, engaged_sites, &matched_domain, - &match_type)) { + &match_type, &record_ukm)) { + if (record_ukm) { + LookalikeUrlInterstitialPage::RecordUkmEvent( + source_id, match_type, UserAction::kInterstitialNotShown); + } return content::NavigationThrottle::PROCEED; } DCHECK(!matched_domain.empty()); @@ -450,8 +460,6 @@ return content::NavigationThrottle::PROCEED; } - ukm::SourceId source_id = ukm::ConvertToSourceId( - navigation_handle()->GetNavigationId(), ukm::SourceIdType::NAVIGATION_ID); if (ShouldDisplayInterstitial(match_type)) { // matched_domain can be a top domain or an engaged domain. Simply use its @@ -504,10 +512,13 @@ const DomainInfo& navigated_domain, const std::vector<DomainInfo>& engaged_sites, std::string* matched_domain, - MatchType* match_type) { + MatchType* match_type, + bool* force_record_ukm) { DCHECK(!navigated_domain.domain_and_registry.empty()); DCHECK(matched_domain); DCHECK(match_type); + DCHECK(force_record_ukm); + *force_record_ukm = false; if (navigated_domain.idn_result.has_idn_component) { // If the navigated domain is IDN, check its skeleton against engaged sites @@ -521,18 +532,26 @@ return true; } - if (!navigated_domain.idn_result.matching_top_domain.empty()) { + if (!navigated_domain.idn_result.matching_top_domain.domain.empty()) { // In practice, this is not possible since the top domain list does not // contain IDNs, so domain_and_registry can't both have IDN and be a top // domain. Still, sanity check in case the top domain list changes in the // future. // At this point, navigated domain should not be a top domain. DCHECK_NE(navigated_domain.domain_and_registry, - navigated_domain.idn_result.matching_top_domain); + navigated_domain.idn_result.matching_top_domain.domain); RecordEvent(NavigationSuggestionEvent::kMatchTopSite); - *matched_domain = navigated_domain.idn_result.matching_top_domain; + *matched_domain = navigated_domain.idn_result.matching_top_domain.domain; *match_type = MatchType::kTopSite; - return true; + + if (navigated_domain.idn_result.matching_top_domain.is_top_500) { + return true; + } else { + // We will not show an interstitial if the domain is not top 500 but we + // still want to record metrics. + *force_record_ukm = true; + return false; + } } }
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.h b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.h index 5d32af2..87ff9a2 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle.h +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle.h
@@ -100,14 +100,17 @@ LookalikeUrlInterstitialPage::MatchType match_type) const; // Returns true if a domain is visually similar to the hostname of |url|. The - // matching domain can be a top domain or an engaged site. Similarity check - // is made using both visual skeleton and edit distance comparison. If this - // returns true, match details will be written into |matched_domain| and + // matching domain can be a top 500 domain or an engaged site. Similarity + // check is made using both visual skeleton and edit distance comparison. If + // this returns true, match details will be written into |matched_domain| and // |match_type|. They cannot be nullptr. + // |force_record_ukm| can be set to true even if the function returns false. + // In this case, the caller must record a UKM using |match_type|. bool GetMatchingDomain(const DomainInfo& navigated_domain, const std::vector<DomainInfo>& engaged_sites, std::string* matched_domain, - LookalikeUrlInterstitialPage::MatchType* match_type); + LookalikeUrlInterstitialPage::MatchType* match_type, + bool* force_record_ukm); ThrottleCheckResult ShowInterstitial( const GURL& safe_domain,
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc index 9053b9a..3399477 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc
@@ -448,6 +448,24 @@ CheckUkm({kNavigatedUrl}, "MatchType", MatchType::kTopSite); } +// Similar to Idn_TopDomain_Match but the domain is not in top 500. Should not +// show an interstitial, but should still record metrics. +IN_PROC_BROWSER_TEST_P(LookalikeUrlNavigationThrottleBrowserTest, + Idn_TopDomain_Match_Not500) { + const GURL kNavigatedUrl = GetURL("googlé.sk"); + // Even if the navigated site has a low engagement score, it should be + // considered for lookalike suggestions. + SetEngagementScore(browser(), kNavigatedUrl, kLowEngagement); + + base::HistogramTester histograms; + TestInterstitialNotShown(browser(), kNavigatedUrl); + histograms.ExpectTotalCount(LookalikeUrlNavigationThrottle::kHistogramName, + 1); + histograms.ExpectBucketCount(LookalikeUrlNavigationThrottle::kHistogramName, + NavigationSuggestionEvent::kMatchTopSite, 1); + CheckUkm({kNavigatedUrl}, "MatchType", MatchType::kTopSite); +} + // Same as Idn_TopDomain_Match, but this time the domain contains characters // from different scripts, failing the checks in IDN spoof checker before // reaching the top domain check. In this case, the end result is the same, but
diff --git a/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc b/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc index 4b6f5ce..750a1e8 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list_unittest.cc
@@ -191,7 +191,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.native_widget = new views::DesktopNativeWidgetAura(widget.get()); params.bounds = gfx::Rect(0, 0, 20, 20); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/chrome/browser/net/errorpage_browsertest.cc b/chrome/browser/net/errorpage_browsertest.cc index 91e6839..348db55 100644 --- a/chrome/browser/net/errorpage_browsertest.cc +++ b/chrome/browser/net/errorpage_browsertest.cc
@@ -385,7 +385,7 @@ ASSERT_TRUE(embedded_test_server()->Start()); - UIThreadSearchTermsData search_terms_data(browser()->profile()); + UIThreadSearchTermsData search_terms_data; search_term_url_ = GURL(search_terms_data.GoogleBaseURLValue()); }
diff --git a/chrome/browser/notifications/scheduler/display_agent_android.cc b/chrome/browser/notifications/scheduler/display_agent_android.cc index 2a3cd3e..9aac0217 100644 --- a/chrome/browser/notifications/scheduler/display_agent_android.cc +++ b/chrome/browser/notifications/scheduler/display_agent_android.cc
@@ -91,13 +91,6 @@ env, static_cast<int>(system_data->type), ConvertUTF8ToJavaString(env, system_data->guid)); - ShowNotificationInternal(env, java_notification_data, java_system_data); -} - -void DisplayAgentAndroid::ShowNotificationInternal( - JNIEnv* env, - const base::android::JavaRef<jobject>& java_notification_data, - const base::android::JavaRef<jobject>& java_system_data) { Java_DisplayAgent_showNotification(env, java_notification_data, java_system_data); }
diff --git a/chrome/browser/notifications/scheduler/display_agent_android.h b/chrome/browser/notifications/scheduler/display_agent_android.h index f012229..e1d91e6f 100644 --- a/chrome/browser/notifications/scheduler/display_agent_android.h +++ b/chrome/browser/notifications/scheduler/display_agent_android.h
@@ -16,13 +16,6 @@ DisplayAgentAndroid(); ~DisplayAgentAndroid() override; - protected: - // Protected for testing. - virtual void ShowNotificationInternal( - JNIEnv* env, - const base::android::JavaRef<jobject>& notificationData, - const base::android::JavaRef<jobject>& systemData); - private: void ShowNotification( std::unique_ptr<notifications::NotificationData> notification_data,
diff --git a/chrome/browser/notifications/scheduler/internal/background_task_coordinator.cc b/chrome/browser/notifications/scheduler/internal/background_task_coordinator.cc index 88d22a4..ec41955c 100644 --- a/chrome/browser/notifications/scheduler/internal/background_task_coordinator.cc +++ b/chrome/browser/notifications/scheduler/internal/background_task_coordinator.cc
@@ -188,26 +188,57 @@ return base::RandDouble() * time_window; } -BackgroundTaskCoordinator::BackgroundTaskCoordinator( +class BackgroundTaskCoordinatorImpl : public BackgroundTaskCoordinator { + public: + BackgroundTaskCoordinatorImpl( + std::unique_ptr<NotificationBackgroundTaskScheduler> background_task, + const SchedulerConfig* config, + TimeRandomizer time_randomizer, + base::Clock* clock) + : background_task_(std::move(background_task)), + config_(config), + time_randomizer_(time_randomizer), + clock_(clock) {} + + ~BackgroundTaskCoordinatorImpl() override = default; + + private: + // BackgroundTaskCoordinator implementation. + void ScheduleBackgroundTask(Notifications notifications, + ClientStates client_states, + SchedulerTaskTime task_start_time) override { + auto helper = std::make_unique<BackgroundTaskCoordinatorHelper>( + background_task_.get(), config_, time_randomizer_, clock_); + helper->ScheduleBackgroundTask(std::move(notifications), + std::move(client_states), task_start_time); + } + + // The class that actually schedules platform background task. + std::unique_ptr<NotificationBackgroundTaskScheduler> background_task_; + + // System configuration. + const SchedulerConfig* config_; + + // Randomize the time to show the notification, to avoid large number of users + // to perform actions at the same time. + TimeRandomizer time_randomizer_; + + // Clock to query the current timestamp. + base::Clock* clock_; + + DISALLOW_COPY_AND_ASSIGN(BackgroundTaskCoordinatorImpl); +}; + +// static +std::unique_ptr<BackgroundTaskCoordinator> BackgroundTaskCoordinator::Create( std::unique_ptr<NotificationBackgroundTaskScheduler> background_task, const SchedulerConfig* config, TimeRandomizer time_randomizer, - base::Clock* clock) - : background_task_(std::move(background_task)), - config_(config), - time_randomizer_(time_randomizer), - clock_(clock) {} + base::Clock* clock) { + return std::make_unique<BackgroundTaskCoordinatorImpl>( + std::move(background_task), config, time_randomizer, clock); +} BackgroundTaskCoordinator::~BackgroundTaskCoordinator() = default; -void BackgroundTaskCoordinator::ScheduleBackgroundTask( - Notifications notifications, - ClientStates client_states, - SchedulerTaskTime task_start_time) { - auto helper = std::make_unique<BackgroundTaskCoordinatorHelper>( - background_task_.get(), config_, time_randomizer_, clock_); - helper->ScheduleBackgroundTask(std::move(notifications), - std::move(client_states), task_start_time); -} - } // namespace notifications
diff --git a/chrome/browser/notifications/scheduler/internal/background_task_coordinator.h b/chrome/browser/notifications/scheduler/internal/background_task_coordinator.h index ebf158a..04dc4ec 100644 --- a/chrome/browser/notifications/scheduler/internal/background_task_coordinator.h +++ b/chrome/browser/notifications/scheduler/internal/background_task_coordinator.h
@@ -32,35 +32,22 @@ std::map<SchedulerClientType, std::vector<const NotificationEntry*>>; using ClientStates = std::map<SchedulerClientType, const ClientState*>; using TimeRandomizer = base::RepeatingCallback<base::TimeDelta()>; + static base::TimeDelta DefaultTimeRandomizer( const base::TimeDelta& time_window); - BackgroundTaskCoordinator( + + static std::unique_ptr<BackgroundTaskCoordinator> Create( std::unique_ptr<NotificationBackgroundTaskScheduler> background_task, const SchedulerConfig* config, TimeRandomizer time_randomizer, base::Clock* clock); + virtual ~BackgroundTaskCoordinator(); // Schedule background task based on current notification in the storage. virtual void ScheduleBackgroundTask(Notifications notifications, ClientStates client_states, - SchedulerTaskTime task_start_time); - - private: - // The class that actually schedules platform background task. - std::unique_ptr<NotificationBackgroundTaskScheduler> background_task_; - - // System configuration. - const SchedulerConfig* config_; - - // Randomize the time to show the notification, to avoid large number of users - // to perform actions at the same time. - TimeRandomizer time_randomizer_; - - // Clock to query the current timestamp. - base::Clock* clock_; - - DISALLOW_COPY_AND_ASSIGN(BackgroundTaskCoordinator); + SchedulerTaskTime task_start_time) = 0; }; } // namespace notifications
diff --git a/chrome/browser/notifications/scheduler/internal/background_task_coordinator_unittest.cc b/chrome/browser/notifications/scheduler/internal/background_task_coordinator_unittest.cc index b1eda78..1323e8e 100644 --- a/chrome/browser/notifications/scheduler/internal/background_task_coordinator_unittest.cc +++ b/chrome/browser/notifications/scheduler/internal/background_task_coordinator_unittest.cc
@@ -76,7 +76,7 @@ auto background_task = std::make_unique<test::MockNotificationBackgroundTaskScheduler>(); background_task_ = background_task.get(); - coordinator_ = std::make_unique<BackgroundTaskCoordinator>( + coordinator_ = BackgroundTaskCoordinator::Create( std::move(background_task), &config_, base::BindRepeating(&NoopTimeRandomizer, base::TimeDelta()), &clock_); }
diff --git a/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.cc b/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.cc index 91bfadf..7561549 100644 --- a/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.cc +++ b/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.cc
@@ -8,14 +8,12 @@ #include <utility> #include "base/bind.h" -#include "base/time/default_clock.h" #include "chrome/browser/notifications/scheduler/internal/background_task_coordinator.h" #include "chrome/browser/notifications/scheduler/internal/display_decider.h" #include "chrome/browser/notifications/scheduler/internal/impression_history_tracker.h" #include "chrome/browser/notifications/scheduler/internal/scheduled_notification_manager.h" #include "chrome/browser/notifications/scheduler/internal/scheduler_config.h" #include "chrome/browser/notifications/scheduler/public/display_agent.h" -#include "chrome/browser/notifications/scheduler/public/notification_background_task_scheduler.h" #include "chrome/browser/notifications/scheduler/public/notification_scheduler_client.h" #include "chrome/browser/notifications/scheduler/public/notification_scheduler_client_registrar.h" @@ -23,7 +21,7 @@ NotificationSchedulerContext::NotificationSchedulerContext( std::unique_ptr<NotificationSchedulerClientRegistrar> client_registrar, - std::unique_ptr<NotificationBackgroundTaskScheduler> background_task, + std::unique_ptr<BackgroundTaskCoordinator> background_task_coordinator, std::unique_ptr<ImpressionHistoryTracker> impression_tracker, std::unique_ptr<ScheduledNotificationManager> notification_manager, std::unique_ptr<DisplayAgent> display_agent, @@ -35,12 +33,7 @@ display_agent_(std::move(display_agent)), display_decider_(std::move(display_decider)), config_(std::move(config)), - background_task_coordinator_(std::make_unique<BackgroundTaskCoordinator>( - std::move(background_task), - config_.get(), - base::BindRepeating(&BackgroundTaskCoordinator::DefaultTimeRandomizer, - config_->background_task_random_time_window), - base::DefaultClock::GetInstance())) {} + background_task_coordinator_(std::move(background_task_coordinator)) {} NotificationSchedulerContext::~NotificationSchedulerContext() = default;
diff --git a/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.h b/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.h index 6de0494..c8d95052 100644 --- a/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.h +++ b/chrome/browser/notifications/scheduler/internal/notification_scheduler_context.h
@@ -17,7 +17,6 @@ class DisplayAgent; class DisplayDecider; class ImpressionHistoryTracker; -class NotificationBackgroundTaskScheduler; class NotificationSchedulerClientRegistrar; class ScheduledNotificationManager; struct SchedulerConfig; @@ -28,7 +27,7 @@ public: NotificationSchedulerContext( std::unique_ptr<NotificationSchedulerClientRegistrar> client_registrar, - std::unique_ptr<NotificationBackgroundTaskScheduler> background_task, + std::unique_ptr<BackgroundTaskCoordinator> background_task_coordinator, std::unique_ptr<ImpressionHistoryTracker> impression_tracker, std::unique_ptr<ScheduledNotificationManager> notification_manager, std::unique_ptr<DisplayAgent> display_agent,
diff --git a/chrome/browser/notifications/scheduler/schedule_service_factory_helper.cc b/chrome/browser/notifications/scheduler/schedule_service_factory_helper.cc index b0838ef..342b224 100644 --- a/chrome/browser/notifications/scheduler/schedule_service_factory_helper.cc +++ b/chrome/browser/notifications/scheduler/schedule_service_factory_helper.cc
@@ -10,6 +10,7 @@ #include "base/sequenced_task_runner.h" #include "base/task/post_task.h" #include "base/time/default_clock.h" +#include "chrome/browser/notifications/scheduler/internal/background_task_coordinator.h" #include "chrome/browser/notifications/scheduler/internal/display_decider.h" #include "chrome/browser/notifications/scheduler/internal/icon_store.h" #include "chrome/browser/notifications/scheduler/internal/impression_history_tracker.h" @@ -89,8 +90,14 @@ std::move(notification_store), std::move(icon_store), registered_clients, *config.get()); + auto background_task_coordinator = BackgroundTaskCoordinator::Create( + std::move(background_task_scheduler), config.get(), + base::BindRepeating(&BackgroundTaskCoordinator::DefaultTimeRandomizer, + config->background_task_random_time_window), + base::DefaultClock::GetInstance()); + auto context = std::make_unique<NotificationSchedulerContext>( - std::move(client_registrar), std::move(background_task_scheduler), + std::move(client_registrar), std::move(background_task_coordinator), std::move(impression_tracker), std::move(notification_manager), std::move(display_agent), DisplayDecider::Create(), std::move(config));
diff --git a/chrome/browser/notifications/scheduler/test/BUILD.gn b/chrome/browser/notifications/scheduler/test/BUILD.gn index ec4d221..acf0805 100644 --- a/chrome/browser/notifications/scheduler/test/BUILD.gn +++ b/chrome/browser/notifications/scheduler/test/BUILD.gn
@@ -10,6 +10,8 @@ sources = [ "fake_clock.cc", "fake_clock.h", + "mock_background_task_coordinator.cc", + "mock_background_task_coordinator.h", "mock_display_agent.cc", "mock_display_agent.h", "mock_display_decider.cc",
diff --git a/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.cc b/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.cc new file mode 100644 index 0000000..67bb460 --- /dev/null +++ b/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.cc
@@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.h" + +namespace notifications { +namespace test { + +MockBackgroundTaskCoordinator::MockBackgroundTaskCoordinator() = default; + +MockBackgroundTaskCoordinator::~MockBackgroundTaskCoordinator() = default; + +} // namespace test +} // namespace notifications
diff --git a/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.h b/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.h new file mode 100644 index 0000000..e44f4d9 --- /dev/null +++ b/chrome/browser/notifications/scheduler/test/mock_background_task_coordinator.h
@@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_NOTIFICATIONS_SCHEDULER_TEST_MOCK_BACKGROUND_TASK_COORDINATOR_H_ +#define CHROME_BROWSER_NOTIFICATIONS_SCHEDULER_TEST_MOCK_BACKGROUND_TASK_COORDINATOR_H_ + +#include "chrome/browser/notifications/scheduler/internal/background_task_coordinator.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace notifications { +namespace test { + +class MockBackgroundTaskCoordinator : public BackgroundTaskCoordinator { + public: + MockBackgroundTaskCoordinator(); + ~MockBackgroundTaskCoordinator() override; + MOCK_METHOD3(ScheduleBackgroundTask, + void(BackgroundTaskCoordinator::Notifications notifications, + BackgroundTaskCoordinator::ClientStates client_states, + SchedulerTaskTime task_start_time)); +}; + +} // namespace test +} // namespace notifications + +#endif // CHROME_BROWSER_NOTIFICATIONS_SCHEDULER_TEST_MOCK_BACKGROUND_TASK_COORDINATOR_H_
diff --git a/chrome/browser/optimization_guide/optimization_guide_hints_manager.cc b/chrome/browser/optimization_guide/optimization_guide_hints_manager.cc index 59ed904..f5aa110 100644 --- a/chrome/browser/optimization_guide/optimization_guide_hints_manager.cc +++ b/chrome/browser/optimization_guide/optimization_guide_hints_manager.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/optimization_guide/optimization_guide_hints_manager.h" +#include <string> #include <utility> #include "base/bind.h" @@ -17,6 +18,7 @@ #include "components/optimization_guide/hints_component_info.h" #include "components/optimization_guide/hints_component_util.h" #include "components/optimization_guide/hints_processing_util.h" +#include "components/optimization_guide/optimization_guide_prefs.h" #include "components/optimization_guide/optimization_guide_service.h" #include "components/optimization_guide/optimization_guide_switches.h" #include "components/optimization_guide/proto/hints.pb.h" @@ -33,13 +35,20 @@ std::unique_ptr<optimization_guide::HintUpdateData> ProcessHintsComponent( const optimization_guide::HintsComponentInfo& info, std::unique_ptr<optimization_guide::HintUpdateData> update_data) { - // TODO(crbug/969558): Add the result here and record the histogram. + optimization_guide::ProcessHintsComponentResult out_result; std::unique_ptr<optimization_guide::proto::Configuration> config = - optimization_guide::ProcessHintsComponent(info, /*out_result=*/nullptr); - if (!config) + optimization_guide::ProcessHintsComponent(info, &out_result); + if (!config) { + optimization_guide::RecordProcessHintsComponentResult(out_result); return nullptr; + } - optimization_guide::ProcessHints(config->mutable_hints(), update_data.get()); + bool did_process_hints = optimization_guide::ProcessHints( + config->mutable_hints(), update_data.get()); + optimization_guide::RecordProcessHintsComponentResult( + did_process_hints + ? optimization_guide::ProcessHintsComponentResult::kSuccess + : optimization_guide::ProcessHintsComponentResult::kProcessedNoHints); return update_data; } @@ -49,6 +58,38 @@ std::move(update_closure).Run(); } +// Returns whether the particular component version can be processed, and if it +// can be, locks the semaphore (in the form of a pref) to signal that the +// processing of this particular version has started. +bool CanProcessComponentVersion(PrefService* pref_service, + const base::Version& version) { + DCHECK(version.IsValid()); + + const std::string previous_attempted_version_string = pref_service->GetString( + optimization_guide::prefs::kPendingHintsProcessingVersion); + if (!previous_attempted_version_string.empty()) { + const base::Version previous_attempted_version = + base::Version(previous_attempted_version_string); + if (!previous_attempted_version.IsValid()) { + DLOG(ERROR) << "Bad contents in hints processing pref"; + // Clear pref for fresh start next time. + pref_service->ClearPref( + optimization_guide::prefs::kPendingHintsProcessingVersion); + return false; + } + if (previous_attempted_version.CompareTo(version) == 0) { + // Previously attempted same version without completion. + return false; + } + } + + // Write config version to pref. + pref_service->SetString( + optimization_guide::prefs::kPendingHintsProcessingVersion, + version.GetString()); + return true; +} + } // namespace OptimizationGuideHintsManager::OptimizationGuideHintsManager( @@ -98,12 +139,20 @@ std::unique_ptr<optimization_guide::HintUpdateData> update_data = hint_cache_->MaybeCreateUpdateDataForComponentHints(info.version); if (!update_data) { + optimization_guide::RecordProcessHintsComponentResult( + optimization_guide::ProcessHintsComponentResult:: + kSkippedProcessingHints); MaybeRunUpdateClosure(std::move(next_update_closure_)); return; } - // TODO(sophiechang): Check if we are mid-crash loop for processing this hint - // version. + if (!CanProcessComponentVersion(pref_service_, info.version)) { + optimization_guide::RecordProcessHintsComponentResult( + optimization_guide::ProcessHintsComponentResult:: + kFailedFinishProcessing); + MaybeRunUpdateClosure(std::move(next_update_closure_)); + return; + } // Processes the hints from the newly available component on a background // thread, providing a HintUpdateData for component update from the hint @@ -149,6 +198,10 @@ std::unique_ptr<optimization_guide::HintUpdateData> hint_update_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + // If we get here, the hints have been processed correctly. + pref_service_->ClearPref( + optimization_guide::prefs::kPendingHintsProcessingVersion); + if (hint_update_data) { hint_cache_->UpdateComponentHints( std::move(hint_update_data),
diff --git a/chrome/browser/optimization_guide/optimization_guide_hints_manager_unittest.cc b/chrome/browser/optimization_guide/optimization_guide_hints_manager_unittest.cc index dd183ee..44deb17 100644 --- a/chrome/browser/optimization_guide/optimization_guide_hints_manager_unittest.cc +++ b/chrome/browser/optimization_guide/optimization_guide_hints_manager_unittest.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/files/file_util.h" #include "base/test/metrics/histogram_tester.h" +#include "components/optimization_guide/hints_component_util.h" #include "components/optimization_guide/optimization_guide_prefs.h" #include "components/optimization_guide/optimization_guide_service.h" #include "components/optimization_guide/optimization_guide_switches.h" @@ -184,6 +185,11 @@ optimization_guide::switches::kHintsProtoOverride, encoded_config); CreateServiceAndHintsManager(); + // The below histogram should not be recorded since hints weren't coming + // directly from the component. + histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult", 0); + // However, we still expect the local histogram for the hints being updated to + // be recorded. histogram_tester.ExpectUniqueSample( "OptimizationGuide.UpdateComponentHints.Result2", true, 1); } @@ -196,8 +202,10 @@ optimization_guide::switches::kHintsProtoOverride, "this-is-not-a-proto"); CreateServiceAndHintsManager(); - // If the proto was invalid, we do not expect it to go through with the - // process of updating hints. + // The below histogram should not be recorded since hints weren't coming + // directly from the component. + histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult", 0); + // We also do not expect to update the component hints with bad hints either. histogram_tester.ExpectTotalCount( "OptimizationGuide.UpdateComponentHints.Result2", 0); } @@ -223,6 +231,12 @@ base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( optimization_guide::switches::kHintsProtoOverride, encoded_config); CreateServiceAndHintsManager(); + // The below histogram should not be recorded since hints weren't coming + // directly from the component. + histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult", + 0); + // However, we still expect the local histogram for the hints being updated + // to be recorded. histogram_tester.ExpectUniqueSample( "OptimizationGuide.UpdateComponentHints.Result2", true, 1); } @@ -231,6 +245,10 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig("3.0.0.0"); + // The below histograms should not be recorded since component hints + // processing is disabled. + histogram_tester.ExpectTotalCount("OptimizationGuide.ProcessHintsResult", + 0); histogram_tester.ExpectTotalCount( "OptimizationGuide.UpdateComponentHints.Result2", 0); } @@ -259,7 +277,8 @@ base::HistogramTester histogram_tester; InitializeWithDefaultConfig("1.0.0.0"); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.UpdateComponentHints.Result2", true, 1); + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); } // Test the second time parsing the config. This should also update the hints. @@ -267,7 +286,8 @@ base::HistogramTester histogram_tester; InitializeWithDefaultConfig("2.0.0.0"); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.UpdateComponentHints.Result2", true, 1); + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); } } @@ -277,7 +297,8 @@ base::HistogramTester histogram_tester; InitializeWithDefaultConfig("10.0.0.0"); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.UpdateComponentHints.Result2", true, 1); + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); } // Test the second time parsing the config. This will be treated by the cache @@ -287,8 +308,11 @@ InitializeWithDefaultConfig("2.0.0.0"); // If we have already parsed a version later than this version, we expect // for the hints to not be updated. - histogram_tester.ExpectTotalCount( - "OptimizationGuide.UpdateComponentHints.Result2", 0); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult:: + kSkippedProcessingHints, + 1); } } @@ -300,7 +324,8 @@ base::HistogramTester histogram_tester; InitializeWithDefaultConfig(version); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.UpdateComponentHints.Result2", true, 1); + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); } // Test the second time parsing the config. This will be treated by the cache @@ -308,10 +333,11 @@ { base::HistogramTester histogram_tester; InitializeWithDefaultConfig(version); - // If we have already parsed this version, then we do not expect to update - // the hints. - histogram_tester.ExpectTotalCount( - "OptimizationGuide.UpdateComponentHints.Result2", 0); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult:: + kSkippedProcessingHints, + 1); } } @@ -319,5 +345,79 @@ base::HistogramTester histogram_tester; ProcessInvalidHintsComponentInfo("1.0.0.0"); histogram_tester.ExpectUniqueSample( - "OptimizationGuide.UpdateComponentHints.Result2", false, 1); + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kFailedReadingFile, 1); +} + +TEST_F(OptimizationGuideHintsManagerTest, ProcessHintsWithExistingPref) { + // Write hints processing pref for version 2.0.0. + pref_service()->SetString( + optimization_guide::prefs::kPendingHintsProcessingVersion, "2.0.0"); + + // Verify config not processed for same version (2.0.0) and pref not cleared. + { + base::HistogramTester histogram_tester; + InitializeWithDefaultConfig("2.0.0"); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult:: + kFailedFinishProcessing, + 1); + EXPECT_FALSE( + pref_service() + ->GetString( + optimization_guide::prefs::kPendingHintsProcessingVersion) + .empty()); + } + + // Now verify config is processed for different version and pref cleared. + { + base::HistogramTester histogram_tester; + InitializeWithDefaultConfig("3.0.0"); + EXPECT_TRUE( + pref_service() + ->GetString( + optimization_guide::prefs::kPendingHintsProcessingVersion) + .empty()); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + } +} + +TEST_F(OptimizationGuideHintsManagerTest, ProcessHintsWithInvalidPref) { + // Create pref file with invalid version. + pref_service()->SetString( + optimization_guide::prefs::kPendingHintsProcessingVersion, "bad-2.0.0"); + + // Verify config not processed for existing pref with bad value but + // that the pref is cleared. + { + base::HistogramTester histogram_tester; + InitializeWithDefaultConfig("2.0.0"); + EXPECT_TRUE( + pref_service() + ->GetString( + optimization_guide::prefs::kPendingHintsProcessingVersion) + .empty()); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult:: + kFailedFinishProcessing, + 1); + } + + // Now verify config is processed with pref cleared. + { + base::HistogramTester histogram_tester; + InitializeWithDefaultConfig("2.0.0"); + EXPECT_TRUE( + pref_service() + ->GetString( + optimization_guide::prefs::kPendingHintsProcessingVersion) + .empty()); + histogram_tester.ExpectUniqueSample( + "OptimizationGuide.ProcessHintsResult", + optimization_guide::ProcessHintsComponentResult::kSuccess, 1); + } }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc index 6935e4f8..cf5c235 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -618,6 +618,12 @@ ADS_HISTOGRAM("Cpu.AdFrames.PerFrame.PeakWindowedPercent", UMA_HISTOGRAM_PERCENTAGE, visibility, ad_frame_data.peak_windowed_cpu_percent()); + if (ad_frame_data.peak_window_start_time()) { + ADS_HISTOGRAM("Cpu.AdFrames.PerFrame.PeakWindowStartTime", + PAGE_LOAD_HISTOGRAM, visibility, + ad_frame_data.peak_window_start_time().value() - + GetDelegate()->GetNavigationStart()); + } } if (ad_frame_data.user_activation_status() == @@ -709,6 +715,12 @@ ADS_HISTOGRAM("Cpu.FullPage.PeakWindowedPercent", UMA_HISTOGRAM_PERCENTAGE, visibility, aggregate_frame_data_->peak_windowed_cpu_percent()); + if (aggregate_frame_data_->peak_window_start_time()) { + ADS_HISTOGRAM("Cpu.FullPage.PeakWindowStartTime", PAGE_LOAD_HISTOGRAM, + visibility, + aggregate_frame_data_->peak_window_start_time().value() - + GetDelegate()->GetNavigationStart()); + } } if (pre_interactive_duration_.InMilliseconds() > 0) { ADS_HISTOGRAM("Cpu.FullPage.TotalUsage.PreInteractive", PAGE_LOAD_HISTOGRAM,
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc index 2aced070..9d287a1 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_unittest.cc
@@ -1019,12 +1019,20 @@ // Navigate away and check the peak windowed cpu usage. NavigateFrame(kNonAdUrl, main_frame); + // 10% is the maximum for the individual ad frame. histogram_tester().ExpectUniqueSample( SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowedPercent"), 10, 1); + + // The peak window started at 12 seconds into the page load + histogram_tester().ExpectUniqueSample( + SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowStartTime"), 12000, 1); + // 13% is the maximum for all frames (including main). histogram_tester().ExpectUniqueSample( SuffixedHistogram("Cpu.FullPage.PeakWindowedPercent"), 13, 1); + histogram_tester().ExpectUniqueSample( + SuffixedHistogram("Cpu.FullPage.PeakWindowStartTime"), 12000, 1); } TEST_F(AdsPageLoadMetricsObserverTest, TestCpuTimingMetricsWindowedActivated) { @@ -1066,12 +1074,20 @@ // Navigate away and check the peak windowed cpu usage. NavigateFrame(kNonAdUrl, main_frame); + // 11% is the maximum before activation for the ad frame. histogram_tester().ExpectUniqueSample( SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowedPercent"), 11, 1); + + // The peak window started at 0 seconds into the page load + histogram_tester().ExpectUniqueSample( + SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowStartTime"), 0, 1); + // 16% is the maximum for all frames (including main), ignores activation. histogram_tester().ExpectUniqueSample( SuffixedHistogram("Cpu.FullPage.PeakWindowedPercent"), 16, 1); + histogram_tester().ExpectUniqueSample( + SuffixedHistogram("Cpu.FullPage.PeakWindowStartTime"), 12000, 1); } TEST_F(AdsPageLoadMetricsObserverTest, TestCpuTimingMetrics) { @@ -1286,7 +1302,11 @@ histogram_tester().ExpectTotalCount( SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowedPercent"), 0); histogram_tester().ExpectTotalCount( + SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowStartTime"), 0); + histogram_tester().ExpectTotalCount( SuffixedHistogram("Cpu.FullPage.PeakWindowedPercent"), 0); + histogram_tester().ExpectTotalCount( + SuffixedHistogram("Cpu.FullPage.PeakWindowStartTime"), 0); auto entries = test_ukm_recorder().GetEntriesByName( ukm::builders::AdFrameLoad::kEntryName); @@ -1373,7 +1393,11 @@ histogram_tester().ExpectTotalCount( SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowedPercent"), 0); histogram_tester().ExpectTotalCount( + SuffixedHistogram("Cpu.AdFrames.PerFrame.PeakWindowStartTime"), 0); + histogram_tester().ExpectTotalCount( SuffixedHistogram("Cpu.FullPage.PeakWindowedPercent"), 0); + histogram_tester().ExpectTotalCount( + SuffixedHistogram("Cpu.FullPage.PeakWindowStartTime"), 0); auto entries = test_ukm_recorder().GetEntriesByName( ukm::builders::AdFrameLoad::kEntryName);
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc index 8a62600..7a74032 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.cc
@@ -172,8 +172,11 @@ int current_windowed_cpu_percent = 100 * cpu_total_for_current_window_.InMilliseconds() / kCpuWindowSize.InMilliseconds(); - if (current_windowed_cpu_percent > peak_windowed_cpu_percent_) + if (current_windowed_cpu_percent > peak_windowed_cpu_percent_) { peak_windowed_cpu_percent_ = current_windowed_cpu_percent; + peak_window_start_time_ = + cpu_updates_for_current_window_.front().update_time; + } } base::TimeDelta FrameData::GetInteractiveCpuUsage(
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h index 4a4d143..c3a6a26 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/frame_data.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_PAGE_LOAD_METRICS_OBSERVERS_AD_METRICS_FRAME_DATA_H_ #include "base/macros.h" +#include "base/optional.h" #include "chrome/browser/page_load_metrics/page_load_metrics_observer.h" #include "chrome/common/page_load_metrics/page_load_metrics.mojom.h" #include "services/metrics/public/cpp/ukm_source_id.h" @@ -141,6 +142,10 @@ int peak_windowed_cpu_percent() const { return peak_windowed_cpu_percent_; } + base::Optional<base::TimeTicks> peak_window_start_time() const { + return peak_window_start_time_; + } + FrameTreeNodeId frame_tree_node_id() const { return frame_tree_node_id_; } OriginStatus origin_status() const { return origin_status_; } @@ -210,21 +215,29 @@ InteractiveStatus::kMaxValue) + 1] = {base::TimeDelta(), base::TimeDelta()}; + // Time spent by the frame in the cpu before and after activation. base::TimeDelta cpu_by_activation_period_ [static_cast<size_t>(UserActivationStatus::kMaxValue) + 1] = { base::TimeDelta(), base::TimeDelta()}; + // Duration of time the page spent in the foreground before activation. base::TimeDelta pre_activation_foreground_duration_; + // The cpu time spent in the current window. base::TimeDelta cpu_total_for_current_window_; + // The cpu updates themselves that are still relevant for the time window. // Note: Since the window is 30 seconds and PageLoadMetrics updates arrive at // most every half second, this can never have more than 60 elements. base::queue<CpuUpdateData> cpu_updates_for_current_window_; + // The peak windowed cpu load during the unactivated period. int peak_windowed_cpu_percent_ = 0; + // The time that the peak cpu usage window started at. + base::Optional<base::TimeTicks> peak_window_start_time_; + // The depth of this FrameData's root frame. unsigned int root_frame_depth_ = 0;
diff --git a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc index 0475262..420cad36 100644 --- a/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/core_page_load_metrics_observer_unittest.cc
@@ -1358,11 +1358,11 @@ NavigateAndCommit(GURL(kDefaultTestUrl2)); EXPECT_THAT( - histogram_tester().GetAllSamples(internal::kHistogramFirstInputDelay), + histogram_tester().GetAllSamples(internal::kHistogramFirstInputDelay4), testing::ElementsAre(base::Bucket(5, 1))); - EXPECT_THAT( - histogram_tester().GetAllSamples(internal::kHistogramFirstInputTimestamp), - testing::ElementsAre(base::Bucket(4780, 1))); + EXPECT_THAT(histogram_tester().GetAllSamples( + internal::kHistogramFirstInputTimestamp4), + testing::ElementsAre(base::Bucket(4780, 1))); } TEST_F(CorePageLoadMetricsObserverTest, LongestInputDelayAndTimestamp) {
diff --git a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc index 38c5e0b..3bcd402 100644 --- a/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc +++ b/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer_unittest.cc
@@ -832,9 +832,9 @@ test_ukm_recorder().ExpectEntrySourceHasUrl(kv.second.get(), GURL(kTestUrl1)); test_ukm_recorder().ExpectEntryMetric( - kv.second.get(), PageLoad::kInteractiveTiming_FirstInputDelay3Name, 50); + kv.second.get(), PageLoad::kInteractiveTiming_FirstInputDelay4Name, 50); test_ukm_recorder().ExpectEntryMetric( - kv.second.get(), PageLoad::kInteractiveTiming_FirstInputTimestamp3Name, + kv.second.get(), PageLoad::kInteractiveTiming_FirstInputTimestamp4Name, 712); } }
diff --git a/chrome/browser/performance_manager/frame_priority/override_vote_aggregator.cc b/chrome/browser/performance_manager/frame_priority/override_vote_aggregator.cc new file mode 100644 index 0000000..8b0837f --- /dev/null +++ b/chrome/browser/performance_manager/frame_priority/override_vote_aggregator.cc
@@ -0,0 +1,142 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/performance_manager/public/frame_priority/override_vote_aggregator.h" + +namespace performance_manager { +namespace frame_priority { + +OverrideVoteAggregator::OverrideVoteAggregator() : factory_(this) {} + +OverrideVoteAggregator::~OverrideVoteAggregator() = default; + +VotingChannel OverrideVoteAggregator::GetOverrideVotingChannel() { + DCHECK(vote_data_map_.empty()); + DCHECK_EQ(kInvalidVoterId, override_voter_id_); + DCHECK_GT(2u, factory_.voting_channels_issued()); + auto channel = factory_.BuildVotingChannel(); + override_voter_id_ = channel.voter_id(); + return channel; +} + +VotingChannel OverrideVoteAggregator::GetDefaultVotingChannel() { + DCHECK(vote_data_map_.empty()); + DCHECK_EQ(kInvalidVoterId, default_voter_id_); + DCHECK_GT(2u, factory_.voting_channels_issued()); + auto channel = factory_.BuildVotingChannel(); + default_voter_id_ = channel.voter_id(); + return channel; +} + +void OverrideVoteAggregator::SetUpstreamVotingChannel(VotingChannel&& channel) { + DCHECK(channel.IsValid()); + DCHECK(vote_data_map_.empty()); + DCHECK(!channel_.IsValid()); + channel_ = std::move(channel); +} + +bool OverrideVoteAggregator::IsSetup() const { + return override_voter_id_ != kInvalidVoterId && + default_voter_id_ != kInvalidVoterId && channel_.IsValid(); +} + +VoteReceipt OverrideVoteAggregator::SubmitVote(VoterId voter_id, + const Vote& vote) { + DCHECK(vote.IsValid()); + DCHECK(IsSetup()); + + VoteData& vote_data = vote_data_map_[vote.frame_node()]; + if (voter_id == override_voter_id_) { + DCHECK(!vote_data.override_vote.IsValid()); + vote_data.override_vote = AcceptedVote(this, voter_id, vote); + UpstreamVote(vote, &vote_data); + return vote_data.override_vote.IssueReceipt(); + } else { + DCHECK_EQ(default_voter_id_, voter_id); + DCHECK(!vote_data.default_vote.IsValid()); + vote_data.default_vote = AcceptedVote(this, voter_id, vote); + if (!vote_data.override_vote.IsValid()) + UpstreamVote(vote, &vote_data); + return vote_data.default_vote.IssueReceipt(); + } +} + +VoteReceipt OverrideVoteAggregator::ChangeVote(VoteReceipt receipt, + AcceptedVote* old_vote, + const Vote& new_vote) { + DCHECK(receipt.HasVote(old_vote)); + VoteData& vote_data = GetVoteData(old_vote)->second; + + // Update the vote in place. + old_vote->UpdateVote(new_vote); + + // The vote being changed is the upstream vote if: + // (1) It is the override vote, or + // (2) There is no override vote. + if (old_vote == &vote_data.override_vote || + !vote_data.override_vote.IsValid()) { + UpstreamVote(new_vote, &vote_data); + } + + // Pass the same receipt right back to the user. + return receipt; +} + +void OverrideVoteAggregator::VoteInvalidated(AcceptedVote* vote) { + auto it = GetVoteData(vote); + VoteData& vote_data = it->second; + + // Figure out which is the "other" vote in this case. + bool is_override_vote = false; + AcceptedVote* other = nullptr; + if (vote == &vote_data.override_vote) { + is_override_vote = true; + other = &vote_data.default_vote; + } else { + DCHECK_EQ(&vote_data.default_vote, vote); + other = &vote_data.override_vote; + } + + // If the other vote is invalid the whole entry is being erased, which will + // cancel the upstream vote as well. + if (!other->IsValid()) { + vote_data_map_.erase(it); + return; + } + + // Otherwise, the other vote is valid. If the other vote is the + // |override_vote| (ie, the vote being invalidated is not) then the upstream + // vote doesn't need to change. The last case is that the |override_vote| is + // being invalidated, and the default is valid. In this case we need to + // upstream a new vote. + if (is_override_vote) + UpstreamVote(other->vote(), &vote_data); +} + +OverrideVoteAggregator::VoteDataMap::iterator +OverrideVoteAggregator::GetVoteData(AcceptedVote* vote) { + // The vote being retrieved should have us as its consumer, and have been + // emitted by one of our known voters. + DCHECK(vote); + DCHECK_EQ(this, vote->consumer()); + DCHECK(vote->voter_id() == override_voter_id_ || + vote->voter_id() == default_voter_id_); + DCHECK(IsSetup()); + + auto it = vote_data_map_.find(vote->vote().frame_node()); + DCHECK(it != vote_data_map_.end()); + return it; +} + +void OverrideVoteAggregator::UpstreamVote(const Vote& vote, + VoteData* vote_data) { + // Change our existing vote, or create a new one as necessary. + if (vote_data->receipt.HasVote()) + vote_data->receipt.ChangeVote(vote.priority(), vote.reason()); + else + vote_data->receipt = channel_.SubmitVote(vote); +} + +} // namespace frame_priority +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/frame_priority/override_vote_aggregator_unittest.cc b/chrome/browser/performance_manager/frame_priority/override_vote_aggregator_unittest.cc new file mode 100644 index 0000000..2949c90 --- /dev/null +++ b/chrome/browser/performance_manager/frame_priority/override_vote_aggregator_unittest.cc
@@ -0,0 +1,188 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/performance_manager/public/frame_priority/override_vote_aggregator.h" + +#include "chrome/browser/performance_manager/frame_priority/unittest_util.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace performance_manager { +namespace frame_priority { + +// Some dummy frames. +const FrameNode* kDummyFrame1 = reinterpret_cast<const FrameNode*>(0xDEADBEEF); +const FrameNode* kDummyFrame2 = reinterpret_cast<const FrameNode*>(0xBAADF00D); + +TEST(OverrideVoteAggregatorTest, BlackboxTest) { + // Priorities to use for default and override votes. The override priority is + // lower on purpose. + static constexpr base::TaskPriority kDefaultPriority = + base::TaskPriority::HIGHEST; + static constexpr base::TaskPriority kOverridePriority = + base::TaskPriority::LOWEST; + + static const char kReason[] = "another reason"; + + // Builds the small hierarchy of voters as follows: + // + // consumer + // | + // agg + // / \ + // / \ + // voter0 voter1 + // (override) (default) + test::DummyVoteConsumer consumer; + OverrideVoteAggregator agg; + test::DummyVoter voter0; + test::DummyVoter voter1; + + VoterId agg_id = kInvalidVoterId; + { + auto channel = consumer.voting_channel_factory_.BuildVotingChannel(); + agg_id = channel.voter_id(); + agg.SetUpstreamVotingChannel(std::move(channel)); + } + + voter0.SetVotingChannel(agg.GetOverrideVotingChannel()); + voter1.SetVotingChannel(agg.GetDefaultVotingChannel()); + EXPECT_TRUE(agg.IsSetup()); + + // Submitting a default vote should immediately propagate to the consumer. + voter1.EmitVote(kDummyFrame1, kDefaultPriority); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(1u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(0, agg_id, kDummyFrame1, kDefaultPriority, + test::DummyVoter::kReason); + + // Canceling the default vote should clear all votes. + voter1.receipts_.clear(); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(0u, voter1.receipts_.size()); + EXPECT_EQ(0u, agg.GetSizeForTesting()); + EXPECT_EQ(1u, consumer.votes_.size()); + EXPECT_EQ(0u, consumer.valid_vote_count_); + + // Resubmitting the default vote should propagate to the consumer. + voter1.EmitVote(kDummyFrame1, kDefaultPriority); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kDefaultPriority, + test::DummyVoter::kReason); + + // Submitting an override vote should override it and propagate to the + // consumer. This should update the existing vote in place. + voter0.EmitVote(kDummyFrame1, kOverridePriority); + EXPECT_EQ(1u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, + test::DummyVoter::kReason); + + // Canceling the override vote should drop back to using the default vote. + // This will again reuse the existing upstream vote. + voter0.receipts_.clear(); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kDefaultPriority, + test::DummyVoter::kReason); + + // Changing the default vote should propagate, as there's no override vote. + voter1.receipts_[0].ChangeVote(kDefaultPriority, kReason); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kDefaultPriority, kReason); + + // Changing back should also propagate. + voter1.receipts_[0].ChangeVote(kDefaultPriority, test::DummyVoter::kReason); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kDefaultPriority, + test::DummyVoter::kReason); + + // Submitting an override vote should override it and propagate to the + // consumer. + voter0.EmitVote(kDummyFrame1, kOverridePriority); + EXPECT_EQ(1u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, + test::DummyVoter::kReason); + + // Canceling the default vote should do nothing. + voter1.receipts_.clear(); + EXPECT_EQ(1u, voter0.receipts_.size()); + EXPECT_EQ(0u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, + test::DummyVoter::kReason); + + // Submitting another default vote should do nothing. + voter1.EmitVote(kDummyFrame1, kDefaultPriority); + EXPECT_EQ(1u, voter0.receipts_.size()); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, + test::DummyVoter::kReason); + + // Changing the default vote should do nothing. + voter1.receipts_.back().ChangeVote(kDefaultPriority, kReason); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, + test::DummyVoter::kReason); + + // Changing the override vote should change the upstream vote. + voter0.receipts_.back().ChangeVote(kOverridePriority, kReason); + EXPECT_EQ(1u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, kReason); + + // Canceling the default vote should do nothing. + voter1.receipts_.clear(); + EXPECT_EQ(1u, voter0.receipts_.size()); + EXPECT_EQ(0u, voter1.receipts_.size()); + EXPECT_EQ(1u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(1u, consumer.valid_vote_count_); + consumer.ExpectValidVote(1, agg_id, kDummyFrame1, kOverridePriority, kReason); + + // Finally, canceling the override vote should cancel the upstream vote. + voter0.receipts_.clear(); + EXPECT_EQ(0u, voter0.receipts_.size()); + EXPECT_EQ(0u, voter1.receipts_.size()); + EXPECT_EQ(0u, agg.GetSizeForTesting()); + EXPECT_EQ(2u, consumer.votes_.size()); + EXPECT_EQ(0u, consumer.valid_vote_count_); +} + +} // namespace frame_priority +} // namespace performance_manager
diff --git a/chrome/browser/performance_manager/frame_priority/unittest_util.cc b/chrome/browser/performance_manager/frame_priority/unittest_util.cc index b8cb722..d888e1df 100644 --- a/chrome/browser/performance_manager/frame_priority/unittest_util.cc +++ b/chrome/browser/performance_manager/frame_priority/unittest_util.cc
@@ -56,7 +56,8 @@ void DummyVoteConsumer::ExpectValidVote(size_t index, VoterId voter_id, const FrameNode* frame_node, - base::TaskPriority priority) { + base::TaskPriority priority, + const char* reason) { EXPECT_LT(index, votes_.size()); const AcceptedVote& accepted_vote = votes_[index]; EXPECT_EQ(this, accepted_vote.consumer()); @@ -66,6 +67,8 @@ EXPECT_EQ(frame_node, vote.frame_node()); EXPECT_EQ(priority, vote.priority()); EXPECT_TRUE(vote.reason()); + if (reason) + EXPECT_EQ(reason, vote.reason()); } // static
diff --git a/chrome/browser/performance_manager/frame_priority/unittest_util.h b/chrome/browser/performance_manager/frame_priority/unittest_util.h index e6e3e8da..3f25c255e 100644 --- a/chrome/browser/performance_manager/frame_priority/unittest_util.h +++ b/chrome/browser/performance_manager/frame_priority/unittest_util.h
@@ -29,11 +29,13 @@ void VoteInvalidated(AcceptedVote* vote) override; // Checks that the vote at position |index| is valid, and has the - // corresponding |voter|, |frame_node| and |priority|. + // corresponding |voter|, |frame_node| and |priority|. If |reason| is non-null + // then it will be validated as well. void ExpectValidVote(size_t index, VoterId voter_id, const FrameNode* frame_node, - base::TaskPriority priority); + base::TaskPriority priority, + const char* reason = nullptr); VotingChannelFactory voting_channel_factory_; std::vector<AcceptedVote> votes_;
diff --git a/chrome/browser/performance_manager/public/frame_priority/override_vote_aggregator.h b/chrome/browser/performance_manager/public/frame_priority/override_vote_aggregator.h new file mode 100644 index 0000000..ca59bde --- /dev/null +++ b/chrome/browser/performance_manager/public/frame_priority/override_vote_aggregator.h
@@ -0,0 +1,91 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_PERFORMANCE_MANAGER_PUBLIC_FRAME_PRIORITY_OVERRIDE_VOTE_AGGREGATOR_H_ +#define CHROME_BROWSER_PERFORMANCE_MANAGER_PUBLIC_FRAME_PRIORITY_OVERRIDE_VOTE_AGGREGATOR_H_ + +#include <map> + +#include "chrome/browser/performance_manager/public/frame_priority/frame_priority.h" + +namespace performance_manager { +namespace frame_priority { + +// Aggregator that allows votes from 2 different Voters, where one of the voters +// is allowed to override the votes of another. This aggregator should be +// completely setup before any votes are submitted to it. +class OverrideVoteAggregator : public VoteConsumer { + public: + OverrideVoteAggregator(); + ~OverrideVoteAggregator() override; + + // All 3 of these must have been called in order for the aggregator to be + // fully setup. + VotingChannel GetOverrideVotingChannel(); + VotingChannel GetDefaultVotingChannel(); + void SetUpstreamVotingChannel(VotingChannel&& channel); + + bool IsSetup() const; + + size_t GetSizeForTesting() const { return vote_data_map_.size(); } + + protected: + // VoteConsumer implementation: + VoteReceipt SubmitVote(VoterId voter_id, const Vote& vote) override; + VoteReceipt ChangeVote(VoteReceipt receipt, + AcceptedVote* vote, + const Vote& old_vote) override; + void VoteInvalidated(AcceptedVote* vote) override; + + private: + // This is move-only because all of its members are move-only. + struct VoteData { + VoteData() = default; + VoteData(const VoteData& rhs) = delete; + VoteData(VoteData&& rhs) = default; + VoteData& operator=(const VoteData& rhs) = delete; + VoteData& operator=(VoteData&& rhs) = default; + ~VoteData() = default; + + // Each of these IsValid if a vote has been emitted for this frame, + // otherwise !IsValid. At least one of the votes must be valid, otherwise + // the entire map entry will be destroyed. + AcceptedVote override_vote; + AcceptedVote default_vote; + + // The receipt for the vote we've upstreamed. + VoteReceipt receipt; + }; + + using VoteDataMap = std::map<const FrameNode*, VoteData>; + + // Looks up the VoteData associated with the provided |vote|. The data is + // expected to already exist (enforced by a DCHECK). + VoteDataMap::iterator GetVoteData(AcceptedVote* vote); + + // Rebrands |vote| as belonging to this voter, and then sends it along to our + // |consumer_|. Stores the resulting receipt in |vote_data|. + void UpstreamVote(const Vote& vote, VoteData* vote_data); + + // Our two input voters. We'll only accept votes from these voters otherwise + // we'll DCHECK. + VoterId override_voter_id_ = kInvalidVoterId; + VoterId default_voter_id_ = kInvalidVoterId; + + // Our channel for upstreaming our votes. + VotingChannel channel_; + + // Our VotingChannelFactory for providing VotingChannels to our input voters. + VotingChannelFactory factory_; + + // The votes we've upstreamed to our consumer. + VoteDataMap vote_data_map_; + + DISALLOW_COPY_AND_ASSIGN(OverrideVoteAggregator); +}; + +} // namespace frame_priority +} // namespace performance_manager + +#endif // CHROME_BROWSER_PERFORMANCE_MANAGER_PUBLIC_FRAME_PRIORITY_OVERRIDE_VOTE_AGGREGATOR_H_
diff --git a/chrome/browser/permissions/permission_manager.cc b/chrome/browser/permissions/permission_manager.cc index 42758c9f..692164d4 100644 --- a/chrome/browser/permissions/permission_manager.cc +++ b/chrome/browser/permissions/permission_manager.cc
@@ -368,8 +368,7 @@ GURL(chrome::kChromeUINewTabURL).GetOrigin()) { if (requesting_origin.GetOrigin() == GURL(chrome::kChromeSearchLocalNtpUrl).GetOrigin()) { - return GURL(UIThreadSearchTermsData(profile_).GoogleBaseURLValue()) - .GetOrigin(); + return GURL(UIThreadSearchTermsData().GoogleBaseURLValue()).GetOrigin(); } else { return requesting_origin; }
diff --git a/chrome/browser/permissions/permission_manager_unittest.cc b/chrome/browser/permissions/permission_manager_unittest.cc index 3ac55125..58563dd 100644 --- a/chrome/browser/permissions/permission_manager_unittest.cc +++ b/chrome/browser/permissions/permission_manager_unittest.cc
@@ -140,7 +140,7 @@ } GURL google_base_url() const { - return GURL(UIThreadSearchTermsData(profile_.get()).GoogleBaseURLValue()); + return GURL(UIThreadSearchTermsData().GoogleBaseURLValue()); } bool callback_called() const {
diff --git a/chrome/browser/permissions/permission_request_manager_browsertest.cc b/chrome/browser/permissions/permission_request_manager_browsertest.cc index 9abe9588..0af9ddb 100644 --- a/chrome/browser/permissions/permission_request_manager_browsertest.cc +++ b/chrome/browser/permissions/permission_request_manager_browsertest.cc
@@ -684,10 +684,18 @@ owned_requests_.clear(); } +// crbug.com/989858 +#if defined(OS_WIN) +#define MAYBE_ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest \ + DISABLED_ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest +#else +#define MAYBE_ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest \ + ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest +#endif // Regression test for https://crbug.com/933321. IN_PROC_BROWSER_TEST_F( PermissionDialogTest, - ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest) { + MAYBE_ActiveTabClosedAfterRendererCrashesWithPendingPermissionRequest) { ShowUi("geolocation"); ASSERT_TRUE(VerifyUi());
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 75be9663..1e604e9 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -477,6 +477,10 @@ "webauthn.ble.paired_mac_addresses"; #endif // defined(OS_ANDROID) +// Deprecated 7/2019 +const char kLastKnownGoogleURL[] = "browser.last_known_google_url"; +const char kLastPromptedGoogleURL[] = "browser.last_prompted_google_url"; + // Register prefs used only for migration (clearing or moving to a new key). void RegisterProfilePrefsForMigration( user_prefs::PrefRegistrySyncable* registry) { @@ -543,6 +547,9 @@ std::string()); registry->RegisterListPref(kWebAuthnBlePairedMacAddressesPrefName); #endif // defined(OS_ANDROID) + + registry->RegisterStringPref(kLastKnownGoogleURL, std::string()); + registry->RegisterStringPref(kLastPromptedGoogleURL, std::string()); } } // namespace @@ -1126,6 +1133,8 @@ syncer::MigrateSyncSuppressedPref(profile_prefs); profile_prefs->ClearPref(kSignedInTime); syncer::ClearObsoleteMemoryPressurePrefs(profile_prefs); + profile_prefs->ClearPref(kLastKnownGoogleURL); + profile_prefs->ClearPref(kLastPromptedGoogleURL); #if defined(OS_ANDROID) // Added 7/2019.
diff --git a/chrome/browser/prefs/pref_service_incognito_whitelist.cc b/chrome/browser/prefs/pref_service_incognito_whitelist.cc index aaea15c..2434f00 100644 --- a/chrome/browser/prefs/pref_service_incognito_whitelist.cc +++ b/chrome/browser/prefs/pref_service_incognito_whitelist.cc
@@ -10,7 +10,6 @@ #include "build/build_config.h" #include "chrome/common/pref_names.h" #include "components/bookmarks/common/bookmark_pref_names.h" -#include "components/google/core/browser/google_pref_names.h" #include "components/metrics/metrics_pref_names.h" #include "components/rappor/rappor_pref_names.h" #include "components/reading_list/core/reading_list_pref_names.h" @@ -170,10 +169,6 @@ prefs::kDevToolsDiscoverTCPTargetsEnabled, prefs::kDevToolsTCPDiscoveryConfig, - // Google URL prefs don't store user data and just keep track of the URL. - prefs::kLastKnownGoogleURL, - prefs::kLastPromptedGoogleURL, - #if defined(OS_WIN) // The total number of times that network profile warning is shown is // aggregated between regular and incognito modes.
diff --git a/chrome/browser/previews/hints_fetcher_browsertest.cc b/chrome/browser/previews/hints_fetcher_browsertest.cc index ea29bd5..01ff5af 100644 --- a/chrome/browser/previews/hints_fetcher_browsertest.cc +++ b/chrome/browser/previews/hints_fetcher_browsertest.cc
@@ -40,6 +40,7 @@ #include "components/previews/core/previews_switches.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/network_connection_change_simulator.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "services/network/public/cpp/network_quality_tracker.h" @@ -168,6 +169,11 @@ run_loop.Run(); } + void SetNetworkConnectionOffline() { + content::NetworkConnectionChangeSimulator().SetConnectionType( + network::mojom::ConnectionType::CONNECTION_NONE); + } + // Seeds the Site Engagement Service with two HTTP and two HTTPS sites for the // current profile. void SeedSiteEngagementService() { @@ -652,3 +658,34 @@ optimization_guide::HintCacheStore::StoreEntryType::kComponentHint), 0); } + +IN_PROC_BROWSER_TEST_F( + HintsFetcherBrowserTest, + DISABLE_ON_WIN_MAC_CHROMESOS(HintsFetcherNetworkOffline)) { + const base::HistogramTester* histogram_tester = GetHistogramTester(); + GURL url = https_url(); + base::CommandLine::ForCurrentProcess()->RemoveSwitch( + optimization_guide::switches::kFetchHintsOverride); + base::CommandLine::ForCurrentProcess()->AppendSwitch( + optimization_guide::switches::kFetchHintsOverrideTimer); + + // Set the network to be offline. + SetNetworkConnectionOffline(); + + // Set the blacklist state to initialized so the sites in the engagement + // service will be used and not blacklisted on the first GetTopHosts + // request. + SeedSiteEngagementService(); + + // Set the blacklist state to initialized so the sites in the engagement + // service will be used and not blacklisted on the first GetTopHosts request. + SetTopHostBlacklistState(optimization_guide::prefs:: + HintsFetcherTopHostBlacklistState::kInitialized); + + // Whitelist NoScript for https_url()'s' host. + SetUpComponentUpdateHints(https_url()); + + // No HintsFetch should occur because the connection is offline. + histogram_tester->ExpectTotalCount( + "OptimizationGuide.HintsFetcher.GetHintsRequest.HostCount", 0); +}
diff --git a/chrome/browser/printing/cloud_print/privet_traffic_detector.cc b/chrome/browser/printing/cloud_print/privet_traffic_detector.cc index 60ae78cb5..f8abbf2 100644 --- a/chrome/browser/printing/cloud_print/privet_traffic_detector.cc +++ b/chrome/browser/printing/cloud_print/privet_traffic_detector.cc
@@ -49,9 +49,8 @@ "lo", "lo", 0, net::NetworkChangeNotifier::CONNECTION_UNKNOWN, localhost_prefix, 8, net::IP_ADDRESS_ATTRIBUTE_NONE)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(std::move(callback), std::move(ip4_networks))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(std::move(callback), std::move(ip4_networks))); } void GetNetworkListOnUIThread( @@ -83,10 +82,9 @@ : helper_(new Helper(profile, on_traffic_detected)) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::GetNetworkConnectionTracker()->AddNetworkConnectionObserver(this); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart, - base::Unretained(helper_))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&PrivetTrafficDetector::Helper::ScheduleRestart, + base::Unretained(helper_))); } PrivetTrafficDetector::~PrivetTrafficDetector() { @@ -99,7 +97,7 @@ void PrivetTrafficDetector::OnConnectionChanged( network::mojom::ConnectionType type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrivetTrafficDetector::Helper::HandleConnectionChanged, base::Unretained(helper_), type)); @@ -132,7 +130,7 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); ResetConnection(); weak_ptr_factory_.InvalidateWeakPtrs(); - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &GetNetworkListOnUIThread, @@ -154,7 +152,7 @@ network::mojom::UDPSocketReceiverRequest receiver_request = mojo::MakeRequest(&receiver_ptr); receiver_binding_.Bind(std::move(receiver_request)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&CreateUDPSocketOnUIThread, profile_, mojo::MakeRequest(&socket_), std::move(receiver_ptr))); @@ -256,8 +254,8 @@ recv_addr_ = src_addr.value(); if (IsPrivetPacket(data.value())) { ResetConnection(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - on_traffic_detected_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + on_traffic_detected_); } else { socket_->ReceiveMoreWithBufferSize(1, net::dns_protocol::kMaxMulticastSize); }
diff --git a/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc b/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc index 9a2c2d1d..d8a90a0 100644 --- a/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc +++ b/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc
@@ -288,7 +288,7 @@ void TearDown() override; scoped_refptr<base::SingleThreadTaskRunner> IOTaskRunner() { - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + return base::CreateSingleThreadTaskRunner({BrowserThread::IO}); } base::Process Launch(const std::string& name); void WaitForConnect(mojo::IsolatedConnection* mojo_connection); @@ -438,8 +438,9 @@ EXPECT_TRUE(base::ThreadTaskRunnerHandle::Get().get()); mojo::MessagePipe pipe; - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ConnectAsync, std::move(pipe.handle1), GetServiceProcessServerName(), mojo_connection)); ServiceProcessControl::GetInstance()->SetMojoHandle( @@ -478,7 +479,7 @@ TEST_F(CloudPrintProxyPolicyStartupTest, StartAndShutdown) { mojo::core::Init(); mojo::core::ScopedIPCSupport ipc_support( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({BrowserThread::IO}), mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST); base::Process process =
diff --git a/chrome/browser/printing/print_dialog_cloud_win.cc b/chrome/browser/printing/print_dialog_cloud_win.cc index 0880b83..b77e8bc 100644 --- a/chrome/browser/printing/print_dialog_cloud_win.cc +++ b/chrome/browser/printing/print_dialog_cloud_win.cc
@@ -130,8 +130,9 @@ const base::string16& print_ticket, const std::string& file_type) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFile, path_to_file), base::BindOnce(&CreatePrintDialog, browser_context, print_job_title, print_ticket, file_type));
diff --git a/chrome/browser/printing/print_error_dialog.cc b/chrome/browser/printing/print_error_dialog.cc index 66343db26..1f95636f 100644 --- a/chrome/browser/printing/print_error_dialog.cc +++ b/chrome/browser/printing/print_error_dialog.cc
@@ -28,6 +28,6 @@ void ShowPrintErrorDialog() { // Nested loop may destroy caller. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ShowPrintErrorDialogTask)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ShowPrintErrorDialogTask)); }
diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index b039a047..4324f93 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc
@@ -219,8 +219,8 @@ base::RunLoop loop(base::RunLoop::Type::kNestableTasksAllowed); quit_closure_ = loop.QuitClosure(); - base::PostDelayedTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - loop.QuitClosure(), timeout); + base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI}, + loop.QuitClosure(), timeout); loop.Run(); @@ -451,8 +451,8 @@ } case JobEventDetails::DOC_DONE: { // This will call Stop() and broadcast a JOB_DONE message. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintJob::OnDocumentDone, this)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintJob::OnDocumentDone, this)); break; } #if defined(OS_WIN) @@ -508,7 +508,7 @@ // Delay shutdown until the worker terminates. We want this code path // to wait on the thread to quit before continuing. if (worker_->IsRunning()) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&PrintJob::ControlledWorkerShutdown, this), base::TimeDelta::FromMilliseconds(100)); @@ -518,9 +518,9 @@ // Now make sure the thread object is cleaned up. Do this on a worker // thread because it may block. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::MayBlock(), base::WithBaseSyncPrimitives(), + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PrintJobWorker::Stop, base::Unretained(worker_.get())), @@ -533,8 +533,8 @@ bool PrintJob::PostTask(const base::Location& from_here, base::OnceClosure task) { - return base::PostTaskWithTraits(from_here, {content::BrowserThread::UI}, - std::move(task)); + return base::PostTask(from_here, {content::BrowserThread::UI}, + std::move(task)); } void PrintJob::HoldUntilStopIsCalled() {
diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index 63f432b..72a0c8c 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc
@@ -165,16 +165,15 @@ // When we delegate to a destination, we don't ask the user for settings. // TODO(mad): Ask the destination for settings. if (ask_user_for_settings) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PrintJobWorker::GetSettingsWithUI, base::Unretained(this), document_page_count, has_selection, is_scripted, std::move(callback))); } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UseDefaultSettings, - base::Unretained(this), std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UseDefaultSettings, + base::Unretained(this), std::move(callback))); } } @@ -182,11 +181,10 @@ SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UpdatePrintSettings, - base::Unretained(this), std::move(new_settings), - std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UpdatePrintSettings, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #if defined(OS_CHROMEOS) @@ -195,11 +193,10 @@ SettingsCallback callback) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, - base::Unretained(this), std::move(new_settings), - std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PrintJobWorker::UpdatePrintSettingsFromPOD, + base::Unretained(this), std::move(new_settings), + std::move(callback))); } #endif
diff --git a/chrome/browser/printing/print_preview_message_handler.cc b/chrome/browser/printing/print_preview_message_handler.cc index 5fd2ea6..e18eeb6 100644 --- a/chrome/browser/printing/print_preview_message_handler.cc +++ b/chrome/browser/printing/print_preview_message_handler.cc
@@ -51,7 +51,7 @@ std::unique_ptr<PrinterQuery> printer_query = queue->PopPrinterQuery(document_cookie); if (printer_query) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); }
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index 0a52572..046cb140 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -79,7 +79,7 @@ std::unique_ptr<PrinterQuery> query) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(std::move(settings_callback), std::move(query))); } @@ -143,7 +143,7 @@ weak_ptr_factory_.GetWeakPtr(), print_data, job_settings.FindIntKey(kSettingPreviewPageCount).value(), std::move(callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(CreateQueryWithSettings, std::move(job_settings), rfh->GetProcess()->GetID(), rfh->GetRoutingID(), queue_, @@ -184,17 +184,16 @@ if (printer_query->last_status() == PrintingContext::CANCEL) { queue_->QueuePrinterQuery(std::move(printer_query)); #if defined(OS_WIN) - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled, - weak_ptr_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintViewManagerBase::SystemDialogCancelled, + weak_ptr_factory_.GetWeakPtr())); #endif std::move(callback).Run(base::Value()); return; } if (!printer_query->cookie() || !printer_query->settings().dpi()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); std::move(callback).Run(base::Value("Update settings failed")); @@ -205,11 +204,10 @@ // OnDidGetPrintedPagesCount(). int cookie = printer_query->cookie(); queue_->QueuePrinterQuery(std::move(printer_query)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob, - weak_ptr_factory_.GetWeakPtr(), print_data, page_count, - cookie, std::move(callback))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&PrintViewManagerBase::StartLocalPrintJob, + weak_ptr_factory_.GetWeakPtr(), print_data, + page_count, cookie, std::move(callback))); } void PrintViewManagerBase::StartLocalPrintJob( @@ -704,7 +702,7 @@ std::unique_ptr<PrinterQuery> printer_query = queue_->PopPrinterQuery(cookie); if (!printer_query) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::StopWorker, std::move(printer_query))); }
diff --git a/chrome/browser/printing/printer_manager_dialog_linux.cc b/chrome/browser/printing/printer_manager_dialog_linux.cc index 672a6c5c..f236c05 100644 --- a/chrome/browser/printing/printer_manager_dialog_linux.cc +++ b/chrome/browser/printing/printer_manager_dialog_linux.cc
@@ -88,8 +88,9 @@ namespace printing { void PrinterManagerDialog::ShowPrinterManagerDialog(Profile* profile) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&DetectAndOpenPrinterConfigDialog)); }
diff --git a/chrome/browser/printing/printer_manager_dialog_win.cc b/chrome/browser/printing/printer_manager_dialog_win.cc index 3bb3253..a6a4e9c1 100644 --- a/chrome/browser/printing/printer_manager_dialog_win.cc +++ b/chrome/browser/printing/printer_manager_dialog_win.cc
@@ -39,9 +39,10 @@ if (base::win::GetVersion() >= base::win::Version::WIN10_RS1) { platform_util::OpenExternal(profile, GURL("ms-settings:printers")); } else { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, - base::BindOnce(OpenPrintersDialogCallback)); + base::PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}, + base::BindOnce(OpenPrintersDialogCallback)); } }
diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc index 6bd6dd72..3ea696ae 100644 --- a/chrome/browser/printing/printer_query.cc +++ b/chrome/browser/printing/printer_query.cc
@@ -57,7 +57,7 @@ const PrintSettings& new_settings, PrintingContext::Result result) { // |this| is owned by |callback|, so |base::Unretained()| is safe. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PrinterQuery::GetSettingsDone, base::Unretained(this), std::move(callback), new_settings, result)); @@ -161,8 +161,8 @@ bool PrinterQuery::PostTask(const base::Location& from_here, base::OnceClosure task) { - return base::PostTaskWithTraits(from_here, {content::BrowserThread::IO}, - std::move(task)); + return base::PostTask(from_here, {content::BrowserThread::IO}, + std::move(task)); } bool PrinterQuery::is_valid() const {
diff --git a/chrome/browser/printing/printing_message_filter.cc b/chrome/browser/printing/printing_message_filter.cc index 706617b7..355324f 100644 --- a/chrome/browser/printing/printing_message_filter.cc +++ b/chrome/browser/printing/printing_message_filter.cc
@@ -102,7 +102,7 @@ base::Unretained(this))); is_printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs()); is_printing_enabled_.MoveToSequence( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); + base::CreateSingleThreadTaskRunner({BrowserThread::IO})); } PrintingMessageFilter::~PrintingMessageFilter() { @@ -269,7 +269,7 @@ #if defined(OS_WIN) && BUILDFLAG(ENABLE_PRINT_PREVIEW) if (canceled) { int routing_id = reply_msg->routing_id(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PrintingMessageFilter::NotifySystemDialogCancelled, this, routing_id));
diff --git a/chrome/browser/profile_resetter/profile_resetter_test_base.cc b/chrome/browser/profile_resetter/profile_resetter_test_base.cc index d8ab04c..9d6ef45 100644 --- a/chrome/browser/profile_resetter/profile_resetter_test_base.cc +++ b/chrome/browser/profile_resetter/profile_resetter_test_base.cc
@@ -64,9 +64,8 @@ content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); return std::make_unique<TemplateURLService>( - profile->GetPrefs(), std::make_unique<UIThreadSearchTermsData>(profile), + profile->GetPrefs(), std::make_unique<UIThreadSearchTermsData>(), WebDataServiceFactory::GetKeywordWebDataForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), - std::unique_ptr<TemplateURLServiceClient>(), nullptr, nullptr, - base::Closure()); + nullptr, nullptr, base::Closure()); }
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index dea351ca..4a2aaef 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -33,7 +33,6 @@ #include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h" #include "chrome/browser/feature_engagement/tracker_factory.h" #include "chrome/browser/google/google_search_domain_mixing_metrics_emitter_factory.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/invalidation/deprecated_profile_invalidation_provider_factory.h" @@ -289,7 +288,6 @@ GlobalErrorServiceFactory::GetInstance(); #endif GoogleSearchDomainMixingMetricsEmitterFactory::GetInstance(); - GoogleURLTrackerFactory::GetInstance(); HistoryServiceFactory::GetInstance(); HostContentSettingsMapFactory::GetInstance(); IdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt();
diff --git a/chrome/browser/resources/print_preview/polymer3/demo.js b/chrome/browser/resources/print_preview/polymer3/demo.js index 6a59ffd..4d1df534 100644 --- a/chrome/browser/resources/print_preview/polymer3/demo.js +++ b/chrome/browser/resources/print_preview/polymer3/demo.js
@@ -2,29 +2,63 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'chrome://resources/polymer/v3_0/paper-button/paper-button.js'; +import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; +import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; +import 'chrome://resources/cr_elements/cr_toast/cr_toast.m.js'; +import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js'; +import 'chrome://resources/cr_elements/icons.m.js'; +import 'chrome://resources/cr_elements/md_select_css.m.js'; +import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; class HelloPolymer3Element extends PolymerElement { static get template() { return html` - <div>Hello Polymer3 [[time]]</div> - <paper-button on-click="onClick_">Update time</paper-button> + <style include="md-select"> + cr-toggle { + display: inline-block; + } + </style> + + <cr-checkbox checked="{{checkboxChecked_}}"> + [[checkboxChecked_]] + </cr-checkbox> + + <div> + <cr-toggle checked="{{toggleChecked_}}"></cr-toggle> + <span>[[toggleChecked_]]</span> + </div> + + <select class="md-select"> + <option>JS</option> + <option>modules</option> + <option>are</option> + <option>cool</option> + </select> + + <div> + <cr-button on-click="onClick_">Show toast</cr-button> + <cr-toast><span>I am toasted</span></cr-toast> + </div> + + <iron-icon icon="cr:error"></iron-icon> `; } static get properties() { return { - time: { - type: Number, - value: Date.now(), - }, + /** @private */ + toggleChecked_: Boolean, + + /** @private */ + checkboxChecked_: Boolean, }; } + /** @private */ onClick_() { - this.time = Date.now(); + this.shadowRoot.querySelector('cr-toast').show(2000); } } // class HelloPolymer3
diff --git a/chrome/browser/resources/settings/chromeos/OWNERS b/chrome/browser/resources/settings/chromeos/OWNERS index 5fb80bb..addef34 100644 --- a/chrome/browser/resources/settings/chromeos/OWNERS +++ b/chrome/browser/resources/settings/chromeos/OWNERS
@@ -1,4 +1,6 @@ maybelle@chromium.org jamescook@chromium.org +michaelpg@chromium.org +stevenjb@chromium.org # COMPONENT: OS>Systems>Settings
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc index 7f9b055..f9036e8 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.cc
@@ -592,6 +592,8 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // This will cause the next ::ReadFile call in ServiceChromePromptRequests to // fail, triggering the error handler that kills the cleaner process. + ::CancelIoEx(request_read_handle_.Get(), nullptr); + ::CancelIoEx(response_write_handle_.Get(), nullptr); request_read_handle_.Close(); response_write_handle_.Close(); } @@ -613,6 +615,8 @@ // an error, could just be a more recent cleaner version.) if (!request.unknown_fields().empty()) { LOG(ERROR) << "Discarding PromptUserRequest with unknown fields."; + WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, + CustomErrors::kRequestUnknownField); return; } @@ -623,6 +627,8 @@ if (!base::UTF8ToUTF16(file_path.c_str(), file_path.size(), &file_path_utf16)) { LOG(ERROR) << "Undisplayable file path in PromptUserRequest."; + WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, + CustomErrors::kUndisplayableFilePath); return; } files_to_delete.push_back(base::FilePath(file_path_utf16)); @@ -637,6 +643,9 @@ if (!base::UTF8ToUTF16(registry_key.c_str(), registry_key.size(), ®istry_key_utf16)) { LOG(ERROR) << "Undisplayable registry key in PromptUserRequest."; + WriteStatusErrorCodeToHistogram( + ErrorCategory::kCustomError, + CustomErrors::kUndisplayableRegistryKey); return; } registry_keys.push_back(registry_key_utf16); @@ -655,6 +664,8 @@ if (!base::UTF8ToUTF16(extension_id.c_str(), extension_id.size(), &extension_id_utf16)) { LOG(ERROR) << "Undisplayable extension id in PromptUserRequest."; + WriteStatusErrorCodeToHistogram(ErrorCategory::kCustomError, + CustomErrors::kUndisplayableExtension); return; } extension_ids.push_back(extension_id_utf16);
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h index d06297b5..6e3776f 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win.h
@@ -159,6 +159,10 @@ kRequestInvalidSize = 4, kRequestContentInvalid = 5, kRequestUnknown = 6, + kRequestUnknownField = 7, + kUndisplayableFilePath = 8, + kUndisplayableRegistryKey = 9, + kUndisplayableExtension = 9, }; static int32_t GetErrorCodeInt(ErrorCategory category,
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc index 93178df6..3076e1c 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/chrome_prompt_channel_win_unittest.cc
@@ -116,6 +116,15 @@ this, &ChromePromptChannelProtobufTest::CloseCleanerHandles)); } + // Expect the histograms contains at least the specified sample. + template <typename T> + void ExpectSample(ErrorCategory category, T error, int count = 1) { + histogram_tester_.ExpectBucketCount( + ChromePromptChannelProtobuf::kErrorHistogramName, + ChromePromptChannelProtobuf::GetErrorCodeInt(category, error), count); + } + + // Expect that the histogram contains only the specified sample. template <typename T> void ExpectUniqueSample(ErrorCategory category, T error, int count = 1) { histogram_tester_.ExpectUniqueSample( @@ -123,19 +132,14 @@ ChromePromptChannelProtobuf::GetErrorCodeInt(category, error), count); } - void ExpectHistogramEmpty() { + void ExpectHistogramSize(uint32_t size) { histogram_tester_.ExpectTotalCount( - ChromePromptChannelProtobuf::kErrorHistogramName, 0); + ChromePromptChannelProtobuf::kErrorHistogramName, size); } // This is used when we want to validate that certain operations failed a // precise number of times without needing to know the specific error code. void ExpectCategoryErrorCount(const ErrorExpectationMap& expected_counts) { - // Not to be used with CustomErrors as those are well-known. - EXPECT_THAT(expected_counts, - Not(Contains(Key(ErrorCategory::kCustomError)))) - << "For custom errors please use ExpectUniqueSample"; - const std::vector<base::Bucket> buckets = histogram_tester_.GetAllSamples( ChromePromptChannelProtobuf::kErrorHistogramName); @@ -526,15 +530,15 @@ std::string request_content; PostRequestWrite(request, &request_content); - PostCloseCleanerHandles(); + // Here we should not post a disconnect since the error will trigger one. WaitForDisconnect(); - // Having extra fields in PromptUserRequest should not cause any problems. - // This means the handling of the first message does not generate errors. The - // only error we see is the reading of the next request length which cannot - // succeed because we closed the pipes. - ExpectCategoryErrorCount({{ErrorCategory::kReadRequestLengthWinError, 1}}); + // The ReadRequestLengthWinError is because the pipe was closed by the unknown + // field error handler while waiting for the next request. + ExpectCategoryErrorCount({{ErrorCategory::kReadRequestLengthWinError, 1}, + {ErrorCategory::kCustomError, 1}}); + ExpectSample(ErrorCategory::kCustomError, CustomErrors::kRequestUnknownField); ExpectReadFails(); }
diff --git a/chrome/browser/search/instant_service.cc b/chrome/browser/search/instant_service.cc index 2f0b54b..379fc9c 100644 --- a/chrome/browser/search/instant_service.cc +++ b/chrome/browser/search/instant_service.cc
@@ -67,6 +67,7 @@ "attribution_action_url"; const char kNtpCustomBackgroundCollectionId[] = "collection_id"; const char kNtpCustomBackgroundResumeToken[] = "resume_token"; +const char kNtpCustomBackgroundRefreshTimestamp[] = "refresh_timestamp"; const char kCustomBackgroundsUmaClientName[] = "NtpCustomBackgrounds"; @@ -76,7 +77,8 @@ const std::string& attribution_line_2, const GURL& action_url, const base::Optional<std::string>& collection_id, - const base::Optional<std::string>& resume_token) { + const base::Optional<std::string>& resume_token, + const base::Optional<int> refresh_timestamp) { base::DictionaryValue background_info; background_info.SetKey(kNtpCustomBackgroundURL, base::Value(background_url.spec())); @@ -90,6 +92,8 @@ base::Value(collection_id.value_or(""))); background_info.SetKey(kNtpCustomBackgroundResumeToken, base::Value(resume_token.value_or(""))); + background_info.SetKey(kNtpCustomBackgroundRefreshTimestamp, + base::Value(refresh_timestamp.value_or(0))); return background_info; } @@ -112,6 +116,8 @@ *background_info->FindKey(kNtpCustomBackgroundCollectionId)); auto resume_token = const_cast<base::Value&&>( *background_info->FindKey(kNtpCustomBackgroundResumeToken)); + auto refresh_timestamp = const_cast<base::Value&&>( + *background_info->FindKey(kNtpCustomBackgroundRefreshTimestamp)); new_background_info.SetKey(kNtpCustomBackgroundURL, url.Clone()); new_background_info.SetKey(kNtpCustomBackgroundAttributionLine1, @@ -126,6 +132,8 @@ collection_id.Clone()); new_background_info.SetKey(kNtpCustomBackgroundResumeToken, resume_token.Clone()); + new_background_info.SetKey(kNtpCustomBackgroundRefreshTimestamp, + refresh_timestamp.Clone()); return new_background_info; } @@ -143,6 +151,8 @@ base::Value(base::Value::Type::STRING)); defaults.SetKey(kNtpCustomBackgroundResumeToken, base::Value(base::Value::Type::STRING)); + defaults.SetKey(kNtpCustomBackgroundRefreshTimestamp, + base::Value(base::Value::Type::INTEGER)); return defaults; } @@ -171,7 +181,8 @@ theme_observer_(this), background_service_observer_(this), native_theme_(ui::NativeTheme::GetInstanceForNativeUi()), - background_updated_timestamp_(base::TimeTicks::Now()) { + background_updated_timestamp_(base::TimeTicks::Now()), + clock_(base::DefaultClock::GetInstance()) { // The initialization below depends on a typical set of browser threads. Skip // it if we are running in a unit test without the full suite. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) @@ -462,7 +473,7 @@ base::DictionaryValue background_info = GetBackgroundInfoAsDict( background_url, attribution_line_1, attribution_line_2, action_url, - base::nullopt, base::nullopt); + base::nullopt, base::nullopt, base::nullopt); pref_service_->Set(prefs::kNtpCustomBackgroundDict, background_info); } else { pref_service_->ClearPref(prefs::kNtpCustomBackgroundDict); @@ -491,6 +502,8 @@ } ThemeBackgroundInfo* InstantService::GetInitializedThemeInfo() { + RefreshBackgroundIfNeeded(); + if (!theme_info_) BuildThemeInfo(); return theme_info_.get(); @@ -529,10 +542,12 @@ attribution2 = image.attribution[1]; std::string resume_token = background_service_->next_image_resume_token(); + int64_t timestamp = (clock_->Now() + base::TimeDelta::FromDays(1)).ToTimeT(); base::DictionaryValue background_info = GetBackgroundInfoAsDict( image.image_url, attribution1, attribution2, image.attribution_action_url, - image.collection_id, resume_token); + image.collection_id, resume_token, timestamp); + pref_service_->Set(prefs::kNtpCustomBackgroundDict, background_info); } @@ -967,7 +982,28 @@ } } +void InstantService::RefreshBackgroundIfNeeded() { + const base::DictionaryValue* background_info = + profile_->GetPrefs()->GetDictionary(prefs::kNtpCustomBackgroundDict); + int64_t refresh_timestamp = + background_info->FindKey(kNtpCustomBackgroundRefreshTimestamp)->GetInt(); + if (refresh_timestamp == 0) + return; + + if (clock_->Now().ToTimeT() > refresh_timestamp) { + std::string collection_id = + background_info->FindKey(kNtpCustomBackgroundCollectionId)->GetString(); + std::string resume_token = + background_info->FindKey(kNtpCustomBackgroundResumeToken)->GetString(); + background_service_->FetchNextCollectionImage(collection_id, resume_token); + } +} + void InstantService::SetImageFetcherForTesting( image_fetcher::ImageFetcher* image_fetcher) { image_fetcher_ = base::WrapUnique(image_fetcher); } + +void InstantService::SetClockForTesting(base::Clock* clock) { + clock_ = clock; +}
diff --git a/chrome/browser/search/instant_service.h b/chrome/browser/search/instant_service.h index a33c887..0d60ba6d 100644 --- a/chrome/browser/search/instant_service.h +++ b/chrome/browser/search/instant_service.h
@@ -206,6 +206,7 @@ FRIEND_TEST_ALL_PREFIXES(InstantServiceTest, TestUpdateCustomBackgroundColor); FRIEND_TEST_ALL_PREFIXES(InstantServiceTest, LocalImageDoesNotUpdateCustomBackgroundColor); + FRIEND_TEST_ALL_PREFIXES(InstantServiceTest, RefreshesBackgroundAfter24Hours); // KeyedService: void Shutdown() override; @@ -272,10 +273,15 @@ void SetImageFetcherForTesting(image_fetcher::ImageFetcher* image_fetcher); + void SetClockForTesting(base::Clock* clock); + base::TimeTicks GetBackgroundUpdatedTimestampForTesting() { return background_updated_timestamp_; } + // Requests a new background image if it hasn't been updated in >24 hours. + void RefreshBackgroundIfNeeded(); + Profile* const profile_; // The process ids associated with Instant processes. @@ -317,6 +323,8 @@ base::TimeTicks background_updated_timestamp_; + base::Clock* clock_; + base::WeakPtrFactory<InstantService> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(InstantService);
diff --git a/chrome/browser/search/instant_service_unittest.cc b/chrome/browser/search/instant_service_unittest.cc index 99c3fd49..8abf1c4 100644 --- a/chrome/browser/search/instant_service_unittest.cc +++ b/chrome/browser/search/instant_service_unittest.cc
@@ -43,10 +43,27 @@ background_info.SetKey("attribution_action_url", base::Value(std::string())); background_info.SetKey("collection_id", base::Value(std::string())); background_info.SetKey("resume_token", base::Value(std::string())); - + background_info.SetKey("refresh_timestamp", base::Value(0)); return background_info; } +base::Time GetReferenceTime() { + base::Time::Exploded exploded_reference_time; + exploded_reference_time.year = 2019; + exploded_reference_time.month = 1; + exploded_reference_time.day_of_month = 1; + exploded_reference_time.day_of_week = 1; + exploded_reference_time.hour = 0; + 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; +} + class MockInstantService : public InstantService { public: explicit MockInstantService(Profile* profile) : InstantService(profile) {} @@ -711,3 +728,48 @@ EXPECT_EQ("https://www.test.com/", theme_info->custom_background_url); EXPECT_TRUE(instant_service_->IsCustomBackgroundSet()); } + +TEST_F(InstantServiceTest, RefreshesBackgroundAfter24Hours) { + ASSERT_FALSE(instant_service_->IsCustomBackgroundSet()); + const std::string kValidId("art"); + const GURL kImageUrl1("https://www.test.com/1/"); + const GURL kImageUrl2("https://www.test.com/2/"); + + instant_service_->SetClockForTesting(clock_); + clock_->SetNow(GetReferenceTime()); + + // A valid id should update the pref/background. + CollectionImage image; + image.collection_id = kValidId; + image.image_url = kImageUrl1; + instant_service_->SetNextCollectionImageForTesting(image); + + instant_service_->AddValidBackdropCollectionForTesting(kValidId); + instant_service_->SetCustomBackgroundInfo(GURL(), "", "", GURL(), kValidId); + thread_bundle()->RunUntilIdle(); + + ThemeBackgroundInfo* theme_info = instant_service_->GetInitializedThemeInfo(); + EXPECT_EQ(kValidId, theme_info->collection_id); + EXPECT_TRUE(instant_service_->IsCustomBackgroundSet()); + + CollectionImage image2; + image2.collection_id = kValidId; + image2.image_url = kImageUrl2; + instant_service_->SetNextCollectionImageForTesting(image2); + + // Should not refresh background. + theme_info = instant_service_->GetInitializedThemeInfo(); + thread_bundle()->RunUntilIdle(); + EXPECT_EQ(kValidId, theme_info->collection_id); + EXPECT_EQ(kImageUrl1, theme_info->custom_background_url); + EXPECT_TRUE(instant_service_->IsCustomBackgroundSet()); + + clock_->Advance(base::TimeDelta::FromHours(25)); + + // Should refresh background after >24 hours. + theme_info = instant_service_->GetInitializedThemeInfo(); + thread_bundle()->RunUntilIdle(); + EXPECT_EQ(kValidId, theme_info->collection_id); + EXPECT_EQ(kImageUrl2, theme_info->custom_background_url); + EXPECT_TRUE(instant_service_->IsCustomBackgroundSet()); +}
diff --git a/chrome/browser/search/instant_unittest_base.cc b/chrome/browser/search/instant_unittest_base.cc index 69f1e02..04efbf3 100644 --- a/chrome/browser/search/instant_unittest_base.cc +++ b/chrome/browser/search/instant_unittest_base.cc
@@ -18,8 +18,6 @@ #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/search_test_utils.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/image_fetcher/core/mock_image_fetcher.h" #include "components/search/search.h" #include "components/search_engines/template_url.h" @@ -37,10 +35,11 @@ void InstantUnitTestBase::SetUp() { BrowserWithTestWindowTest::SetUp(); + clock_ = new base::SimpleTestClock(); + template_url_service_ = TemplateURLServiceFactory::GetForProfile(profile()); search_test_utils::WaitForTemplateURLServiceToLoad(template_url_service_); - UIThreadSearchTermsData::SetGoogleBaseURL("https://www.google.com/"); SetUserSelectedDefaultSearchProvider("{google:baseURL}"); instant_service_ = InstantServiceFactory::GetForProfile(profile()); @@ -49,7 +48,9 @@ } void InstantUnitTestBase::TearDown() { - UIThreadSearchTermsData::SetGoogleBaseURL(""); + delete clock_; + clock_ = nullptr; + BrowserWithTestWindowTest::TearDown(); } @@ -67,17 +68,6 @@ template_url_service_->SetUserSelectedDefaultSearchProvider(template_url); } -void InstantUnitTestBase::NotifyGoogleBaseURLUpdate( - const std::string& new_google_base_url) { - // GoogleURLTracker is not created in tests. - // (See GoogleURLTrackerFactory::ServiceIsNULLWhileTesting()) - // For determining google:baseURL for NTP, the following is used: - // UIThreadSearchTermsData::GoogleBaseURLValue() - // For simulating test behavior, this is overridden below. - UIThreadSearchTermsData::SetGoogleBaseURL(new_google_base_url); - TemplateURLServiceFactory::GetForProfile(profile())->GoogleBaseURLChanged(); -} - TestingProfile* InstantUnitTestBase::CreateProfile() { TestingProfile* profile = BrowserWithTestWindowTest::CreateProfile(); TemplateURLServiceFactory::GetInstance()->SetTestingFactoryAndUse(
diff --git a/chrome/browser/search/instant_unittest_base.h b/chrome/browser/search/instant_unittest_base.h index 2956d2d7..344f77d 100644 --- a/chrome/browser/search/instant_unittest_base.h +++ b/chrome/browser/search/instant_unittest_base.h
@@ -8,6 +8,7 @@ #include <string> #include "base/metrics/field_trial.h" +#include "base/test/simple_test_clock.h" #include "build/build_config.h" #include "chrome/browser/search/instant_service.h" #include "chrome/test/base/browser_with_test_window_test.h" @@ -31,14 +32,10 @@ // search_terms_replacement_key. void SetUserSelectedDefaultSearchProvider(const std::string& base_url); - // Simulates a Google Base URL change as would happen in event of - // search-domain-check. Note that the GoogleURLTrackerFactory is disabled for - // tests, so this is required. - void NotifyGoogleBaseURLUpdate(const std::string& new_google_base_url); - InstantService* instant_service_; TemplateURLService* template_url_service_; std::unique_ptr<base::FieldTrialList> field_trial_list_; + base::SimpleTestClock* clock_; private: // BrowserWithTestWindowTest override:
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc index b5a2125..8331944 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.cc
@@ -16,7 +16,6 @@ #include "chrome/browser/search/one_google_bar/one_google_bar_data.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/webui_url_constants.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "components/variations/net/variations_http_headers.h" #include "content/public/browser/system_connector.h" @@ -267,11 +266,9 @@ OneGoogleBarLoaderImpl::OneGoogleBarLoaderImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker, const std::string& application_locale, bool account_consistency_mirror_required) : url_loader_factory_(url_loader_factory), - google_url_tracker_(google_url_tracker), application_locale_(application_locale), account_consistency_mirror_required_( account_consistency_mirror_required) {} @@ -298,7 +295,7 @@ GURL OneGoogleBarLoaderImpl::GetApiUrl() const { GURL google_base_url = google_util::CommandLineGoogleBaseURL(); if (!google_base_url.is_valid()) { - google_base_url = google_url_tracker_->google_url(); + google_base_url = GURL(google_util::kGoogleHomepageURL); } GURL api_url = google_base_url.Resolve(kNewTabOgbApiPath);
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.h b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.h index d5ba4a0..363076e 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.h +++ b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl.h
@@ -14,8 +14,6 @@ #include "base/optional.h" #include "chrome/browser/search/one_google_bar/one_google_bar_loader.h" -class GoogleURLTracker; - namespace base { class Value; } @@ -31,7 +29,6 @@ public: OneGoogleBarLoaderImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker, const std::string& application_locale, bool account_consistency_mirror_required); ~OneGoogleBarLoaderImpl() override; @@ -54,7 +51,6 @@ void Respond(Status status, const base::Optional<OneGoogleBarData>& data); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - GoogleURLTracker* google_url_tracker_; const std::string application_locale_; const bool account_consistency_mirror_required_;
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc index 5c59e12..34383ee 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_loader_impl_unittest.cc
@@ -14,7 +14,6 @@ #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" #include "chrome/browser/search/one_google_bar/one_google_bar_data.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/signin/core/browser/signin_header_helper.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_service_manager_context.h" @@ -23,7 +22,6 @@ #include "services/data_decoder/public/cpp/testing_json_parser.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "services/network/test/test_network_connection_tracker.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,22 +41,6 @@ "page_hooks": {} }}})json"; -// Required to instantiate a GoogleUrlTracker in UNIT_TEST_MODE. -class GoogleURLTrackerClientStub : public GoogleURLTrackerClient { - public: - GoogleURLTrackerClientStub() {} - ~GoogleURLTrackerClientStub() override {} - - bool IsBackgroundNetworkingEnabled() override { return true; } - PrefService* GetPrefs() override { return nullptr; } - network::SharedURLLoaderFactory* GetURLLoaderFactory() override { - return nullptr; - } - - private: - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClientStub); -}; - } // namespace ACTION_P(Quit, run_loop) { @@ -73,25 +55,17 @@ explicit OneGoogleBarLoaderImplTest(bool account_consistency_mirror_required) : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), - google_url_tracker_( - std::make_unique<GoogleURLTrackerClientStub>(), - GoogleURLTracker::ALWAYS_DOT_COM_MODE, - network::TestNetworkConnectionTracker::GetInstance()), test_shared_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)), account_consistency_mirror_required_( account_consistency_mirror_required) {} - ~OneGoogleBarLoaderImplTest() override { - static_cast<KeyedService&>(google_url_tracker_).Shutdown(); - } - void SetUp() override { testing::Test::SetUp(); one_google_bar_loader_ = std::make_unique<OneGoogleBarLoaderImpl>( - test_shared_loader_factory_, &google_url_tracker_, kApplicationLocale, + test_shared_loader_factory_, kApplicationLocale, account_consistency_mirror_required_); } @@ -129,7 +103,6 @@ data_decoder::TestingJsonParser::ScopedFactoryOverride factory_override_; - GoogleURLTracker google_url_tracker_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; bool account_consistency_mirror_required_;
diff --git a/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc b/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc index ba808e1..3bdbb36 100644 --- a/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc +++ b/chrome/browser/search/one_google_bar/one_google_bar_service_factory.cc
@@ -11,7 +11,6 @@ #include "base/optional.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/one_google_bar/one_google_bar_loader_impl.h" #include "chrome/browser/search/one_google_bar/one_google_bar_service.h" @@ -41,7 +40,6 @@ "OneGoogleBarService", BrowserContextDependencyManager::GetInstance()) { DependsOn(CookieSettingsFactory::GetInstance()); - DependsOn(GoogleURLTrackerFactory::GetInstance()); DependsOn(IdentityManagerFactory::GetInstance()); } @@ -53,8 +51,6 @@ Profile* profile = Profile::FromBrowserContext(context); signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); - GoogleURLTracker* google_url_tracker = - GoogleURLTrackerFactory::GetForProfile(profile); content_settings::CookieSettings* cookie_settings = CookieSettingsFactory::GetForProfile(profile).get(); auto url_loader_factory = @@ -63,8 +59,7 @@ return new OneGoogleBarService( identity_manager, std::make_unique<OneGoogleBarLoaderImpl>( - url_loader_factory, google_url_tracker, - g_browser_process->GetApplicationLocale(), + url_loader_factory, g_browser_process->GetApplicationLocale(), AccountConsistencyModeManager::IsMirrorEnabledForProfile(profile) && signin::SettingsAllowSigninCookies(cookie_settings))); }
diff --git a/chrome/browser/search/promos/promo_service.cc b/chrome/browser/search/promos/promo_service.cc index 127ab3f1..da8ca2a4 100644 --- a/chrome/browser/search/promos/promo_service.cc +++ b/chrome/browser/search/promos/promo_service.cc
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/values.h" #include "chrome/common/webui_url_constants.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "content/public/browser/system_connector.h" #include "net/base/load_flags.h" @@ -80,17 +79,15 @@ } // namespace PromoService::PromoService( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker) - : url_loader_factory_(url_loader_factory), - google_url_tracker_(google_url_tracker) {} + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) + : url_loader_factory_(url_loader_factory) {} PromoService::~PromoService() = default; GURL PromoService::GetGoogleBaseUrl() const { GURL google_base_url = google_util::CommandLineGoogleBaseURL(); if (!google_base_url.is_valid()) { - google_base_url = google_url_tracker_->google_url(); + google_base_url = GURL(google_util::kGoogleHomepageURL); } return google_base_url;
diff --git a/chrome/browser/search/promos/promo_service.h b/chrome/browser/search/promos/promo_service.h index 39fe6c4..0c3039f 100644 --- a/chrome/browser/search/promos/promo_service.h +++ b/chrome/browser/search/promos/promo_service.h
@@ -14,7 +14,6 @@ #include "chrome/browser/search/promos/promo_service_observer.h" #include "components/keyed_service/core/keyed_service.h" -class GoogleURLTracker; class GURL; namespace network { @@ -41,9 +40,8 @@ FATAL_ERROR }; - PromoService( - scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker); + explicit PromoService( + scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory); ~PromoService() override; // KeyedService implementation. @@ -80,8 +78,6 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; std::unique_ptr<network::SimpleURLLoader> simple_loader_; - GoogleURLTracker* google_url_tracker_; - base::ObserverList<PromoServiceObserver, true>::Unchecked observers_; base::Optional<PromoData> promo_data_;
diff --git a/chrome/browser/search/promos/promo_service_factory.cc b/chrome/browser/search/promos/promo_service_factory.cc index e6ef4572..240a662 100644 --- a/chrome/browser/search/promos/promo_service_factory.cc +++ b/chrome/browser/search/promos/promo_service_factory.cc
@@ -11,7 +11,6 @@ #include "base/optional.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/promos/promo_service.h" #include "chrome/browser/signin/account_consistency_mode_manager.h" @@ -37,18 +36,14 @@ "PromoService", BrowserContextDependencyManager::GetInstance()) { DependsOn(CookieSettingsFactory::GetInstance()); - DependsOn(GoogleURLTrackerFactory::GetInstance()); } PromoServiceFactory::~PromoServiceFactory() = default; KeyedService* PromoServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { - Profile* profile = Profile::FromBrowserContext(context); - GoogleURLTracker* google_url_tracker = - GoogleURLTrackerFactory::GetForProfile(profile); auto url_loader_factory = content::BrowserContext::GetDefaultStoragePartition(context) ->GetURLLoaderFactoryForBrowserProcess(); - return new PromoService(url_loader_factory, google_url_tracker); + return new PromoService(url_loader_factory); }
diff --git a/chrome/browser/search/promos/promo_service_unittest.cc b/chrome/browser/search/promos/promo_service_unittest.cc index c09487c73..5719b89 100644 --- a/chrome/browser/search/promos/promo_service_unittest.cc +++ b/chrome/browser/search/promos/promo_service_unittest.cc
@@ -11,13 +11,11 @@ #include "base/test/bind_test_util.h" #include "base/test/scoped_task_environment.h" #include "chrome/browser/search/promos/promo_data.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_service_manager_context.h" #include "services/data_decoder/public/cpp/testing_json_parser.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" -#include "services/network/test/test_network_connection_tracker.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -26,46 +24,18 @@ using testing::Eq; using testing::StartsWith; -namespace { -// Required to instantiate a GoogleUrlTracker in UNIT_TEST_MODE. -class GoogleURLTrackerClientStub : public GoogleURLTrackerClient { - public: - GoogleURLTrackerClientStub() {} - ~GoogleURLTrackerClientStub() override {} - - bool IsBackgroundNetworkingEnabled() override { return true; } - PrefService* GetPrefs() override { return nullptr; } - network::SharedURLLoaderFactory* GetURLLoaderFactory() override { - return nullptr; - } - - private: - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClientStub); -}; - -} // namespace - class PromoServiceTest : public testing::Test { public: PromoServiceTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), test_shared_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( - &test_url_loader_factory_)), - google_url_tracker_( - std::make_unique<GoogleURLTrackerClientStub>(), - GoogleURLTracker::ALWAYS_DOT_COM_MODE, - network::TestNetworkConnectionTracker::GetInstance()) {} + &test_url_loader_factory_)) {} void SetUp() override { testing::Test::SetUp(); - service_ = std::make_unique<PromoService>(test_shared_loader_factory_, - &google_url_tracker_); - } - - void TearDown() override { - static_cast<KeyedService&>(google_url_tracker_).Shutdown(); + service_ = std::make_unique<PromoService>(test_shared_loader_factory_); } void SetUpResponseWithData(const GURL& load_url, @@ -95,8 +65,6 @@ network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; - GoogleURLTracker google_url_tracker_; - std::unique_ptr<PromoService> service_; };
diff --git a/chrome/browser/search/search.cc b/chrome/browser/search/search.cc index cb14223..c3a68e4 100644 --- a/chrome/browser/search/search.cc +++ b/chrome/browser/search/search.cc
@@ -186,7 +186,7 @@ GURL search_provider_url(template_url->new_tab_url_ref().ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(base::string16()), - UIThreadSearchTermsData(profile))); + UIThreadSearchTermsData())); if (!search_provider_url.is_valid()) return NewTabURLDetails(local_url, NEW_TAB_URL_NOT_SET);
diff --git a/chrome/browser/search/search_engine_base_url_tracker_unittest.cc b/chrome/browser/search/search_engine_base_url_tracker_unittest.cc index 004db03..853bd70 100644 --- a/chrome/browser/search/search_engine_base_url_tracker_unittest.cc +++ b/chrome/browser/search/search_engine_base_url_tracker_unittest.cc
@@ -15,8 +15,8 @@ base::MockCallback<SearchEngineBaseURLTracker::BaseURLChangedCallback> callback; SearchEngineBaseURLTracker tracker( - template_url_service_, - std::make_unique<UIThreadSearchTermsData>(profile()), callback.Get()); + template_url_service_, std::make_unique<UIThreadSearchTermsData>(), + callback.Get()); // Changing the search provider should invoke the callback. EXPECT_CALL( @@ -24,37 +24,3 @@ Run(SearchEngineBaseURLTracker::ChangeReason::DEFAULT_SEARCH_PROVIDER)); SetUserSelectedDefaultSearchProvider("https://bar.com/"); } - -TEST_F(SearchEngineBaseURLTrackerTest, DispatchGoogleURLUpdated) { - base::MockCallback<SearchEngineBaseURLTracker::BaseURLChangedCallback> - callback; - SearchEngineBaseURLTracker tracker( - template_url_service_, - std::make_unique<UIThreadSearchTermsData>(profile()), callback.Get()); - - // While Google is the default search provider, changes to the Google base URL - // should invoke the callback. - EXPECT_CALL(callback, - Run(SearchEngineBaseURLTracker::ChangeReason::GOOGLE_BASE_URL)); - NotifyGoogleBaseURLUpdate("https://www.google.es/"); -} - -TEST_F(SearchEngineBaseURLTrackerTest, - DontDispatchGoogleURLUpdatedForNonGoogleSearchProvider) { - base::MockCallback<SearchEngineBaseURLTracker::BaseURLChangedCallback> - callback; - SearchEngineBaseURLTracker tracker( - template_url_service_, - std::make_unique<UIThreadSearchTermsData>(profile()), callback.Get()); - - // Set up a non-Google default search provider. - EXPECT_CALL( - callback, - Run(SearchEngineBaseURLTracker::ChangeReason::DEFAULT_SEARCH_PROVIDER)); - SetUserSelectedDefaultSearchProvider("https://bar.com/"); - testing::Mock::VerifyAndClearExpectations(&callback); - - // Now, a change to the Google base URL should not invoke the callback. - EXPECT_CALL(callback, Run(testing::_)).Times(0); - NotifyGoogleBaseURLUpdate("https://www.google.es/"); -}
diff --git a/chrome/browser/search/search_suggest/search_suggest_loader_impl.cc b/chrome/browser/search/search_suggest/search_suggest_loader_impl.cc index 79017df..1da8911 100644 --- a/chrome/browser/search/search_suggest/search_suggest_loader_impl.cc +++ b/chrome/browser/search/search_suggest/search_suggest_loader_impl.cc
@@ -15,7 +15,6 @@ #include "chrome/browser/search/search_suggest/search_suggest_data.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/webui_url_constants.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "components/variations/net/variations_http_headers.h" #include "content/public/browser/system_connector.h" @@ -202,10 +201,8 @@ SearchSuggestLoaderImpl::SearchSuggestLoaderImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker, const std::string& application_locale) : url_loader_factory_(url_loader_factory), - google_url_tracker_(google_url_tracker), application_locale_(application_locale) {} SearchSuggestLoaderImpl::~SearchSuggestLoaderImpl() = default; @@ -232,7 +229,7 @@ GURL SearchSuggestLoaderImpl::GetApiUrl(const std::string& blocklist) const { GURL google_base_url = google_util::CommandLineGoogleBaseURL(); if (!google_base_url.is_valid()) { - google_base_url = google_url_tracker_->google_url(); + google_base_url = GURL(google_util::kGoogleHomepageURL); } GURL api_url = google_base_url.Resolve(kNewTabSearchSuggestionsApiPath);
diff --git a/chrome/browser/search/search_suggest/search_suggest_loader_impl.h b/chrome/browser/search/search_suggest/search_suggest_loader_impl.h index bbc7e82..a752d7d 100644 --- a/chrome/browser/search/search_suggest/search_suggest_loader_impl.h +++ b/chrome/browser/search/search_suggest/search_suggest_loader_impl.h
@@ -14,8 +14,6 @@ #include "base/optional.h" #include "chrome/browser/search/search_suggest/search_suggest_loader.h" -class GoogleURLTracker; - namespace base { class Value; } @@ -31,7 +29,6 @@ public: SearchSuggestLoaderImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, - GoogleURLTracker* google_url_tracker, const std::string& application_locale); ~SearchSuggestLoaderImpl() override; @@ -54,7 +51,6 @@ void Respond(Status status, const base::Optional<SearchSuggestData>& data); scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; - GoogleURLTracker* google_url_tracker_; const std::string application_locale_; std::vector<SearchSuggestionsCallback> callbacks_;
diff --git a/chrome/browser/search/search_suggest/search_suggest_loader_impl_unittest.cc b/chrome/browser/search/search_suggest/search_suggest_loader_impl_unittest.cc index bc55e75..2371b02 100644 --- a/chrome/browser/search/search_suggest/search_suggest_loader_impl_unittest.cc +++ b/chrome/browser/search/search_suggest/search_suggest_loader_impl_unittest.cc
@@ -14,7 +14,6 @@ #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" #include "chrome/browser/search/search_suggest/search_suggest_data.h" -#include "components/google/core/browser/google_url_tracker.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_service_manager_context.h" #include "net/http/http_request_headers.h" @@ -46,22 +45,6 @@ "<div></div>", "script": "<script></script>","impression_cap_expire_time_ms" : 1, "request_freeze_time_ms": 2,"max_impressions": 3}}})json"; -// Required to instantiate a GoogleUrlTracker in UNIT_TEST_MODE. -class GoogleURLTrackerClientStub : public GoogleURLTrackerClient { - public: - GoogleURLTrackerClientStub() {} - ~GoogleURLTrackerClientStub() override {} - - bool IsBackgroundNetworkingEnabled() override { return true; } - PrefService* GetPrefs() override { return nullptr; } - network::SharedURLLoaderFactory* GetURLLoaderFactory() override { - return nullptr; - } - - private: - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClientStub); -}; - } // namespace ACTION_P(Quit, run_loop) { @@ -76,23 +59,15 @@ explicit SearchSuggestLoaderImplTest(bool account_consistency_mirror_required) : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), - google_url_tracker_( - std::make_unique<GoogleURLTrackerClientStub>(), - GoogleURLTracker::ALWAYS_DOT_COM_MODE, - network::TestNetworkConnectionTracker::GetInstance()), test_shared_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)) {} - ~SearchSuggestLoaderImplTest() override { - static_cast<KeyedService&>(google_url_tracker_).Shutdown(); - } - void SetUp() override { testing::Test::SetUp(); search_suggest_loader_ = std::make_unique<SearchSuggestLoaderImpl>( - test_shared_loader_factory_, &google_url_tracker_, kApplicationLocale); + test_shared_loader_factory_, kApplicationLocale); } void SetUpResponseWithData(const std::string& response) { @@ -129,7 +104,6 @@ data_decoder::TestingJsonParser::ScopedFactoryOverride factory_override_; - GoogleURLTracker google_url_tracker_; network::TestURLLoaderFactory test_url_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;
diff --git a/chrome/browser/search/search_suggest/search_suggest_service_factory.cc b/chrome/browser/search/search_suggest/search_suggest_service_factory.cc index 68e73ec..400ed17 100644 --- a/chrome/browser/search/search_suggest/search_suggest_service_factory.cc +++ b/chrome/browser/search/search_suggest/search_suggest_service_factory.cc
@@ -11,7 +11,6 @@ #include "base/optional.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/ntp_features.h" #include "chrome/browser/search/search_suggest/search_suggest_loader_impl.h" @@ -40,7 +39,6 @@ "SearchSuggestService", BrowserContextDependencyManager::GetInstance()) { DependsOn(CookieSettingsFactory::GetInstance()); - DependsOn(GoogleURLTrackerFactory::GetInstance()); DependsOn(IdentityManagerFactory::GetInstance()); } @@ -51,14 +49,11 @@ Profile* profile = Profile::FromBrowserContext(context); signin::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile); - GoogleURLTracker* google_url_tracker = - GoogleURLTrackerFactory::GetForProfile(profile); auto url_loader_factory = content::BrowserContext::GetDefaultStoragePartition(context) ->GetURLLoaderFactoryForBrowserProcess(); return new SearchSuggestService( profile, identity_manager, std::make_unique<SearchSuggestLoaderImpl>( - url_loader_factory, google_url_tracker, - g_browser_process->GetApplicationLocale())); + url_loader_factory, g_browser_process->GetApplicationLocale())); }
diff --git a/chrome/browser/search_engines/template_url_service_factory.cc b/chrome/browser/search_engines/template_url_service_factory.cc index c137bd1..8903b8c 100644 --- a/chrome/browser/search_engines/template_url_service_factory.cc +++ b/chrome/browser/search_engines/template_url_service_factory.cc
@@ -9,7 +9,6 @@ #include "base/bind.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" @@ -50,15 +49,13 @@ #endif Profile* profile = static_cast<Profile*>(context); return std::make_unique<TemplateURLService>( - profile->GetPrefs(), - std::unique_ptr<SearchTermsData>(new UIThreadSearchTermsData(profile)), + profile->GetPrefs(), std::make_unique<UIThreadSearchTermsData>(), WebDataServiceFactory::GetKeywordWebDataForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), std::unique_ptr<TemplateURLServiceClient>( new ChromeTemplateURLServiceClient( HistoryServiceFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS))), - GoogleURLTrackerFactory::GetForProfile(profile), g_browser_process->rappor_service(), dsp_change_callback); } @@ -66,7 +63,6 @@ : BrowserContextKeyedServiceFactory( "TemplateURLServiceFactory", BrowserContextDependencyManager::GetInstance()) { - DependsOn(GoogleURLTrackerFactory::GetInstance()); DependsOn(HistoryServiceFactory::GetInstance()); DependsOn(WebDataServiceFactory::GetInstance()); }
diff --git a/chrome/browser/search_engines/template_url_service_sync_unittest.cc b/chrome/browser/search_engines/template_url_service_sync_unittest.cc index 5911f29..e3c78b4 100644 --- a/chrome/browser/search_engines/template_url_service_sync_unittest.cc +++ b/chrome/browser/search_engines/template_url_service_sync_unittest.cc
@@ -2099,7 +2099,6 @@ TEST_F(TemplateURLServiceSyncTest, SyncBaseURLs) { // Verify that bringing in a remote TemplateURL that uses Google base URLs // causes it to get a local keyword that matches the local base URL. - test_util_a_->SetGoogleBaseURL(GURL("http://google.com/")); syncer::SyncDataList initial_data; std::unique_ptr<TemplateURL> turl( CreateTestTemplateURL(ASCIIToUTF16("google.co.uk"), @@ -2121,16 +2120,6 @@ ProcessAndExpectNotify(changes, 1); EXPECT_EQ(ASCIIToUTF16("google.com"), synced_turl->keyword()); EXPECT_EQ(0U, processor()->change_list_size()); - - // A local change to the Google base URL should update the keyword and - // generate a sync change. - test_util_a_->SetGoogleBaseURL(GURL("http://google.co.in/")); - EXPECT_EQ(ASCIIToUTF16("google.co.in"), synced_turl->keyword()); - EXPECT_EQ(1U, processor()->change_list_size()); - ASSERT_TRUE(processor()->contains_guid("guid")); - syncer::SyncChange change(processor()->change_for_guid("guid")); - EXPECT_EQ(syncer::SyncChange::ACTION_UPDATE, change.change_type()); - EXPECT_EQ("google.co.in", GetKeyword(change.sync_data())); } TEST_F(TemplateURLServiceSyncTest, MergeInSyncTemplateURL) {
diff --git a/chrome/browser/search_engines/template_url_service_test_util.cc b/chrome/browser/search_engines/template_url_service_test_util.cc index aee657b..4cf7369b 100644 --- a/chrome/browser/search_engines/template_url_service_test_util.cc +++ b/chrome/browser/search_engines/template_url_service_test_util.cc
@@ -59,9 +59,7 @@ DefaultSearchManager::kDefaultSearchProviderDataPrefName); } -TemplateURLServiceTestUtil::TemplateURLServiceTestUtil() - : changed_count_(0), - search_terms_data_(NULL) { +TemplateURLServiceTestUtil::TemplateURLServiceTestUtil() : changed_count_(0) { // Make unique temp directory. EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); profile_.reset(new TestingProfile(temp_dir_.GetPath())); @@ -122,23 +120,21 @@ void TemplateURLServiceTestUtil::ClearModel() { model_->Shutdown(); model_.reset(); - search_terms_data_ = NULL; } void TemplateURLServiceTestUtil::ResetModel(bool verify_load) { if (model_) ClearModel(); - search_terms_data_ = new TestingSearchTermsData("http://www.google.com/"); model_.reset(new TemplateURLService( profile()->GetPrefs(), - std::unique_ptr<SearchTermsData>(search_terms_data_), + std::make_unique<TestingSearchTermsData>("http://www.google.com/"), web_data_service_.get(), std::unique_ptr<TemplateURLServiceClient>( new TestingTemplateURLServiceClient( HistoryServiceFactory::GetForProfileIfExists( profile(), ServiceAccessType::EXPLICIT_ACCESS), &search_term_)), - NULL, NULL, base::Closure())); + nullptr, base::Closure())); model()->AddObserver(this); changed_count_ = 0; if (verify_load) @@ -151,12 +147,6 @@ return search_term; } -void TemplateURLServiceTestUtil::SetGoogleBaseURL(const GURL& base_url) { - DCHECK(base_url.is_valid()); - search_terms_data_->set_google_base_url(base_url.spec()); - model_->GoogleBaseURLChanged(); -} - TemplateURL* TemplateURLServiceTestUtil::AddExtensionControlledTURL( std::unique_ptr<TemplateURL> extension_turl) { TemplateURL* result = model()->Add(std::move(extension_turl));
diff --git a/chrome/browser/search_engines/template_url_service_test_util.h b/chrome/browser/search_engines/template_url_service_test_util.h index 56d7984..8cc6aa662 100644 --- a/chrome/browser/search_engines/template_url_service_test_util.h +++ b/chrome/browser/search_engines/template_url_service_test_util.h
@@ -16,11 +16,9 @@ #include "components/search_engines/template_url_data.h" #include "components/search_engines/template_url_service_observer.h" -class GURL; class KeywordWebDataService; class TemplateURLService; class TestingProfile; -class TestingSearchTermsData; // Sets the managed preferences for the default search provider. // enabled arg enables/disables use of managed engine by DefaultSearchManager. @@ -63,9 +61,6 @@ // TemplateURLService::SetKeywordSearchTermsForURL and clears the search term. base::string16 GetAndClearSearchTerm(); - // Sets the google base url. |base_url| must be valid. - void SetGoogleBaseURL(const GURL& base_url); - // Adds extension controlled TemplateURL to the model and overrides default // search pref in an extension controlled preferences, if extension wants to // be default. @@ -87,7 +82,6 @@ int changed_count_; base::string16 search_term_; scoped_refptr<KeywordWebDataService> web_data_service_; - TestingSearchTermsData* search_terms_data_; std::unique_ptr<TemplateURLService> model_; DISALLOW_COPY_AND_ASSIGN(TemplateURLServiceTestUtil);
diff --git a/chrome/browser/search_engines/template_url_service_unittest.cc b/chrome/browser/search_engines/template_url_service_unittest.cc index 6ebf4d1..aa97df7 100644 --- a/chrome/browser/search_engines/template_url_service_unittest.cc +++ b/chrome/browser/search_engines/template_url_service_unittest.cc
@@ -1107,88 +1107,35 @@ } } -TEST_F(TemplateURLServiceWithoutFallbackTest, ChangeGoogleBaseValue) { +// Historically, {google:baseURL} keywords would change to different +// country-specific Google URLs dynamically. That logic was removed, but test +// that country-specific Google URLs can still be added manually. +TEST_F(TemplateURLServiceWithoutFallbackTest, ManualCountrySpecificGoogleURL) { // NOTE: Do not load the prepopulate data, which also has a {google:baseURL} // keyword in it and would confuse this test. test_util()->ChangeModelToLoadState(); - test_util()->SetGoogleBaseURL(GURL("http://google.com/")); const TemplateURL* t_url = AddKeywordWithDate( "name", "google.com", "{google:baseURL}?q={searchTerms}", "http://sugg1", std::string(), "http://icon1", false, "UTF-8;UTF-16"); - ASSERT_EQ(t_url, model()->GetTemplateURLForHost("google.com")); - EXPECT_EQ("google.com", t_url->url_ref().GetHost(search_terms_data())); + ASSERT_EQ(t_url, model()->GetTemplateURLForHost("www.google.com")); + EXPECT_EQ("www.google.com", t_url->url_ref().GetHost(search_terms_data())); EXPECT_EQ(ASCIIToUTF16("google.com"), t_url->keyword()); - // Change the Google base url. - test_util()->ResetObserverCount(); - test_util()->SetGoogleBaseURL(GURL("http://google.co.uk/")); - VerifyObserverCount(1); - - // Make sure the host->TemplateURL map was updated appropriately. - ASSERT_EQ(t_url, model()->GetTemplateURLForHost("google.co.uk")); - EXPECT_TRUE(model()->GetTemplateURLForHost("google.com") == NULL); - EXPECT_EQ("google.co.uk", t_url->url_ref().GetHost(search_terms_data())); - EXPECT_EQ(ASCIIToUTF16("google.co.uk"), t_url->keyword()); - EXPECT_EQ("http://google.co.uk/?q=x", t_url->url_ref().ReplaceSearchTerms( - TemplateURLRef::SearchTermsArgs(ASCIIToUTF16("x")), search_terms_data())); - - // Now add a manual entry and then change the Google base URL such that the - // autogenerated Google search keyword would conflict. + // Now add a manual entry for a country-specific Google URL. TemplateURL* manual = AddKeywordWithDate( - "manual", "google.de", "http://google.de/search?q={searchTerms}", + "manual", "google.de", "http://www.google.de/search?q={searchTerms}", std::string(), std::string(), std::string(), false); - test_util()->SetGoogleBaseURL(GURL("http://google.de")); - // Verify that the manual entry is untouched, and the autogenerated keyword - // has not changed. + // Verify that the entries do not conflict. + ASSERT_EQ(t_url, + model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.com"))); + EXPECT_EQ("www.google.com", t_url->url_ref().GetHost(search_terms_data())); + EXPECT_EQ(ASCIIToUTF16("google.com"), t_url->keyword()); ASSERT_EQ(manual, model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.de"))); - EXPECT_EQ("google.de", manual->url_ref().GetHost(search_terms_data())); - ASSERT_EQ(t_url, - model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.co.uk"))); - EXPECT_EQ("google.de", t_url->url_ref().GetHost(search_terms_data())); - EXPECT_EQ(ASCIIToUTF16("google.co.uk"), t_url->keyword()); - - // Change the base URL again and verify that the autogenerated keyword follows - // even though it didn't match the base URL, while the manual entry is still - // untouched. - test_util()->SetGoogleBaseURL(GURL("http://google.fr/")); - ASSERT_EQ(manual, model()->GetTemplateURLForHost("google.de")); - EXPECT_EQ("google.de", manual->url_ref().GetHost(search_terms_data())); + EXPECT_EQ("www.google.de", manual->url_ref().GetHost(search_terms_data())); EXPECT_EQ(ASCIIToUTF16("google.de"), manual->keyword()); - ASSERT_EQ(t_url, model()->GetTemplateURLForHost("google.fr")); - EXPECT_TRUE(model()->GetTemplateURLForHost("google.co.uk") == NULL); - EXPECT_EQ("google.fr", t_url->url_ref().GetHost(search_terms_data())); - EXPECT_EQ(ASCIIToUTF16("google.fr"), t_url->keyword()); - - // Now add an OSDD entry and then change the Google base URL such that the - // autogenerated Google search keyword would conflict. - TemplateURL* osdd = AddKeywordWithDate( - "osdd", "google.it", "http://google.it/search?q={searchTerms}", - std::string(), std::string(), std::string(), true); - ASSERT_EQ(osdd, - model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.it"))); - EXPECT_EQ(ASCIIToUTF16("google.it"), osdd->keyword()); - ASSERT_EQ(osdd, model()->GetTemplateURLForHost("google.it")); - EXPECT_EQ("google.it", osdd->url_ref().GetHost(search_terms_data())); - const std::string osdd_guid = osdd->sync_guid(); - ASSERT_EQ(osdd, model()->GetTemplateURLForGUID(osdd_guid)); - test_util()->SetGoogleBaseURL(GURL("http://google.it")); - - // Verify that the osdd entry was removed, and the autogenerated keyword has - // changed. - EXPECT_FALSE(model()->GetTemplateURLForGUID(osdd_guid)); - ASSERT_EQ(t_url, - model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.it"))); - EXPECT_EQ(ASCIIToUTF16("google.it"), t_url->keyword()); - ASSERT_EQ(t_url, model()->GetTemplateURLForHost("google.it")); - EXPECT_EQ("google.it", t_url->url_ref().GetHost(search_terms_data())); - ASSERT_EQ(manual, - model()->GetTemplateURLForKeyword(ASCIIToUTF16("google.de"))); - EXPECT_EQ(ASCIIToUTF16("google.de"), manual->keyword()); - ASSERT_EQ(manual, model()->GetTemplateURLForHost("google.de")); - EXPECT_EQ("google.de", manual->url_ref().GetHost(search_terms_data())); } // Make sure TemplateURLService generates a KEYWORD_GENERATED visit for
diff --git a/chrome/browser/search_engines/ui_thread_search_terms_data.cc b/chrome/browser/search_engines/ui_thread_search_terms_data.cc index 9d081b4..7e40e90 100644 --- a/chrome/browser/search_engines/ui_thread_search_terms_data.cc +++ b/chrome/browser/search_engines/ui_thread_search_terms_data.cc
@@ -9,11 +9,9 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/google/google_brand.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_switches.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" @@ -27,31 +25,19 @@ using content::BrowserThread; -// static -std::string* UIThreadSearchTermsData::google_base_url_ = NULL; - -UIThreadSearchTermsData::UIThreadSearchTermsData(Profile* profile) - : profile_(profile) { +UIThreadSearchTermsData::UIThreadSearchTermsData() { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || - BrowserThread::CurrentlyOn(BrowserThread::UI)); + BrowserThread::CurrentlyOn(BrowserThread::UI)); } std::string UIThreadSearchTermsData::GoogleBaseURLValue() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); - if (google_base_url_) - return *google_base_url_; GURL base_url(google_util::CommandLineGoogleBaseURL()); if (base_url.is_valid()) return base_url.spec(); - if (!profile_) - return SearchTermsData::GoogleBaseURLValue(); - - const GoogleURLTracker* tracker = - GoogleURLTrackerFactory::GetForProfile(profile_); - return tracker ? - tracker->google_url().spec() : GoogleURLTracker::kDefaultGoogleHomepage; + return SearchTermsData::GoogleBaseURLValue(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const { @@ -130,12 +116,6 @@ return version; } -// static -void UIThreadSearchTermsData::SetGoogleBaseURL(const std::string& base_url) { - delete google_base_url_; - google_base_url_ = base_url.empty() ? NULL : new std::string(base_url); -} - size_t UIThreadSearchTermsData::EstimateMemoryUsage() const { return 0; }
diff --git a/chrome/browser/search_engines/ui_thread_search_terms_data.h b/chrome/browser/search_engines/ui_thread_search_terms_data.h index 1797504..85d29f00 100644 --- a/chrome/browser/search_engines/ui_thread_search_terms_data.h +++ b/chrome/browser/search_engines/ui_thread_search_terms_data.h
@@ -12,14 +12,10 @@ #include "base/strings/string16.h" #include "components/search_engines/search_terms_data.h" -class Profile; - // Implementation of SearchTermsData that is only usable on the UI thread. class UIThreadSearchTermsData : public SearchTermsData { public: - // If |profile_| is NULL, the Google base URL accessors will return default - // values, and NTPIsThemedParam() will return an empty string. - explicit UIThreadSearchTermsData(Profile* profile); + UIThreadSearchTermsData(); std::string GoogleBaseURLValue() const override; std::string GetApplicationLocale() const override; @@ -34,18 +30,11 @@ std::string GetMailRUReferralID() const override; #endif - // Used by tests to override the value for the Google base URL. Passing the - // empty string cancels this override. - static void SetGoogleBaseURL(const std::string& base_url); - // Estimates dynamic memory usage. // See base/trace_event/memory_usage_estimator.h for more info. size_t EstimateMemoryUsage() const override; private: - static std::string* google_base_url_; - Profile* profile_; - DISALLOW_COPY_AND_ASSIGN(UIThreadSearchTermsData); };
diff --git a/chrome/browser/sharing/click_to_call/click_to_call_browsertest.cc b/chrome/browser/sharing/click_to_call/click_to_call_browsertest.cc new file mode 100644 index 0000000..63f3e49 --- /dev/null +++ b/chrome/browser/sharing/click_to_call/click_to_call_browsertest.cc
@@ -0,0 +1,182 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> +#include <string> + +#include "base/bind.h" +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/bind_test_util.h" +#include "base/test/scoped_feature_list.h" +#include "build/build_config.h" +#include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/gcm/gcm_profile_service_factory.h" +#include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" +#include "chrome/browser/sharing/click_to_call/feature.h" +#include "chrome/browser/sharing/features.h" +#include "chrome/browser/sharing/sharing_device_info.h" +#include "chrome/browser/sharing/sharing_device_registration_result.h" +#include "chrome/browser/sharing/sharing_service.h" +#include "chrome/browser/sharing/sharing_service_factory.h" +#include "chrome/browser/sharing/sharing_sync_preference.h" +#include "chrome/browser/sync/test/integration/sync_test.h" +#include "chrome/browser/ui/browser.h" +#include "components/gcm_driver/fake_gcm_profile_service.h" +#include "components/sync/driver/profile_sync_service.h" +#include "url/gurl.h" + +namespace { +const char kTelUrl[] = "tel:+9876543210"; +} // namespace + +class ClickToCallBrowserTest : public SyncTest { + public: + ClickToCallBrowserTest() + : SyncTest(TWO_CLIENT), + scoped_testing_factory_installer_( + base::BindRepeating(&gcm::FakeGCMProfileService::Build)) {} + + ~ClickToCallBrowserTest() override {} + + void SetUpOnMainThread() override { + SyncTest::SetUpOnMainThread(); + + scoped_feature_list_.InitWithFeatures( + {kClickToCallUI, kSharingDeviceRegistration}, {}); + + ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; + + std::unique_ptr<content::WebContents> web_contents_ptr = + content::WebContents::Create( + content::WebContents::CreateParams(GetProfile(0))); + web_contents_ = web_contents_ptr.get(); + Browser* browser = AddBrowser(0); + browser->tab_strip_model()->AppendWebContents(std::move(web_contents_ptr), + true); + + gcm_service_ = static_cast<gcm::FakeGCMProfileService*>( + gcm::GCMProfileServiceFactory::GetForProfile(GetProfile(0))); + gcm_service_->set_collect(true); + } + + void SetUpDevices(int count) { + for (int i = 0; i < count; i++) { + SharingService* service = + SharingServiceFactory::GetForBrowserContext(GetProfile(i)); + + base::RunLoop run_loop; + service->RegisterDeviceInTesting( + std::string("TEST"), + static_cast<int>(SharingDeviceCapability::kTelephony), + base::BindLambdaForTesting([&](SharingDeviceRegistrationResult r) { + ASSERT_EQ(SharingDeviceRegistrationResult::kSuccess, r); + run_loop.Quit(); + })); + run_loop.Run(); + } + } + + std::unique_ptr<TestRenderViewContextMenu> InitRightClickMenu( + const GURL& url, + const base::string16& link_text) { + content::ContextMenuParams params; + params.media_type = blink::WebContextMenuData::MediaType::kMediaTypeNone; + params.unfiltered_link_url = url; + params.link_url = url; + params.src_url = url; + params.link_text = link_text; + params.page_url = web_contents_->GetVisibleURL(); + params.source_type = ui::MenuSourceType::MENU_SOURCE_MOUSE; +#if defined(OS_MACOSX) + params.writing_direction_default = 0; + params.writing_direction_left_to_right = 0; + params.writing_direction_right_to_left = 0; +#endif + auto menu = std::make_unique<TestRenderViewContextMenu>( + web_contents_->GetMainFrame(), params); + menu->Init(); + return menu; + } + + void GetDeviceFCMToken(SharingService* sharing_service, + const std::string& guid, + std::string* fcm_token) const { + auto devices = sharing_service->GetSyncPreferences()->GetSyncedDevices(); + auto it = devices.find(guid); + ASSERT_NE(devices.end(), it); + *fcm_token = it->second.fcm_token; + } + + gcm::FakeGCMProfileService* GetGCMService() const { return gcm_service_; } + + private: + gcm::GCMProfileServiceFactory::ScopedTestingFactoryInstaller + scoped_testing_factory_installer_; + base::test::ScopedFeatureList scoped_feature_list_; + gcm::FakeGCMProfileService* gcm_service_; + content::WebContents* web_contents_; + DISALLOW_COPY_AND_ASSIGN(ClickToCallBrowserTest); +}; + +// TODO(himanshujaju): Add UI checks. Modularize common functions. +IN_PROC_BROWSER_TEST_F(ClickToCallBrowserTest, + ContextMenu_SingleDeviceAvailable) { + SetUpDevices(/*count=*/1); + AwaitQuiescence(); + + SharingService* sharing_service = + SharingServiceFactory::GetForBrowserContext(GetProfile(0)); + auto devices = sharing_service->GetDeviceCandidates( + static_cast<int>(SharingDeviceCapability::kTelephony)); + + std::unique_ptr<TestRenderViewContextMenu> menu = + InitRightClickMenu(GURL(kTelUrl), base::ASCIIToUTF16("Google")); + + // Check click to call items in context menu + ASSERT_TRUE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE)); + EXPECT_FALSE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES)); + + menu->ExecuteCommand(IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE, + 0); + + // Check SharingMessage and Receiver id + std::string fcm_token; + GetDeviceFCMToken(sharing_service, devices[0].guid(), &fcm_token); + EXPECT_EQ(fcm_token, GetGCMService()->last_receiver_id()); + chrome_browser_sharing::SharingMessage sharing_message; + sharing_message.ParseFromString( + GetGCMService()->last_web_push_message().payload); + ASSERT_TRUE(sharing_message.has_click_to_call_message()); + EXPECT_EQ(GURL(kTelUrl).GetContent(), + sharing_message.click_to_call_message().phone_number()); +} + +IN_PROC_BROWSER_TEST_F(ClickToCallBrowserTest, ContextMenu_NoDevicesAvailable) { + AwaitQuiescence(); + + std::unique_ptr<TestRenderViewContextMenu> menu = + InitRightClickMenu(GURL(kTelUrl), base::ASCIIToUTF16("Google")); + EXPECT_FALSE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE)); + EXPECT_FALSE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES)); +} + +IN_PROC_BROWSER_TEST_F(ClickToCallBrowserTest, + ContextMenu_DevicesAvailable_SyncTurnedOff) { + SetUpDevices(/*count=*/1); + AwaitQuiescence(); + GetSyncService(0)->GetUserSettings()->SetSyncRequested(false); + + std::unique_ptr<TestRenderViewContextMenu> menu = + InitRightClickMenu(GURL(kTelUrl), base::ASCIIToUTF16("Google")); + EXPECT_FALSE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_SINGLE_DEVICE)); + EXPECT_FALSE(menu->IsItemPresent( + IDC_CONTENT_CONTEXT_SHARING_CLICK_TO_CALL_MULTIPLE_DEVICES)); +}
diff --git a/chrome/browser/sharing/sharing_device_registration.cc b/chrome/browser/sharing/sharing_device_registration.cc index 4e7d35080..742bd145 100644 --- a/chrome/browser/sharing/sharing_device_registration.cc +++ b/chrome/browser/sharing/sharing_device_registration.cc
@@ -188,6 +188,10 @@ } int SharingDeviceRegistration::GetDeviceCapabilities() const { + // Used in tests + if (device_capabilities_testing_value_) + return device_capabilities_testing_value_.value(); + int device_capabilities = static_cast<int>(SharingDeviceCapability::kNone); if (IsTelephonySupported()) { device_capabilities |= @@ -206,3 +210,8 @@ return false; } + +void SharingDeviceRegistration::SetDeviceCapabilityForTesting( + int device_capabilities) { + device_capabilities_testing_value_ = device_capabilities; +}
diff --git a/chrome/browser/sharing/sharing_device_registration.h b/chrome/browser/sharing/sharing_device_registration.h index 9e514bc..0b81920e 100644 --- a/chrome/browser/sharing/sharing_device_registration.h +++ b/chrome/browser/sharing/sharing_device_registration.h
@@ -47,6 +47,9 @@ // Un-registers device with sharing sync preferences. virtual void UnregisterDevice(RegistrationCallback callback); + // For testing + void SetDeviceCapabilityForTesting(int device_capabilities); + private: FRIEND_TEST_ALL_PREFIXES(SharingDeviceRegistrationTest, RegisterDeviceTest_Success); @@ -91,6 +94,7 @@ instance_id::InstanceIDDriver* instance_id_driver_; VapidKeyManager* vapid_key_manager_; syncer::LocalDeviceInfoProvider* local_device_info_provider_; + base::Optional<int> device_capabilities_testing_value_; base::WeakPtrFactory<SharingDeviceRegistration> weak_ptr_factory_{this};
diff --git a/chrome/browser/sharing/sharing_service.cc b/chrome/browser/sharing/sharing_service.cc index 4dfe5893..22abed13 100644 --- a/chrome/browser/sharing/sharing_service.cc +++ b/chrome/browser/sharing/sharing_service.cc
@@ -127,8 +127,6 @@ std::unordered_set<std::string> device_names; std::vector<SharingDeviceInfo> device_candidates; - const syncer::DeviceInfo* local_device_info = - local_device_info_provider_->GetLocalDeviceInfo(); for (const auto& device : all_devices) { // If the current device is considered expired for our purposes, stop here // since the next devices in the vector are at least as expired than this @@ -136,8 +134,7 @@ if (device->last_updated_timestamp() < min_updated_time) break; - if (local_device_info && - (local_device_info->client_name() == device->client_name())) { + if (GetDeviceName() == device->client_name()) { continue; } @@ -268,6 +265,15 @@ &SharingService::OnDeviceRegistered, weak_ptr_factory_.GetWeakPtr())); } +void SharingService::RegisterDeviceInTesting( + std::string device_name, + int capabilities, + SharingDeviceRegistration::RegistrationCallback callback) { + local_device_name_for_tests_ = std::move(device_name); + sharing_device_registration_->SetDeviceCapabilityForTesting(capabilities); + sharing_device_registration_->RegisterDevice(std::move(callback)); +} + void SharingService::UnregisterDevice() { sharing_device_registration_->UnregisterDevice(base::BindOnce( &SharingService::OnDeviceUnregistered, weak_ptr_factory_.GetWeakPtr())); @@ -358,6 +364,10 @@ sync_service_->GetActiveDataTypes().Has(syncer::PREFERENCES); } +SharingSyncPreference* SharingService::GetSyncPreferences() const { + return sync_prefs_.get(); +} + bool SharingService::IsSyncDisabled() const { return sync_service_ && (sync_service_->GetTransportState() == @@ -366,3 +376,15 @@ syncer::SyncService::TransportState::ACTIVE && !sync_service_->GetActiveDataTypes().Has(syncer::PREFERENCES))); } + +base::Optional<std::string> SharingService::GetDeviceName() const { + if (local_device_name_for_tests_) + return local_device_name_for_tests_; + + const syncer::DeviceInfo* local_device_info = + local_device_info_provider_->GetLocalDeviceInfo(); + if (local_device_info) + return local_device_info->client_name(); + else + return base::nullopt; +}
diff --git a/chrome/browser/sharing/sharing_service.h b/chrome/browser/sharing/sharing_service.h index fa0811b..145eb0e 100644 --- a/chrome/browser/sharing/sharing_service.h +++ b/chrome/browser/sharing/sharing_service.h
@@ -98,6 +98,14 @@ // Returns the current state of SharingService. virtual State GetState() const; + // For testing + void RegisterDeviceInTesting( + std::string device_name, + int capabilities, + SharingDeviceRegistration::RegistrationCallback callback); + + SharingSyncPreference* GetSyncPreferences() const; + private: // Overrides for syncer::SyncServiceObserver. void OnSyncShutdown(syncer::SyncService* sync) override; @@ -107,6 +115,7 @@ void OnAckReceived(const std::string& message_id) override; void RegisterDevice(); + void UnregisterDevice(); void OnDeviceRegistered(SharingDeviceRegistrationResult result); void OnDeviceUnregistered(SharingDeviceRegistrationResult result); @@ -122,6 +131,10 @@ // in transitioning state. bool IsSyncDisabled() const; + // Returns |local_device_name_for_tests_| if set, otherwise returns the actual + // device name from |local_device_info_provider_|. + base::Optional<std::string> GetDeviceName() const; + std::unique_ptr<SharingSyncPreference> sync_prefs_; std::unique_ptr<VapidKeyManager> vapid_key_manager_; std::unique_ptr<SharingDeviceRegistration> sharing_device_registration_; @@ -134,6 +147,7 @@ PingMessageHandler ping_message_handler_; net::BackoffEntry backoff_entry_; State state_; + base::Optional<std::string> local_device_name_for_tests_; // Map of random GUID to SendMessageCallback. std::map<std::string, SendMessageCallback> send_message_callbacks_;
diff --git a/chrome/browser/signin/signin_ui_util_unittest.cc b/chrome/browser/signin/signin_ui_util_unittest.cc index 1b6de2e..d45ea4d 100644 --- a/chrome/browser/signin/signin_ui_util_unittest.cc +++ b/chrome/browser/signin/signin_ui_util_unittest.cc
@@ -14,7 +14,7 @@ #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/browser/signin/signin_promo.h" #include "chrome/test/base/browser_with_test_window_test.h" -#include "components/google/core/browser/google_url_tracker.h" +#include "components/google/core/common/google_util.h" #include "components/signin/public/base/signin_buildflags.h" #include "components/signin/public/identity_manager/account_info.h" #include "components/signin/public/identity_manager/accounts_mutator.h" @@ -364,8 +364,8 @@ TabStripModel* tab_strip = browser()->tab_strip_model(); content::WebContents* active_contents = tab_strip->GetActiveWebContents(); ASSERT_TRUE(active_contents); - EXPECT_EQ(signin::GetChromeSyncURLForDice( - kMainEmail, GoogleURLTracker::kDefaultGoogleHomepage), + EXPECT_EQ(signin::GetChromeSyncURLForDice(kMainEmail, + google_util::kGoogleHomepageURL), active_contents->GetVisibleURL()); tab_strip->CloseWebContentsAt( tab_strip->GetIndexOfWebContents(active_contents), @@ -397,9 +397,9 @@ content::WebContents* active_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(active_contents); - EXPECT_EQ(signin::GetChromeSyncURLForDice( - "", GoogleURLTracker::kDefaultGoogleHomepage), - active_contents->GetVisibleURL()); + EXPECT_EQ( + signin::GetChromeSyncURLForDice("", google_util::kGoogleHomepageURL), + active_contents->GetVisibleURL()); } TEST_F(DiceSigninUiUtilTest, EnableSyncForNewAccountWithNoTabWithExisting) { @@ -452,9 +452,9 @@ content::WebContents* active_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(active_contents); - EXPECT_EQ(signin::GetChromeSyncURLForDice( - "", GoogleURLTracker::kDefaultGoogleHomepage), - active_contents->GetVisibleURL()); + EXPECT_EQ( + signin::GetChromeSyncURLForDice("", google_util::kGoogleHomepageURL), + active_contents->GetVisibleURL()); } TEST_F(DiceSigninUiUtilTest, GetAccountsForDicePromos) {
diff --git a/chrome/browser/supervised_user/supervised_user_service.cc b/chrome/browser/supervised_user/supervised_user_service.cc index 5b54bc9..bbc12e9 100644 --- a/chrome/browser/supervised_user/supervised_user_service.cc +++ b/chrome/browser/supervised_user/supervised_user_service.cc
@@ -101,18 +101,6 @@ prefs::kSupervisedUserSecondCustodianProfileURL, }; -void SetupRestrictedCrosSettingForChildUser( - std::map<std::string, base::Value>* restricted_prefs) { -#if defined(OS_CHROMEOS) - (*restricted_prefs)[std::string(chromeos::kAccountsPrefAllowGuest)] = - base::Value(false); - (*restricted_prefs)[std::string( - chromeos::kAccountsPrefShowUserNamesOnSignIn)] = base::Value(false); - (*restricted_prefs)[std::string(chromeos::kAccountsPrefAllowNewUser)] = - base::Value(false); -#endif // OS_CHROMEOS -} - void CreateURLAccessRequest(const GURL& url, PermissionRequestCreator* creator, SupervisedUserService::SuccessCallback callback) { @@ -186,25 +174,6 @@ weak_ptr_factory_.GetWeakPtr())); SetActive(ProfileIsSupervised()); - SetupRestrictedCrosSettingForChildUser(&child_user_restricted_cros_settings_); -} - -// TODO(crbug/945934) Move the following 2 methods to -// SupervisedUserCrosSettingProvider. -bool SupervisedUserService::IsRestrictedCrosSettingForChildUser( - const std::string& pref_name) const { - if (!profile_->IsChild()) - return false; - return base::Contains(child_user_restricted_cros_settings_, pref_name); -} - -const base::Value* -SupervisedUserService::GetRestrictedCrosSettingValueForChildUser( - const std::string& pref_name) const { - auto value = child_user_restricted_cros_settings_.find(pref_name); - if (value == child_user_restricted_cros_settings_.end()) - return nullptr; - return &(value->second); } void SupervisedUserService::SetDelegate(Delegate* delegate) {
diff --git a/chrome/browser/supervised_user/supervised_user_service.h b/chrome/browser/supervised_user/supervised_user_service.h index d517ff1..72dc4d2 100644 --- a/chrome/browser/supervised_user/supervised_user_service.h +++ b/chrome/browser/supervised_user/supervised_user_service.h
@@ -101,14 +101,6 @@ return whitelists_; } - // Returns true if the preference value is pre-defined and is controlled by - // neither the supervised user nor the supervised user's custodians. - bool IsRestrictedCrosSettingForChildUser(const std::string& name) const; - - // Returns the value of the restricted preference. - const base::Value* GetRestrictedCrosSettingValueForChildUser( - const std::string& name) const; - // Whether the user can request to get access to blocked URLs or to new // extensions. bool AccessRequestsEnabled(); @@ -344,9 +336,6 @@ // It is only relevant for SU-initiated installs. std::map<std::string, base::Version> approved_extensions_map_; - // Stores the restricted preference values for child users. - std::map<std::string, base::Value> child_user_restricted_cros_settings_; - enum class BlacklistLoadState { NOT_LOADED, LOAD_STARTED,
diff --git a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc index 8f99dc8c..372e2464 100644 --- a/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_sessions_sync_test.cc
@@ -480,14 +480,9 @@ WaitForURLOnServer(fragment_url); } -// Flakily fails on mac-rel. http://crbug.com/972871 -#if defined(OS_MACOSX) -#define MAYBE_NavigationChainForwardBack DISABLED_NavigationChainForwardBack -#else -#define MAYBE_NavigationChainForwardBack NavigationChainForwardBack -#endif +// Flakily fails on mac/linux/win. http://crbug.com/972871 IN_PROC_BROWSER_TEST_F(SingleClientSessionsSyncTest, - MAYBE_NavigationChainForwardBack) { + DISABLED_NavigationChainForwardBack) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(CheckInitialState(0));
diff --git a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc index 860657af..5885470 100644 --- a/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_standalone_transport_sync_test.cc
@@ -2,14 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/files/file_util.h" #include "base/macros.h" +#include "base/path_service.h" #include "base/test/scoped_feature_list.h" +#include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/single_client_status_change_checker.h" #include "chrome/browser/sync/test/integration/sync_test.h" +#include "chrome/common/chrome_paths.h" #include "components/sync/base/model_type.h" #include "components/sync/driver/profile_sync_service.h" #include "components/sync/driver/sync_driver_switches.h" @@ -25,6 +29,12 @@ return allowed_types; } +base::FilePath GetTestFilePathForCacheGuid() { + base::FilePath user_data_path; + base::PathService::Get(chrome::DIR_USER_DATA, &user_data_path); + return user_data_path.AppendASCII("SyncTestTmpCacheGuid"); +} + class SyncDisabledByUserChecker : public SingleClientStatusChangeChecker { public: explicit SyncDisabledByUserChecker(syncer::ProfileSyncService* service) @@ -42,7 +52,10 @@ class SingleClientStandaloneTransportSyncTest : public SyncTest { public: - SingleClientStandaloneTransportSyncTest() : SyncTest(SINGLE_CLIENT) {} + SingleClientStandaloneTransportSyncTest() : SyncTest(SINGLE_CLIENT) { + DisableVerifier(); + } + ~SingleClientStandaloneTransportSyncTest() override {} private: @@ -209,4 +222,64 @@ #endif // defined(OS_CHROMEOS) } +// Regression test for crbug.com/955989 that verifies the cache GUID is not +// reset upon restart of the browser, in standalone transport mode. +IN_PROC_BROWSER_TEST_F(SingleClientStandaloneTransportSyncTest, + PRE_ReusesSameCacheGuid) { + ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; + ASSERT_TRUE(GetClient(0)->SignInPrimaryAccount()); + ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive()); + + ASSERT_EQ(syncer::SyncService::TransportState::ACTIVE, + GetSyncService(0)->GetTransportState()); + + // On platforms where Sync starts automatically (in practice, Android and + // ChromeOS), IsFirstSetupComplete gets set automatically, and so the full + // Sync feature will start upon sign-in to a primary account. +#if !defined(OS_CHROMEOS) + ASSERT_FALSE(GetSyncService(0)->GetUserSettings()->IsFirstSetupComplete()); + ASSERT_FALSE(GetSyncService(0)->IsSyncFeatureEnabled()); +#endif // !defined(OS_CHROMEOS) + + syncer::SyncPrefs prefs(GetProfile(0)->GetPrefs()); + const std::string cache_guid = prefs.GetCacheGuid(); + ASSERT_FALSE(cache_guid.empty()); + + // Save the cache GUID to file to remember after restart, for test + // verification purposes only. + base::ScopedAllowBlockingForTesting allow_blocking; + ASSERT_NE(-1, base::WriteFile(GetTestFilePathForCacheGuid(), + cache_guid.c_str(), cache_guid.size())); +} + +IN_PROC_BROWSER_TEST_F(SingleClientStandaloneTransportSyncTest, + ReusesSameCacheGuid) { + ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; + ASSERT_FALSE(GetSyncService(0)->HasDisableReason( + syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN)); + ASSERT_TRUE(GetClient(0)->AwaitSyncTransportActive()); + + ASSERT_EQ(syncer::SyncService::TransportState::ACTIVE, + GetSyncService(0)->GetTransportState()); + + // On platforms where Sync starts automatically (in practice, Android and + // ChromeOS), IsFirstSetupComplete gets set automatically, and so the full + // Sync feature will start upon sign-in to a primary account. +#if !defined(OS_CHROMEOS) + ASSERT_FALSE(GetSyncService(0)->GetUserSettings()->IsFirstSetupComplete()); + ASSERT_FALSE(GetSyncService(0)->IsSyncFeatureEnabled()); +#endif // !defined(OS_CHROMEOS) + + syncer::SyncPrefs prefs(GetProfile(0)->GetPrefs()); + ASSERT_FALSE(prefs.GetCacheGuid().empty()); + + std::string old_cache_guid; + base::ScopedAllowBlockingForTesting allow_blocking; + ASSERT_TRUE( + base::ReadFileToString(GetTestFilePathForCacheGuid(), &old_cache_guid)); + ASSERT_FALSE(old_cache_guid.empty()); + + EXPECT_EQ(old_cache_guid, prefs.GetCacheGuid()); +} + } // namespace
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index 53a59d1c..cdddf24 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -47,7 +47,6 @@ #include "chrome/test/base/search_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "components/bookmarks/test/bookmark_test_helpers.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/impl/profile_identity_provider.h" #include "components/invalidation/impl/profile_invalidation_provider.h" @@ -918,8 +917,6 @@ test_url_loader_factory_.AddResponse( GaiaUrls::GetInstance()->get_user_info_url().spec(), "email=user@gmail.com\ndisplayEmail=user@gmail.com"); - test_url_loader_factory_.AddResponse(GoogleURLTracker::kSearchDomainCheckURL, - ".google.com"); test_url_loader_factory_.AddResponse( GaiaUrls::GetInstance()->oauth2_token_url().spec(), R"({
diff --git a/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc b/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc index 8d49887..a41614d 100644 --- a/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc
@@ -44,9 +44,7 @@ DISALLOW_COPY_AND_ASSIGN(TwoClientPreferencesSyncTest); }; -// TODO(crbug.com/988404): Enable once not flaky anymore. -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, - E2E_ENABLED(DISABLED_Sanity)) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, E2E_ENABLED(Sanity)) { DisableVerifier(); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; // Wait until sync settles before we override the prefs below. @@ -71,8 +69,8 @@ "Sync.ModelTypeEntityChange3.PREFERENCE", /*REMOTE_NON_INITIAL_UPDATE=*/4)); - EXPECT_EQ( - 1U, histogram_tester + EXPECT_NE( + 0U, histogram_tester .GetAllSamples( "Sync.NonReflectionUpdateFreshnessPossiblySkewed2.PREFERENCE") .size());
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 930af45e..c0417fa 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -445,7 +445,7 @@ "//components/feedback", "//components/flags_ui", "//components/gcm_driver", - "//components/google/core/browser", + "//components/google/core/common", "//components/heap_profiling", "//components/history/content/browser", "//components/history/core/browser",
diff --git a/chrome/browser/ui/android/overlay/overlay_window_android.cc b/chrome/browser/ui/android/overlay/overlay_window_android.cc index 5ce88e7..4251640 100644 --- a/chrome/browser/ui/android/overlay/overlay_window_android.cc +++ b/chrome/browser/ui/android/overlay/overlay_window_android.cc
@@ -7,6 +7,7 @@ #include "base/android/jni_android.h" #include "base/memory/ptr_util.h" #include "chrome/android/chrome_jni_headers/PictureInPictureActivity_jni.h" +#include "chrome/browser/android/tab_android.h" #include "content/public/browser/overlay_window.h" #include "content/public/browser/picture_in_picture_window_controller.h" #include "ui/views/widget/widget.h" @@ -21,8 +22,10 @@ content::PictureInPictureWindowController* controller) : controller_(controller) { JNIEnv* env = base::android::AttachCurrentThread(); - Java_PictureInPictureActivity_createActivity(env, - reinterpret_cast<long>(this)); + Java_PictureInPictureActivity_createActivity( + env, reinterpret_cast<long>(this), + TabAndroid::FromWebContents(controller_->GetInitiatorWebContents()) + ->GetJavaObject()); } OverlayWindowAndroid::~OverlayWindowAndroid() { @@ -33,12 +36,25 @@ void OverlayWindowAndroid::OnActivityStart( JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj) { + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& jwindow_android) { java_ref_ = JavaObjectWeakGlobalRef(env, obj); + window_android_ = ui::WindowAndroid::FromJavaWindowAndroid(jwindow_android); + window_android_->AddObserver(this); } -void OverlayWindowAndroid::OnActivityDestroy(JNIEnv* env) { +void OverlayWindowAndroid::OnActivityStopped() { + Destroy(nullptr); +} + +void OverlayWindowAndroid::Destroy(JNIEnv* env) { java_ref_.reset(); + + if (window_android_) { + window_android_->RemoveObserver(this); + window_android_ = nullptr; + } + controller_->CloseAndFocusInitiator(); controller_->OnWindowDestroyed(); } @@ -47,6 +63,9 @@ if (java_ref_.is_uninitialized()) return; + DCHECK(window_android_); + window_android_->RemoveObserver(this); + window_android_ = nullptr; JNIEnv* env = base::android::AttachCurrentThread(); Java_PictureInPictureActivity_close(env, java_ref_.get(env)); controller_->OnWindowDestroyed();
diff --git a/chrome/browser/ui/android/overlay/overlay_window_android.h b/chrome/browser/ui/android/overlay/overlay_window_android.h index 1cbb99f1..c8cf8a8 100644 --- a/chrome/browser/ui/android/overlay/overlay_window_android.h +++ b/chrome/browser/ui/android/overlay/overlay_window_android.h
@@ -8,26 +8,42 @@ #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "content/public/browser/overlay_window.h" +#include "ui/android/window_android.h" +#include "ui/android/window_android_observer.h" #include "ui/gfx/geometry/size.h" #include "ui/views/widget/widget.h" -class OverlayWindowAndroid : public content::OverlayWindow { +class OverlayWindowAndroid : public content::OverlayWindow, + public ui::WindowAndroidObserver { public: explicit OverlayWindowAndroid( content::PictureInPictureWindowController* controller); ~OverlayWindowAndroid() override; - void OnActivityStart(JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj); - void OnActivityDestroy(JNIEnv* env); + void OnActivityStart( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& jwindow_android); + void Destroy(JNIEnv* env); + // ui::WindowAndroidObserver implementation. + void OnCompositingDidCommit() override {} + void OnRootWindowVisibilityChanged(bool visible) override {} + void OnAttachCompositor() override {} + void OnDetachCompositor() override {} + void OnAnimate(base::TimeTicks frame_begin_time) override {} + void OnActivityStopped() override; + void OnActivityStarted() override {} + void OnCursorVisibilityChanged(bool visible) override {} + void OnFallbackCursorModeToggled(bool is_on) override {} + + // OverlayWindow implementation. bool IsActive() override; void Close() override; void ShowInactive() override {} void Hide() override; bool IsVisible() override; bool IsAlwaysOnTop() override; - // Retrieves the window's current bounds, including its window. gfx::Rect GetBounds() override; void UpdateVideoSize(const gfx::Size& natural_size) override {} void SetPlaybackState(PlaybackState playback_state) override {} @@ -42,6 +58,7 @@ private: // A weak reference to Java PictureInPictureActivity object. JavaObjectWeakGlobalRef java_ref_; + ui::WindowAndroid* window_android_; content::PictureInPictureWindowController* controller_; };
diff --git a/chrome/browser/ui/app_list/search/arc/arc_app_reinstall_app_result.cc b/chrome/browser/ui/app_list/search/arc/arc_app_reinstall_app_result.cc index 2c1d6b4..1f6691cd 100644 --- a/chrome/browser/ui/app_list/search/arc/arc_app_reinstall_app_result.cc +++ b/chrome/browser/ui/app_list/search/arc/arc_app_reinstall_app_result.cc
@@ -33,6 +33,8 @@ SetResultType(ash::SearchResultType::kPlayStoreReinstallApp); SetTitle(base::UTF8ToUTF16(mojom_data->title)); SetDisplayType(ash::SearchResultDisplayType::kRecommendation); + SetDisplayLocation(ash::SearchResultDisplayLocation::kTileListContainer); + SetDisplayIndex(ash::SearchResultDisplayIndex::kSixthIndex); set_relevance(kAppReinstallRelevance); SetNotifyVisibilityChange(true); SetIcon(skia_icon);
diff --git a/chrome/browser/ui/ash/accelerator_commands_browsertest.cc b/chrome/browser/ui/ash/accelerator_commands_browsertest.cc index 99048491..adba912 100644 --- a/chrome/browser/ui/ash/accelerator_commands_browsertest.cc +++ b/chrome/browser/ui/ash/accelerator_commands_browsertest.cc
@@ -157,7 +157,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; views::Widget misc_widget; widget = &misc_widget; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); window = widget->GetNativeWindow();
diff --git a/chrome/browser/ui/ash/accessibility/ax_tree_source_aura_unittest.cc b/chrome/browser/ui/ash/accessibility/ax_tree_source_aura_unittest.cc index 6e99dd8..d996ec13 100644 --- a/chrome/browser/ui/ash/accessibility/ax_tree_source_aura_unittest.cc +++ b/chrome/browser/ui/ash/accessibility/ax_tree_source_aura_unittest.cc
@@ -62,7 +62,7 @@ widget_ = new Widget(); Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.context = GetContext(); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); content_ = new View(); widget_->SetContentsView(content_);
diff --git a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc index c364c16..17400e8 100644 --- a/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc +++ b/chrome/browser/ui/ash/launcher/chrome_launcher_controller_unittest.cc
@@ -876,7 +876,7 @@ params.bounds = gfx::Rect(5, 5, 20, 20); params.context = ash_test_helper()->CurrentContext(); views::Widget* widget = new views::Widget(); - widget->Init(params); + widget->Init(std::move(params)); // Set ARC id before showing the window to be recognized in // ArcAppWindowLauncherController. exo::SetShellApplicationId(widget->GetNativeWindow(), window_app_id); @@ -923,7 +923,7 @@ params.context = GetContext(); params.bounds = gfx::Rect(5, 5, 20, 20); views::Widget* widget = new views::Widget(); - widget->Init(params); + widget->Init(std::move(params)); aura::Window* window = widget->GetNativeWindow(); const ash::ShelfID shelf_id(app_id); @@ -2524,7 +2524,7 @@ EXPECT_EQ("Chrome, App1, Fake App 1, App2, Fake App 0", GetPinnedAppStatus()); } -TEST_F(ChromeLauncherControllerWithArcTest, ArcCustomAppIcon) { +TEST_F(ChromeLauncherControllerWithArcTest, DISABLED_ArcCustomAppIcon) { InitLauncherController(); // Wait until other apps are updated to avoid race condition while accessing
diff --git a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc index 28335b4..43d10ded 100644 --- a/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc +++ b/chrome/browser/ui/ash/launcher/launcher_context_menu_unittest.cc
@@ -101,7 +101,7 @@ views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); views::Widget* widget = new views::Widget(); params.context = CurrentContext(); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->Activate(); exo::SetShellApplicationId(widget->GetNativeWindow(), window_app_id);
diff --git a/chrome/browser/ui/ash/network/enrollment_dialog_view.cc b/chrome/browser/ui/ash/network/enrollment_dialog_view.cc index 4e54afb..f362917 100644 --- a/chrome/browser/ui/ash/network/enrollment_dialog_view.cc +++ b/chrome/browser/ui/ash/network/enrollment_dialog_view.cc
@@ -114,7 +114,7 @@ ash_util::SetupWidgetInitParamsForContainer( ¶ms, ash_util::GetSystemModalDialogContainerId()); views::Widget* widget = new views::Widget; // Owned by native widget. - widget->Init(params); + widget->Init(std::move(params)); dialog_view->InitDialog(); widget->Show(); }
diff --git a/chrome/browser/ui/aura/accessibility/automation_manager_aura_browsertest.cc b/chrome/browser/ui/aura/accessibility/automation_manager_aura_browsertest.cc index d89fbe9..98c6a24 100644 --- a/chrome/browser/ui/aura/accessibility/automation_manager_aura_browsertest.cc +++ b/chrome/browser/ui/aura/accessibility/automation_manager_aura_browsertest.cc
@@ -166,7 +166,7 @@ views::Widget* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.bounds = {0, 0, 200, 200}; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->Activate();
diff --git a/chrome/browser/ui/browser_instant_controller.cc b/chrome/browser/ui/browser_instant_controller.cc index 53b13b6f..cae5ba4 100644 --- a/chrome/browser/ui/browser_instant_controller.cc +++ b/chrome/browser/ui/browser_instant_controller.cc
@@ -82,8 +82,7 @@ if (template_url_service) { search_engine_base_url_tracker_ = std::make_unique<SearchEngineBaseURLTracker>( - template_url_service, - std::make_unique<UIThreadSearchTermsData>(profile()), + template_url_service, std::make_unique<UIThreadSearchTermsData>(), base::Bind(&BrowserInstantController::OnSearchEngineBaseURLChanged, base::Unretained(this))); }
diff --git a/chrome/browser/ui/browser_instant_controller_unittest.cc b/chrome/browser/ui/browser_instant_controller_unittest.cc index 14adffe4..9716c930 100644 --- a/chrome/browser/ui/browser_instant_controller_unittest.cc +++ b/chrome/browser/ui/browser_instant_controller_unittest.cc
@@ -50,13 +50,6 @@ false, false}, {"Other NTP", "https://bar.com/newtab", false, false, false, false}}; -// Test cases for when Google is both the initial and final provider. -const TabReloadTestCase kTabReloadTestCasesFinalProviderGoogle[] = { - {"Local NTP", chrome::kChromeSearchLocalNtpUrl, true, true, true, true}, - {"Remote SERP", "https://www.google.com/url?bar=search+terms", false, false, - false, false}, - {"Other NTP", "https://bar.com/newtab", false, false, false, false}}; - class FakeWebContentsObserver : public content::WebContentsObserver { public: explicit FakeWebContentsObserver(content::WebContents* contents) @@ -142,52 +135,6 @@ } } -TEST_F(BrowserInstantControllerTest, GoogleBaseURLUpdated) { - const size_t num_tests = base::size(kTabReloadTestCasesFinalProviderGoogle); - std::vector<std::unique_ptr<FakeWebContentsObserver>> observers; - for (size_t i = 0; i < num_tests; ++i) { - const TabReloadTestCase& test = kTabReloadTestCasesFinalProviderGoogle[i]; - AddTab(browser(), GURL(test.start_url)); - content::WebContents* contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - // Validate initial instant state. - EXPECT_EQ(test.start_in_instant_process, - instant_service_->IsInstantProcess( - contents->GetMainFrame()->GetProcess()->GetID())) - << test.description; - - // Setup an observer to verify reload or absence thereof. - observers.push_back(std::make_unique<FakeWebContentsObserver>(contents)); - } - - NotifyGoogleBaseURLUpdate("https://www.google.es/"); - - for (size_t i = 0; i < num_tests; ++i) { - const TabReloadTestCase& test = kTabReloadTestCasesFinalProviderGoogle[i]; - FakeWebContentsObserver* observer = observers[i].get(); - - // Validate final instant state. - EXPECT_EQ(test.end_in_instant_process, - search::ShouldAssignURLToInstantRenderer(observer->current_url(), - profile())) - << test.description; - - // Ensure only the expected tabs(contents) reloaded. - base::RunLoop loop; - loop.RunUntilIdle(); - EXPECT_EQ(test.should_reload ? 1 : 0, observer->num_reloads()) - << test.description; - - if (test.end_in_local_ntp) { - EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), observer->current_url()) - << test.description; - // The navigation to Local NTP should be definitive i.e. can't go back. - EXPECT_FALSE(observer->can_go_back()); - } - } -} - } // namespace } // namespace chrome
diff --git a/chrome/browser/ui/navigation_correction_tab_observer.cc b/chrome/browser/ui/navigation_correction_tab_observer.cc index 40256d42..9720d6cf 100644 --- a/chrome/browser/ui/navigation_correction_tab_observer.cc +++ b/chrome/browser/ui/navigation_correction_tab_observer.cc
@@ -7,7 +7,6 @@ #include "base/bind.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/google/google_url_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/common/navigation_corrector.mojom.h" @@ -36,18 +35,6 @@ base::Bind(&NavigationCorrectionTabObserver::OnEnabledChanged, base::Unretained(this))); } - - GoogleURLTracker* google_url_tracker = - GoogleURLTrackerFactory::GetForProfile(profile_); - if (google_url_tracker) { - if (google_util::IsGoogleDomainUrl(GetNavigationCorrectionURL(), - google_util::ALLOW_SUBDOMAIN, - google_util::ALLOW_NON_STANDARD_PORTS)) - google_url_tracker->RequestServerCheck(); - google_url_updated_subscription_ = google_url_tracker->RegisterCallback( - base::Bind(&NavigationCorrectionTabObserver::OnGoogleURLUpdated, - base::Unretained(this))); - } } NavigationCorrectionTabObserver::~NavigationCorrectionTabObserver() {} @@ -74,10 +61,6 @@ //////////////////////////////////////////////////////////////////////////////// // Internal helpers -void NavigationCorrectionTabObserver::OnGoogleURLUpdated() { - UpdateNavigationCorrectionInfo(web_contents()->GetMainFrame()); -} - GURL NavigationCorrectionTabObserver::GetNavigationCorrectionURL() const { // Disable navigation corrections when the preference is disabled or when in // Incognito mode. @@ -95,7 +78,7 @@ void NavigationCorrectionTabObserver::UpdateNavigationCorrectionInfo( RenderFrameHost* render_frame_host) { - GURL google_base_url(UIThreadSearchTermsData(profile_).GoogleBaseURLValue()); + GURL google_base_url(UIThreadSearchTermsData().GoogleBaseURLValue()); chrome::mojom::NavigationCorrectorAssociatedPtr client; render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&client); client->SetNavigationCorrectionInfo(
diff --git a/chrome/browser/ui/navigation_correction_tab_observer.h b/chrome/browser/ui/navigation_correction_tab_observer.h index 50a85c1..b68c6732 100644 --- a/chrome/browser/ui/navigation_correction_tab_observer.h +++ b/chrome/browser/ui/navigation_correction_tab_observer.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_NAVIGATION_CORRECTION_TAB_OBSERVER_H_ #include "base/macros.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/prefs/pref_change_registrar.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" @@ -35,9 +34,6 @@ // Internal helpers ---------------------------------------------------------- - // Callback that is called when the Google URL is updated. - void OnGoogleURLUpdated(); - // Returns the URL for the correction service. If the returned URL // is empty, the default error pages will be used. GURL GetNavigationCorrectionURL() const; @@ -51,8 +47,6 @@ Profile* profile_; PrefChangeRegistrar pref_change_registrar_; - std::unique_ptr<GoogleURLTracker::Subscription> - google_url_updated_subscription_; WEB_CONTENTS_USER_DATA_KEY_DECL();
diff --git a/chrome/browser/ui/passwords/manage_passwords_state.cc b/chrome/browser/ui/passwords/manage_passwords_state.cc index 4105c9a..6842fa4 100644 --- a/chrome/browser/ui/passwords/manage_passwords_state.cc +++ b/chrome/browser/ui/passwords/manage_passwords_state.cc
@@ -147,7 +147,8 @@ password_form_map, const GURL& origin, const std::vector<const autofill::PasswordForm*>* federated_matches) { - DCHECK(!password_form_map.empty()); + DCHECK(!password_form_map.empty() || + (federated_matches && !federated_matches->empty())); ClearData(); local_credentials_forms_ = DeepCopyNonPSLMapToVector(password_form_map); if (federated_matches)
diff --git a/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc index 14e9439..db46dac 100644 --- a/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_state_unittest.cc
@@ -450,6 +450,19 @@ EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); } +TEST_F(ManagePasswordsStateTest, PasswordAutofillWithOnlyFederations) { + std::map<base::string16, const autofill::PasswordForm*> password_form_map; + const GURL origin(kTestOrigin); + std::vector<const autofill::PasswordForm*> federated; + federated.push_back(&test_local_federated_form()); + passwords_data().OnPasswordAutofilled(password_form_map, origin, &federated); + + EXPECT_THAT(passwords_data().GetCurrentForms(), + ElementsAre(Pointee(test_local_federated_form()))); + + EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); +} + TEST_F(ManagePasswordsStateTest, ActiveOnMixedPSLAndNonPSLMatched) { std::map<base::string16, const autofill::PasswordForm*> password_form_map; password_form_map[test_local_form().username_value] = &test_local_form();
diff --git a/chrome/browser/ui/search/local_ntp_promos_browsertest.cc b/chrome/browser/ui/search/local_ntp_promos_browsertest.cc index 569d370..66a1f4d 100644 --- a/chrome/browser/ui/search/local_ntp_promos_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_promos_browsertest.cc
@@ -37,7 +37,7 @@ class MockPromoService : public PromoService { public: - MockPromoService() : PromoService(nullptr, nullptr) {} + MockPromoService() : PromoService(nullptr) {} void Refresh() override { PromoDataLoaded(promo_status_, promo_data_); }
diff --git a/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc b/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc index 1236edd..8591c1e 100644 --- a/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc +++ b/chrome/browser/ui/search/local_ntp_voice_search_browsertest.cc
@@ -105,8 +105,7 @@ EXPECT_TRUE(prompt_factory.RequestTypeSeen( PermissionRequestType::PERMISSION_MEDIASTREAM_MIC)); // ...and that it showed the Google base URL, not the NTP URL. - const GURL google_base_url( - UIThreadSearchTermsData(browser()->profile()).GoogleBaseURLValue()); + const GURL google_base_url(UIThreadSearchTermsData().GoogleBaseURLValue()); EXPECT_TRUE(prompt_factory.RequestOriginSeen(google_base_url.GetOrigin())); EXPECT_FALSE(prompt_factory.RequestOriginSeen( GURL(chrome::kChromeUINewTabURL).GetOrigin()));
diff --git a/chrome/browser/ui/signin_view_controller.cc b/chrome/browser/ui/signin_view_controller.cc index cf92cdc..1d5755b 100644 --- a/chrome/browser/ui/signin_view_controller.cc +++ b/chrome/browser/ui/signin_view_controller.cc
@@ -179,11 +179,10 @@ signin_metrics::PromoAction promo_action, const std::string& email_hint, const GURL& redirect_url) { - Profile* profile = browser->profile(); - #if DCHECK_IS_ON() if (!signin::DiceMethodGreaterOrEqual( - AccountConsistencyModeManager::GetMethodForProfile(profile), + AccountConsistencyModeManager::GetMethodForProfile( + browser->profile()), signin::AccountConsistencyMethod::kDiceMigration)) { // Developers often fall into the trap of not configuring the OAuth client // ID and client secret and then attempt to sign in to Chromium, which @@ -214,7 +213,7 @@ // because the set of valid URLs is not specified. std::string continue_url = (redirect_url.is_empty() || !redirect_url.SchemeIsHTTPOrHTTPS()) - ? UIThreadSearchTermsData(profile).GoogleBaseURLValue() + ? UIThreadSearchTermsData().GoogleBaseURLValue() : redirect_url.spec(); GURL signin_url =
diff --git a/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc b/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc index 1daaef32..644102cc 100644 --- a/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc +++ b/chrome/browser/ui/startup/credential_provider_signin_dialog_win.cc
@@ -491,7 +491,7 @@ // This widget will automatically delete itself and its WebDialogView when the // dialog window is closed. views::Widget* widget = new views::Widget; - widget->Init(init_params); + widget->Init(std::move(init_params)); widget->Show(); return web_view;
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc index 96e6b39..8555423 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc
@@ -82,7 +82,7 @@ app_info_bounds); params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_DEFAULT; params.shadow_elevation = kDialogShadowElevation; - dialog_widget->Init(params); + dialog_widget->Init(std::move(params)); // The title is not shown on the dialog, but it is used for overview mode. dialog_widget->GetNativeWindow()->SetTitle(base::UTF8ToUTF16(app->name())); dialog_widget->Show();
diff --git a/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.cc b/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.cc index b7594fe..fd20017 100644 --- a/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.cc +++ b/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.cc
@@ -20,11 +20,10 @@ } void AppWindowDesktopNativeWidgetAuraWin::InitNativeWidget( - const views::Widget::InitParams& params) { - views::Widget::InitParams modified_params = params; + views::Widget::InitParams params) { tree_host_ = new AppWindowDesktopWindowTreeHostWin(app_window_, this); - modified_params.desktop_window_tree_host = tree_host_; - DesktopNativeWidgetAura::InitNativeWidget(modified_params); + params.desktop_window_tree_host = tree_host_; + DesktopNativeWidgetAura::InitNativeWidget(std::move(params)); } void AppWindowDesktopNativeWidgetAuraWin::Maximize() {
diff --git a/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.h b/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.h index e906f2fa..1c0b9f3 100644 --- a/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.h +++ b/chrome/browser/ui/views/apps/app_window_desktop_native_widget_aura_win.h
@@ -26,7 +26,7 @@ ~AppWindowDesktopNativeWidgetAuraWin() override; // Overridden from views::DesktopNativeWidgetAura: - void InitNativeWidget(const views::Widget::InitParams& params) override; + void InitNativeWidget(views::Widget::InitParams params) override; void Maximize() override; void Minimize() override;
diff --git a/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc b/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc index 337c1fab..beb38db7 100644 --- a/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc +++ b/chrome/browser/ui/views/apps/chrome_native_app_window_views.cc
@@ -126,7 +126,7 @@ create_params.visible_on_all_workspaces; OnBeforeWidgetInit(create_params, &init_params, widget()); - widget()->Init(init_params); + widget()->Init(std::move(init_params)); // The frame insets are required to resolve the bounds specifications // correctly. So we set the window bounds and constraints now.
diff --git a/chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc b/chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc index dd5bcb0..838033b 100644 --- a/chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc +++ b/chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc
@@ -45,7 +45,7 @@ params.bounds = gfx::Rect(30, 30, 100, 100); params.context = root_window(); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); app_window_.set_web_view_for_testing(&web_view_); app_window_.set_window_for_testing(widget_.get());
diff --git a/chrome/browser/ui/views/autofill/autofill_popup_base_view.cc b/chrome/browser/ui/views/autofill/autofill_popup_base_view.cc index d6af8c0..d7a00f7 100644 --- a/chrome/browser/ui/views/autofill/autofill_popup_base_view.cc +++ b/chrome/browser/ui/views/autofill/autofill_popup_base_view.cc
@@ -89,7 +89,7 @@ // Ensure the bubble border is not painted on an opaque background. params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; - widget->Init(params); + widget->Init(std::move(params)); widget->AddObserver(this); // No animation for popup appearance (too distracting).
diff --git a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views_unittest.cc b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views_unittest.cc index d7bba80..4144776 100644 --- a/chrome/browser/ui/views/autofill/autofill_popup_view_native_views_unittest.cc +++ b/chrome/browser/ui/views/autofill/autofill_popup_view_native_views_unittest.cc
@@ -106,7 +106,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); } std::unique_ptr<autofill::AutofillPopupViewNativeViews> view_;
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc index 5e5f4c2d..a47b603 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc
@@ -128,11 +128,10 @@ private: static std::unique_ptr<KeyedService> CreateTemplateURLService( content::BrowserContext* profile) { - return base::WrapUnique( - new TemplateURLService(static_cast<Profile*>(profile)->GetPrefs(), - base::WrapUnique(new SearchTermsData), NULL, - std::unique_ptr<TemplateURLServiceClient>(), - NULL, NULL, base::Closure())); + return std::make_unique<TemplateURLService>( + static_cast<Profile*>(profile)->GetPrefs(), + std::make_unique<SearchTermsData>(), nullptr, nullptr, nullptr, + base::Closure()); } DISALLOW_COPY_AND_ASSIGN(BookmarkBarViewTest); @@ -391,7 +390,7 @@ params.native_widget = CreateNativeWidget( NativeWidgetType::DESKTOP_NATIVE_WIDGET_AURA, ¶ms, &widget); #endif - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); widget.GetRootView()->AddChildView(bookmark_bar_view_.get());
diff --git a/chrome/browser/ui/views/chrome_web_dialog_view.cc b/chrome/browser/ui/views/chrome_web_dialog_view.cc index 2804fb6..ef11e5a4 100644 --- a/chrome/browser/ui/views/chrome_web_dialog_view.cc +++ b/chrome/browser/ui/views/chrome_web_dialog_view.cc
@@ -26,10 +26,10 @@ namespace chrome { namespace { -gfx::NativeWindow ShowWebDialogWidget(const views::Widget::InitParams& params, +gfx::NativeWindow ShowWebDialogWidget(views::Widget::InitParams params, views::WebDialogView* view) { views::Widget* widget = new views::Widget; - widget->Init(params); + widget->Init(std::move(params)); // Observer is needed for ChromeVox extension to send messages between content // and background scripts. @@ -46,19 +46,19 @@ gfx::NativeWindow ShowWebDialog(gfx::NativeView parent, content::BrowserContext* context, ui::WebDialogDelegate* delegate) { - return ShowWebDialogWithParams(parent, context, delegate, nullptr); + return ShowWebDialogWithParams(parent, context, delegate, base::nullopt); } gfx::NativeWindow ShowWebDialogWithParams( gfx::NativeView parent, content::BrowserContext* context, ui::WebDialogDelegate* delegate, - const views::Widget::InitParams* extra_params) { + base::Optional<views::Widget::InitParams> extra_params) { views::WebDialogView* view = new views::WebDialogView( context, delegate, std::make_unique<ChromeWebContentsHandler>()); views::Widget::InitParams params; if (extra_params) - params = *extra_params; + params = std::move(*extra_params); params.delegate = view; params.parent = parent; #if defined(OS_CHROMEOS) @@ -67,7 +67,7 @@ ash_util::SetupWidgetInitParamsForContainer(¶ms, container_id); } #endif - gfx::NativeWindow window = ShowWebDialogWidget(params, view); + gfx::NativeWindow window = ShowWebDialogWidget(std::move(params), view); #if defined(OS_CHROMEOS) const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(
diff --git a/chrome/browser/ui/views/chrome_web_dialog_view.h b/chrome/browser/ui/views/chrome_web_dialog_view.h index 94f5e9c3..ca99a5a 100644 --- a/chrome/browser/ui/views/chrome_web_dialog_view.h +++ b/chrome/browser/ui/views/chrome_web_dialog_view.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_VIEWS_CHROME_WEB_DIALOG_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_CHROME_WEB_DIALOG_VIEW_H_ +#include "base/optional.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/widget/widget.h" @@ -23,7 +24,7 @@ gfx::NativeView parent, content::BrowserContext* context, ui::WebDialogDelegate* delegate, - const views::Widget::InitParams* extra_params); + base::Optional<views::Widget::InitParams> extra_params); } // namespace chrome
diff --git a/chrome/browser/ui/views/confirm_bubble_views_unittest.cc b/chrome/browser/ui/views/confirm_bubble_views_unittest.cc index 0fb9855..1482655 100644 --- a/chrome/browser/ui/views/confirm_bubble_views_unittest.cc +++ b/chrome/browser/ui/views/confirm_bubble_views_unittest.cc
@@ -25,7 +25,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; std::unique_ptr<views::Widget> parent_widget(new Widget); - parent_widget->Init(params); + parent_widget->Init(std::move(params)); parent_widget->Show(); // Bubble owns the model.
diff --git a/chrome/browser/ui/views/download/download_started_animation_views.cc b/chrome/browser/ui/views/download/download_started_animation_views.cc index 462d3963..7822b75 100644 --- a/chrome/browser/ui/views/download/download_started_animation_views.cc +++ b/chrome/browser/ui/views/download/download_started_animation_views.cc
@@ -78,7 +78,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.accept_events = false; params.parent = web_contents->GetNativeView(); - popup_->Init(params); + popup_->Init(std::move(params)); popup_->SetOpacity(0.f); popup_->SetContentsView(this); Reposition();
diff --git a/chrome/browser/ui/views/dropdown_bar_host.cc b/chrome/browser/ui/views/dropdown_bar_host.cc index f208d78..9cda042 100644 --- a/chrome/browser/ui/views/dropdown_bar_host.cc +++ b/chrome/browser/ui/views/dropdown_bar_host.cc
@@ -55,7 +55,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = browser_view_->GetWidget()->GetNativeView(); params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; - host_->Init(params); + host_->Init(std::move(params)); host_->SetContentsView(clip_view.release()); SetHostViewNative(host_view);
diff --git a/chrome/browser/ui/views/extensions/chooser_dialog_view_unittest.cc b/chrome/browser/ui/views/extensions/chooser_dialog_view_unittest.cc index 2a97f9da..28d49ce0 100644 --- a/chrome/browser/ui/views/extensions/chooser_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/extensions/chooser_dialog_view_unittest.cc
@@ -34,7 +34,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(10, 11, 200, 200); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget_.Init(params); + parent_widget_.Init(std::move(params)); widget_ = views::DialogDelegate::CreateDialogWidget( dialog_, GetContext(), parent_widget_.GetNativeView());
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_button.cc b/chrome/browser/ui/views/extensions/extensions_menu_button.cc index 70bd05e..5a8704e1 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_button.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_button.cc
@@ -6,6 +6,7 @@ #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_controller.h" +#include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "chrome/browser/ui/views/extensions/extensions_menu_view.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_button.h" #include "chrome/browser/ui/views/frame/browser_view.h" @@ -15,9 +16,11 @@ #include "ui/gfx/paint_vector_icon.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/image_button.h" +#include "ui/views/controls/button/image_button_factory.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/layout/box_layout.h" #include "ui/views/layout/layout_provider.h" +#include "ui/views/vector_icons.h" #include "ui/views/view_class_properties.h" const char ExtensionsMenuButton::kClassName[] = "ExtensionsMenuButton"; @@ -25,6 +28,15 @@ namespace { constexpr int EXTENSION_CONTEXT_MENU = 13; +constexpr int EXTENSION_PINNING = 14; + +constexpr int kSecondaryIconSizeDp = 16; + +void SetSecondaryButtonHighlightPath(views::Button* button) { + auto highlight_path = std::make_unique<SkPath>(); + highlight_path->addOval(gfx::RectToSkRect(gfx::Rect(button->size()))); + button->SetProperty(views::kHighlightPathKey, highlight_path.release()); +} } // namespace @@ -39,7 +51,11 @@ true, true), browser_(browser), - controller_(std::move(controller)) { + controller_(std::move(controller)), + model_(ToolbarActionsModel::Get(browser_->profile())) { + // Set so the extension button receives enter/exit on children to retain hover + // status when hovering child views. + set_notify_enter_exit_on_child(true); ConfigureSecondaryView(); set_auto_compute_tooltip(false); controller_->SetDelegate(this); @@ -48,6 +64,42 @@ ExtensionsMenuButton::~ExtensionsMenuButton() = default; +void ExtensionsMenuButton::UpdatePinButton() { + pin_button_->SetTooltipText(l10n_util::GetStringUTF16( + IsPinned() ? IDS_EXTENSIONS_MENU_UNPIN_BUTTON_TOOLTIP + : IDS_EXTENSIONS_MENU_PIN_BUTTON_TOOLTIP)); + SkColor unpinned_icon_color = + ui::NativeTheme::GetInstanceForNativeUi()->SystemDarkModeEnabled() + ? gfx::kGoogleGrey500 + : gfx::kChromeIconGrey; + SkColor icon_color = IsPinned() + ? GetNativeTheme()->GetSystemColor( + ui::NativeTheme::kColorId_ProminentButtonColor) + : unpinned_icon_color; + views::SetImageFromVectorIcon( + pin_button_, IsPinned() ? views::kUnpinIcon : views::kPinIcon, + kSecondaryIconSizeDp, icon_color); + pin_button_->SetVisible(IsPinned() || IsMouseHovered() || IsMenuRunning()); +} + +void ExtensionsMenuButton::OnMouseEntered(const ui::MouseEvent& event) { + UpdatePinButton(); + // The layout manager does not get notified of visibility changes and the pin + // buttons has not be laid out before if it was invisible. + pin_button_->InvalidateLayout(); + views::Button::OnMouseEntered(event); +} + +void ExtensionsMenuButton::OnMouseExited(const ui::MouseEvent& event) { + UpdatePinButton(); + views::Button::OnMouseExited(event); +} + +void ExtensionsMenuButton::OnBoundsChanged(const gfx::Rect& previous_bounds) { + UpdatePinButton(); + HoverButton::OnBoundsChanged(previous_bounds); +} + const char* ExtensionsMenuButton::GetClassName() const { return kClassName; } @@ -57,6 +109,9 @@ if (sender->GetID() == EXTENSION_CONTEXT_MENU) { RunExtensionContextMenu(ui::MENU_SOURCE_MOUSE); return; + } else if (sender->GetID() == EXTENSION_PINNING) { + model_->SetActionVisibility(controller_->GetId(), !IsPinned()); + return; } DCHECK_EQ(this, sender); controller_->ExecuteAction(true); @@ -123,6 +178,10 @@ menu_runner_.reset(); controller_->OnContextMenuClosed(); menu_adapter_.reset(); + // OnMouseExited is triggered when the context menu is opened. Since we don't + // hide the pin button OnMouseExited if the context menu is open we must + // update its state to hide it when the context menu is closed. + UpdatePinButton(); } void ExtensionsMenuButton::ConfigureSecondaryView() { @@ -136,6 +195,16 @@ ? gfx::kGoogleGrey500 : gfx::kChromeIconGrey; + auto pin_button = views::CreateVectorImageButton(this); + pin_button->SetID(EXTENSION_PINNING); + pin_button->set_ink_drop_base_color(icon_color); + pin_button->SizeToPreferredSize(); + + pin_button_ = pin_button.get(); + SetSecondaryButtonHighlightPath(pin_button_); + UpdatePinButton(); + container->AddChildView(std::move(pin_button)); + auto context_menu_button = std::make_unique<views::MenuButton>(base::string16(), this); context_menu_button->SetID(EXTENSION_CONTEXT_MENU); @@ -144,7 +213,9 @@ context_menu_button->SetImage( views::Button::STATE_NORMAL, - gfx::CreateVectorIcon(kBrowserToolsIcon, 16, icon_color)); + gfx::CreateVectorIcon(kBrowserToolsIcon, kSecondaryIconSizeDp, + icon_color)); + context_menu_button->set_ink_drop_base_color(icon_color); context_menu_button->SetBorder( views::CreateEmptyBorder(views::LayoutProvider::Get()->GetInsetsMetric( @@ -153,12 +224,15 @@ context_menu_button->SetInkDropMode(InkDropMode::ON); context_menu_button->set_has_ink_drop_action_on_click(true); - auto highlight_path = std::make_unique<SkPath>(); - highlight_path->addOval( - gfx::RectToSkRect(gfx::Rect(context_menu_button->size()))); - context_menu_button->SetProperty(views::kHighlightPathKey, - highlight_path.release()); context_menu_button_ = context_menu_button.get(); + SetSecondaryButtonHighlightPath(context_menu_button_); container->AddChildView(std::move(context_menu_button)); } + +bool ExtensionsMenuButton::IsPinned() { + // |model_| can be null in unit tests. + if (!model_) + return false; + return model_->IsActionPinned(controller_->GetId()); +}
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_button.h b/chrome/browser/ui/views/extensions/extensions_menu_button.h index a2d813f1..6dee2df9 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_button.h +++ b/chrome/browser/ui/views/extensions/extensions_menu_button.h
@@ -15,6 +15,7 @@ namespace views { class Button; +class ImageButton; class MenuButton; class MenuModelAdapter; class MenuRunner; @@ -28,9 +29,18 @@ std::unique_ptr<ToolbarActionViewController> controller); ~ExtensionsMenuButton() override; + // Update pin button icon, color, tooltip, and visibility based on pinned + // state. + void UpdatePinButton(); + static const char kClassName[]; private: + // views::Button: + void OnMouseEntered(const ui::MouseEvent& event) override; + void OnMouseExited(const ui::MouseEvent& event) override; + void OnBoundsChanged(const gfx::Rect& previous_bounds) override; + // views::ButtonListener: const char* GetClassName() const override; void ButtonPressed(Button* sender, const ui::Event& event) override; @@ -51,8 +61,11 @@ // Configures the secondary (right-hand-side) view of this HoverButton. void ConfigureSecondaryView(); + bool IsPinned(); + Browser* const browser_; const std::unique_ptr<ToolbarActionViewController> controller_; + ToolbarActionsModel* const model_; // TODO(pbos): There's complicated configuration code in place since menus // can't be triggered from ImageButtons. When MenuRunner::RunMenuAt accepts @@ -60,6 +73,8 @@ // image_button_factory.h methods to configure it. views::MenuButton* context_menu_button_ = nullptr; + views::ImageButton* pin_button_ = nullptr; + // Responsible for converting the context menu model into |menu_|. std::unique_ptr<views::MenuModelAdapter> menu_adapter_;
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_button_unittest.cc b/chrome/browser/ui/views/extensions/extensions_menu_button_unittest.cc index 7ac8fb36..1e2d4b00 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_button_unittest.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_button_unittest.cc
@@ -5,8 +5,10 @@ #include "chrome/browser/ui/views/extensions/extensions_menu_button.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/browser/ui/toolbar/test_toolbar_action_view_controller.h" +#include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/native_widget_factory.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "ui/events/event.h" @@ -19,6 +21,7 @@ : initial_extension_name_(base::ASCIIToUTF16("Initial Extension Name")), initial_tooltip_(base::ASCIIToUTF16("Initial tooltip")) {} void SetUp() override { + scoped_feature_list_.InitAndEnableFeature(features::kExtensionsToolbarMenu); BrowserWithTestWindowTest::SetUp(); widget_ = std::make_unique<views::Widget>(); @@ -36,7 +39,7 @@ CreateNativeWidget(NativeWidgetType::DESKTOP_NATIVE_WIDGET_AURA, &init_params, widget_.get()); #endif - widget_->Init(init_params); + widget_->Init(std::move(init_params)); auto controller = std::make_unique<TestToolbarActionViewController>("hello"); @@ -64,6 +67,7 @@ test_api.NotifyClick(click_event); } + base::test::ScopedFeatureList scoped_feature_list_; const base::string16 initial_extension_name_; const base::string16 initial_tooltip_; std::unique_ptr<views::Widget> widget_;
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_view.cc b/chrome/browser/ui/views/extensions/extensions_menu_view.cc index aa44a76..252e17f 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_view.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_view.cc
@@ -63,6 +63,7 @@ ExtensionsMenuView::~ExtensionsMenuView() { DCHECK_EQ(g_extensions_dialog, this); g_extensions_dialog = nullptr; + extension_menu_buttons_.clear(); } void ExtensionsMenuView::ButtonPressed(views::Button* sender, @@ -113,6 +114,7 @@ std::unique_ptr<views::View> ExtensionsMenuView::CreateExtensionButtonsContainer() { + extension_menu_buttons_.clear(); content::WebContents* const web_contents = browser_->tab_strip_model()->GetActiveWebContents(); @@ -139,7 +141,6 @@ } auto extension_buttons = std::make_unique<views::View>(); - extension_menu_button_container_for_testing_ = extension_buttons.get(); extension_buttons->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); @@ -179,9 +180,11 @@ }); for (auto& controller : *controller_group) { - extension_buttons->AddChildView( + std::unique_ptr<ExtensionsMenuButton> extension_button = std::make_unique<ExtensionsMenuButton>(browser_, - std::move(controller))); + std::move(controller)); + extension_menu_buttons_.push_back(extension_button.get()); + extension_buttons->AddChildView(std::move(extension_button)); } controller_group->clear(); }; @@ -233,7 +236,9 @@ } void ExtensionsMenuView::OnToolbarPinnedActionsChanged() { - Repopulate(); + for (auto* button : extension_menu_buttons_) { + button->UpdatePinButton(); + } } // static
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_view.h b/chrome/browser/ui/views/extensions/extensions_menu_view.h index 7e706b2..15f3da0 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_view.h +++ b/chrome/browser/ui/views/extensions/extensions_menu_view.h
@@ -16,6 +16,7 @@ class ImageView; } // namespace views +class ExtensionsMenuButton; class ExtensionsContainer; // This bubble view displays a list of user extensions. @@ -62,8 +63,8 @@ void OnToolbarModelInitialized() override; void OnToolbarPinnedActionsChanged() override; - views::View* extension_menu_button_container_for_testing() { - return extension_menu_button_container_for_testing_; + std::vector<ExtensionsMenuButton*> extension_menu_buttons_for_testing() { + return extension_menu_buttons_; } views::Button* manage_extensions_button_for_testing() { return manage_extensions_button_for_testing_; @@ -78,8 +79,8 @@ ToolbarActionsModel* const model_; ScopedObserver<ToolbarActionsModel, ToolbarActionsModel::Observer> model_observer_; + std::vector<ExtensionsMenuButton*> extension_menu_buttons_; - views::View* extension_menu_button_container_for_testing_ = nullptr; views::Button* manage_extensions_button_for_testing_ = nullptr; DISALLOW_COPY_AND_ASSIGN(ExtensionsMenuView);
diff --git a/chrome/browser/ui/views/extensions/extensions_menu_view_browsertest.cc b/chrome/browser/ui/views/extensions/extensions_menu_view_browsertest.cc index 50c92f8..5f2d5b81 100644 --- a/chrome/browser/ui/views/extensions/extensions_menu_view_browsertest.cc +++ b/chrome/browser/ui/views/extensions/extensions_menu_view_browsertest.cc
@@ -58,14 +58,8 @@ } static std::vector<ExtensionsMenuButton*> GetExtensionMenuButtons() { - std::vector<ExtensionsMenuButton*> buttons; - for (auto* view : ExtensionsMenuView::GetExtensionsMenuViewForTesting() - ->extension_menu_button_container_for_testing() - ->children()) { - if (view->GetClassName() == ExtensionsMenuButton::kClassName) - buttons.push_back(static_cast<ExtensionsMenuButton*>(view)); - } - return buttons; + return ExtensionsMenuView::GetExtensionsMenuViewForTesting() + ->extension_menu_buttons_for_testing(); } std::vector<ToolbarActionView*> GetToolbarActionViews() const {
diff --git a/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc b/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc index f3b7f3d9..55c3b61b 100644 --- a/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc +++ b/chrome/browser/ui/views/extensions/extensions_toolbar_button.cc
@@ -13,6 +13,7 @@ #include "ui/base/material_design/material_design_controller.h" #include "ui/base/theme_provider.h" #include "ui/gfx/paint_vector_icon.h" +#include "ui/views/controls/button/button_controller.h" ExtensionsToolbarButton::ExtensionsToolbarButton( Browser* browser, @@ -21,7 +22,8 @@ browser_(browser), extensions_container_(extensions_container) { SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_EXTENSIONS_BUTTON)); - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_PRESS); } void ExtensionsToolbarButton::UpdateIcon() {
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc index a927228..0188a20 100644 --- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc +++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
@@ -76,7 +76,7 @@ void BrowserDesktopWindowTreeHostWin::Init( const views::Widget::InitParams& params) { - DesktopWindowTreeHostWin::Init(params); + DesktopWindowTreeHostWin::Init(std::move(params)); if (base::win::GetVersion() < base::win::Version::WIN10) return; // VirtualDesktopManager isn't support pre Win-10.
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_x11.cc b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_x11.cc index 764ffcb..9a4177d 100644 --- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_x11.cc +++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_x11.cc
@@ -54,7 +54,7 @@ void BrowserDesktopWindowTreeHostX11::Init( const views::Widget::InitParams& params) { - views::DesktopWindowTreeHostX11::Init(params); + views::DesktopWindowTreeHostX11::Init(std::move(params)); // We have now created our backing X11 window. We now need to (possibly) // alert Unity that there's a menu bar attached to it.
diff --git a/chrome/browser/ui/views/frame/browser_frame.cc b/chrome/browser/ui/views/frame/browser_frame.cc index 85abd49..881bdbc 100644 --- a/chrome/browser/ui/views/frame/browser_frame.cc +++ b/chrome/browser/ui/views/frame/browser_frame.cc
@@ -104,7 +104,7 @@ } } - Init(params); + Init(std::move(params)); if (!native_browser_frame_->UsesNativeSystemMenu()) { DCHECK(non_client_view());
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index dcd328b2..c7caabc 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -1423,13 +1423,16 @@ send_tab_to_self::SendTabToSelfBubbleViewImpl* bubble = new send_tab_to_self::SendTabToSelfBubbleViewImpl( GetLocationBarView(), gfx::Point(), web_contents, controller); - PageActionIconView* icon_view = - GetLocationBarView()->send_tab_to_self_icon_view(); - if (icon_view) - bubble->SetHighlightedButton(icon_view); views::BubbleDialogDelegateView::CreateBubble(bubble); bubble->Show(send_tab_to_self::SendTabToSelfBubbleViewImpl::USER_GESTURE); + PageActionIconView* icon_view = + toolbar_button_provider() + ->GetOmniboxPageActionIconContainerView() + ->GetPageActionIconView(PageActionIconType::kSendTabToSelf); + if (icon_view) + bubble->SetHighlightedButton(icon_view); + return bubble; }
diff --git a/chrome/browser/ui/views/frame/desktop_browser_frame_aura.cc b/chrome/browser/ui/views/frame/desktop_browser_frame_aura.cc index c1d558c..8e65674 100644 --- a/chrome/browser/ui/views/frame/desktop_browser_frame_aura.cc +++ b/chrome/browser/ui/views/frame/desktop_browser_frame_aura.cc
@@ -48,17 +48,16 @@ } void DesktopBrowserFrameAura::InitNativeWidget( - const views::Widget::InitParams& params) { + views::Widget::InitParams params) { browser_desktop_window_tree_host_ = BrowserDesktopWindowTreeHost::CreateBrowserDesktopWindowTreeHost( browser_frame_, this, browser_view_, browser_frame_); - views::Widget::InitParams modified_params = params; - modified_params.desktop_window_tree_host = + params.desktop_window_tree_host = browser_desktop_window_tree_host_->AsDesktopWindowTreeHost(); - DesktopNativeWidgetAura::InitNativeWidget(modified_params); + DesktopNativeWidgetAura::InitNativeWidget(std::move(params)); visibility_controller_.reset(new wm::VisibilityController); aura::client::SetVisibilityClient(GetNativeView()->GetRootWindow(),
diff --git a/chrome/browser/ui/views/frame/desktop_browser_frame_aura.h b/chrome/browser/ui/views/frame/desktop_browser_frame_aura.h index 45f24d8..81acbbf 100644 --- a/chrome/browser/ui/views/frame/desktop_browser_frame_aura.h +++ b/chrome/browser/ui/views/frame/desktop_browser_frame_aura.h
@@ -40,7 +40,7 @@ // Overridden from views::DesktopNativeWidgetAura: void OnHostClosed() override; - void InitNativeWidget(const views::Widget::InitParams& params) override; + void InitNativeWidget(views::Widget::InitParams params) override; // Overridden from NativeBrowserFrame: views::Widget::InitParams GetWidgetParams() override;
diff --git a/chrome/browser/ui/views/frame/test_with_browser_view.cc b/chrome/browser/ui/views/frame/test_with_browser_view.cc index 2dad23d4..20acff0 100644 --- a/chrome/browser/ui/views/frame/test_with_browser_view.cc +++ b/chrome/browser/ui/views/frame/test_with_browser_view.cc
@@ -42,13 +42,13 @@ content::BrowserContext* context) { Profile* profile = static_cast<Profile*>(context); return std::make_unique<TemplateURLService>( - profile->GetPrefs(), std::make_unique<UIThreadSearchTermsData>(profile), + profile->GetPrefs(), std::make_unique<UIThreadSearchTermsData>(), WebDataServiceFactory::GetKeywordWebDataForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS), std::make_unique<ChromeTemplateURLServiceClient>( HistoryServiceFactory::GetForProfile( profile, ServiceAccessType::EXPLICIT_ACCESS)), - nullptr, nullptr, base::Closure()); + nullptr, base::Closure()); } std::unique_ptr<KeyedService> CreateAutocompleteClassifier(
diff --git a/chrome/browser/ui/views/fullscreen_control/fullscreen_control_popup.cc b/chrome/browser/ui/views/fullscreen_control/fullscreen_control_popup.cc index 0ba5872c2..db9fc37 100644 --- a/chrome/browser/ui/views/fullscreen_control/fullscreen_control_popup.cc +++ b/chrome/browser/ui/views/fullscreen_control/fullscreen_control_popup.cc
@@ -29,7 +29,7 @@ params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = parent_view; - popup->Init(params); + popup->Init(std::move(params)); popup->SetContentsView(view); return popup;
diff --git a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc index 457470b..9f1a4f0 100644 --- a/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_toolbar_button_view.cc
@@ -10,13 +10,15 @@ #include "ui/base/theme_provider.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/native_theme/native_theme.h" +#include "ui/views/controls/button/button_controller.h" MediaToolbarButtonView::MediaToolbarButtonView( service_manager::Connector* connector) : ToolbarButton(this), connector_(connector), controller_(connector_, this) { - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_PRESS); EnableCanvasFlippingForRTLUI(false); ToolbarButton::Init();
diff --git a/chrome/browser/ui/views/hats/hats_web_dialog.cc b/chrome/browser/ui/views/hats/hats_web_dialog.cc index 12ab5b6..eb0af7d 100644 --- a/chrome/browser/ui/views/hats/hats_web_dialog.cc +++ b/chrome/browser/ui/views/hats/hats_web_dialog.cc
@@ -88,9 +88,11 @@ params.bounds = gfx::Rect( bounds.x() + std::max(0, bounds.width() / 2 - kDefaultHatsDialogWidth / 2), - bounds.bottom(), kDefaultHatsDialogWidth, kDefaultHatsDialogHeight); - chrome::ShowWebDialogWithParams(browser_view->GetWidget()->GetNativeView(), - profile, hats_dialog, ¶ms); + bounds.bottom() - views::BubbleBorder::GetBorderAndShadowInsets().top(), + kDefaultHatsDialogWidth, kDefaultHatsDialogHeight); + chrome::ShowWebDialogWithParams( + browser_view->GetWidget()->GetNativeView(), profile, hats_dialog, + base::make_optional<views::Widget::InitParams>(std::move(params))); } HatsWebDialog::HatsWebDialog(const std::string& site_id) : site_id_(site_id) {
diff --git a/chrome/browser/ui/views/hover_button.cc b/chrome/browser/ui/views/hover_button.cc index 2004c8c..963dca5 100644 --- a/chrome/browser/ui/views/hover_button.cc +++ b/chrome/browser/ui/views/hover_button.cc
@@ -16,6 +16,7 @@ #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/background.h" #include "ui/views/border.h" +#include "ui/views/controls/button/menu_button_controller.h" #include "ui/views/controls/styled_label.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/layout/grid_layout.h" @@ -78,7 +79,8 @@ SetInkDropMode(InkDropMode::ON); - set_notify_action(Button::NOTIFY_ON_RELEASE); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_RELEASE); } HoverButton::HoverButton(views::ButtonListener* button_listener,
diff --git a/chrome/browser/ui/views/hover_button_unittest.cc b/chrome/browser/ui/views/hover_button_unittest.cc index 8b72ce2f..ae7bcbc 100644 --- a/chrome/browser/ui/views/hover_button_unittest.cc +++ b/chrome/browser/ui/views/hover_button_unittest.cc
@@ -75,7 +75,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(100, 100, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); } private:
diff --git a/chrome/browser/ui/views/ime/ime_window_view.cc b/chrome/browser/ui/views/ime/ime_window_view.cc index 2a14d105..48c9996 100644 --- a/chrome/browser/ui/views/ime/ime_window_view.cc +++ b/chrome/browser/ui/views/ime/ime_window_view.cc
@@ -44,7 +44,7 @@ params.bounds = bounds; window_->set_focus_on_creation(false); window_->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM); - window_->Init(params); + window_->Init(std::move(params)); window_->UpdateWindowTitle(); window_->UpdateWindowIcon();
diff --git a/chrome/browser/ui/views/location_bar/icon_label_bubble_view_unittest.cc b/chrome/browser/ui/views/location_bar/icon_label_bubble_view_unittest.cc index d04af19f..969d481 100644 --- a/chrome/browser/ui/views/location_bar/icon_label_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/location_bar/icon_label_bubble_view_unittest.cc
@@ -180,7 +180,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); } void Reset() { @@ -414,7 +414,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; views::Widget widget; - widget.Init(params); + widget.Init(std::move(params)); IconLabelBubbleView* icon_label_bubble_view = new TestIconLabelBubbleView(font_list); icon_label_bubble_view->SetLabel(base::ASCIIToUTF16("x"));
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.h b/chrome/browser/ui/views/location_bar/location_bar_view.h index d1db40e..f41b319 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.h +++ b/chrome/browser/ui/views/location_bar/location_bar_view.h
@@ -56,10 +56,6 @@ class SaveCardIconView; } // namespace autofill -namespace send_tab_to_self { -class SendTabToSelfIconView; -} - namespace views { class ImageButton; class Label; @@ -157,12 +153,6 @@ return local_card_migration_icon_view_; } - // The send tab to self icon. It may not be visible. It will be null when - // |browser_| is null. - send_tab_to_self::SendTabToSelfIconView* send_tab_to_self_icon_view() { - return send_tab_to_self_icon_view_; - } - OmniboxPageActionIconContainerView* omnibox_page_action_icon_container_view() { return omnibox_page_action_icon_container_view_; @@ -421,10 +411,6 @@ autofill::LocalCardMigrationIconView* local_card_migration_icon_view_ = nullptr; - // The send tab to self icon. It will be null when |browser_| is null. - send_tab_to_self::SendTabToSelfIconView* send_tab_to_self_icon_view_ = - nullptr; - // The star for bookmarking. It will be null when |browser_| is null. StarView* star_view_ = nullptr;
diff --git a/chrome/browser/ui/views/location_bar/location_icon_view_unittest.cc b/chrome/browser/ui/views/location_bar/location_icon_view_unittest.cc index e1f60fb3..29347ed 100644 --- a/chrome/browser/ui/views/location_bar/location_icon_view_unittest.cc +++ b/chrome/browser/ui/views/location_bar/location_icon_view_unittest.cc
@@ -109,7 +109,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); } };
diff --git a/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc b/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc index 6c2a8643..081cb0d 100644 --- a/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/media_router/cast_dialog_view_unittest.cc
@@ -92,7 +92,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget_ = std::make_unique<views::Widget>(); - anchor_widget_->Init(params); + anchor_widget_->Init(std::move(params)); anchor_widget_->Show(); }
diff --git a/chrome/browser/ui/views/media_router/cast_toolbar_button.cc b/chrome/browser/ui/views/media_router/cast_toolbar_button.cc index 8b1c1be..54c85a51 100644 --- a/chrome/browser/ui/views/media_router/cast_toolbar_button.cc +++ b/chrome/browser/ui/views/media_router/cast_toolbar_button.cc
@@ -21,6 +21,7 @@ #include "ui/gfx/color_palette.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/native_theme/native_theme.h" +#include "ui/views/controls/button/button_controller.h" namespace media_router { @@ -54,7 +55,8 @@ browser_(browser), profile_(browser_->profile()), context_menu_(std::move(context_menu)) { - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_PRESS); EnableCanvasFlippingForRTLUI(false); SetTooltipText(l10n_util::GetStringUTF16(IDS_MEDIA_ROUTER_ICON_TOOLTIP_TEXT));
diff --git a/chrome/browser/ui/views/media_router/cast_toolbar_button_unittest.cc b/chrome/browser/ui/views/media_router/cast_toolbar_button_unittest.cc index 15db045..bf5d049 100644 --- a/chrome/browser/ui/views/media_router/cast_toolbar_button_unittest.cc +++ b/chrome/browser/ui/views/media_router/cast_toolbar_button_unittest.cc
@@ -96,7 +96,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetContentsView(button_.get()); ui::NativeTheme* native_theme = button_->GetNativeTheme();
diff --git a/chrome/browser/ui/views/media_router/cloud_services_dialog_view_unittest.cc b/chrome/browser/ui/views/media_router/cloud_services_dialog_view_unittest.cc index 3c82977..44f12ea 100644 --- a/chrome/browser/ui/views/media_router/cloud_services_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/media_router/cloud_services_dialog_view_unittest.cc
@@ -34,7 +34,7 @@ widget_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget_ = std::make_unique<views::Widget>(); - anchor_widget_->Init(widget_params); + anchor_widget_->Init(std::move(widget_params)); anchor_widget_->Show(); }
diff --git a/chrome/browser/ui/views/media_router/presentation_receiver_window_frame.cc b/chrome/browser/ui/views/media_router/presentation_receiver_window_frame.cc index 7a1fe6c..86b9f33 100644 --- a/chrome/browser/ui/views/media_router/presentation_receiver_window_frame.cc +++ b/chrome/browser/ui/views/media_router/presentation_receiver_window_frame.cc
@@ -19,7 +19,7 @@ params.bounds = bounds; params.delegate = delegate.release(); - Init(params); + Init(std::move(params)); } const ui::ThemeProvider* PresentationReceiverWindowFrame::GetThemeProvider()
diff --git a/chrome/browser/ui/views/menu_interactive_uitest.cc b/chrome/browser/ui/views/menu_interactive_uitest.cc index 4acc26b..e75b725 100644 --- a/chrome/browser/ui/views/menu_interactive_uitest.cc +++ b/chrome/browser/ui/views/menu_interactive_uitest.cc
@@ -82,7 +82,7 @@ params.native_widget = CreateNativeWidget( NativeWidgetType::DESKTOP_NATIVE_WIDGET_AURA, ¶ms, widget); #endif - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->Activate(); // SetupMenu leaves the mouse position where the first menu item will be
diff --git a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc index 967e8711..ba7b1e31 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.cc
@@ -49,7 +49,7 @@ RoundedOmniboxResultsFrame::OnBeforeWidgetInit(¶ms, this); - Init(params); + Init(std::move(params)); } void SetPopupContentsView(OmniboxPopupContentsView* contents) {
diff --git a/chrome/browser/ui/views/omnibox/omnibox_result_view_unittest.cc b/chrome/browser/ui/views/omnibox/omnibox_result_view_unittest.cc index 1751662..90b25af 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_result_view_unittest.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_result_view_unittest.cc
@@ -66,7 +66,7 @@ CreateParams(views::Widget::InitParams::TYPE_POPUP); init_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(init_params); + widget_->Init(std::move(init_params)); views::View* root_view = widget_->GetRootView(); root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
diff --git a/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc b/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc index 0cc2b2b..7e0ae94 100644 --- a/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc +++ b/chrome/browser/ui/views/omnibox/omnibox_view_views_unittest.cc
@@ -303,7 +303,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 400, 80); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); #if defined(OS_CHROMEOS) @@ -1161,7 +1161,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 100, 100); - other_widget->Init(params); + other_widget->Init(std::move(params)); other_widget->Show(); ExpectFullUrlDisplayed();
diff --git a/chrome/browser/ui/views/overlay/overlay_window_views.cc b/chrome/browser/ui/views/overlay/overlay_window_views.cc index 78086319..9c3b51a 100644 --- a/chrome/browser/ui/views/overlay/overlay_window_views.cc +++ b/chrome/browser/ui/views/overlay/overlay_window_views.cc
@@ -251,7 +251,7 @@ // Set WidgetDelegate for more control over |widget_|. params.delegate = new OverlayWindowWidgetDelegate(this); - Init(params); + Init(std::move(params)); SetUpViews(); #if defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/views/page_action/page_action_icon_view.cc b/chrome/browser/ui/views/page_action/page_action_icon_view.cc index c009ff7..046f216 100644 --- a/chrome/browser/ui/views/page_action/page_action_icon_view.cc +++ b/chrome/browser/ui/views/page_action/page_action_icon_view.cc
@@ -20,6 +20,7 @@ #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_mask.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" +#include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/focus_ring.h" #include "ui/views/style/platform_style.h" @@ -55,7 +56,8 @@ GetOmniboxStateOpacity(OmniboxPartState::SELECTED)); SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY); // Only shows bubble after mouse is released. - set_notify_action(NotifyAction::NOTIFY_ON_RELEASE); + button_controller()->set_notify_action( + views::ButtonController::NotifyAction::NOTIFY_ON_RELEASE); UpdateBorder(); }
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc index 185beca..cace8ce 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view_unittest.cc
@@ -187,7 +187,7 @@ views::Widget::InitParams parent_params; parent_params.context = views_helper_.GetContext(); parent_window_ = new views::Widget(); - parent_window_->Init(parent_params); + parent_window_->Init(std::move(parent_params)); content::WebContents* web_contents = web_contents_helper_.web_contents(); TabSpecificContentSettings::CreateForWebContents(web_contents);
diff --git a/chrome/browser/ui/views/page_info/safety_tip_page_info_bubble_view_unittest.cc b/chrome/browser/ui/views/page_info/safety_tip_page_info_bubble_view_unittest.cc index 55c9b26..7c17c84 100644 --- a/chrome/browser/ui/views/page_info/safety_tip_page_info_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/page_info/safety_tip_page_info_bubble_view_unittest.cc
@@ -47,7 +47,7 @@ views::Widget::InitParams parent_params; parent_params.context = views_helper_.GetContext(); parent_window_ = new views::Widget(); - parent_window_->Init(parent_params); + parent_window_->Init(std::move(parent_params)); content::WebContents* web_contents = web_contents_helper_.web_contents(); TabSpecificContentSettings::CreateForWebContents(web_contents);
diff --git a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc index b3f5af9..5fc83820 100644 --- a/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc +++ b/chrome/browser/ui/views/profiles/avatar_toolbar_button.cc
@@ -39,6 +39,7 @@ #include "ui/gfx/image/image.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/button/label_button_border.h" namespace { @@ -82,7 +83,8 @@ // Activate on press for left-mouse-button only to mimic other MenuButtons // without drag-drop actions (specifically the adjacent browser menu). - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + views::ButtonController::NOTIFY_ON_PRESS); set_triggerable_event_flags(ui::EF_LEFT_MOUSE_BUTTON); set_tag(IDC_SHOW_AVATAR_MENU);
diff --git a/chrome/browser/ui/views/profiles/user_manager_view.cc b/chrome/browser/ui/views/profiles/user_manager_view.cc index 93ad5ff8..2002d20 100644 --- a/chrome/browser/ui/views/profiles/user_manager_view.cc +++ b/chrome/browser/ui/views/profiles/user_manager_view.cc
@@ -397,7 +397,7 @@ views::Widget::InitParams params = GetDialogWidgetInitParams(this, nullptr, nullptr, bounds); - (new views::Widget)->Init(params); + (new views::Widget)->Init(std::move(params)); // Since the User Manager can be the only top level window, we don't // want to accidentally quit all of Chrome if the user is just trying to
diff --git a/chrome/browser/ui/views/screen_capture_notification_ui_views.cc b/chrome/browser/ui/views/screen_capture_notification_ui_views.cc index e66ede2..1e2d1ec 100644 --- a/chrome/browser/ui/views/screen_capture_notification_ui_views.cc +++ b/chrome/browser/ui/views/screen_capture_notification_ui_views.cc
@@ -207,7 +207,7 @@ #endif widget->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM); - widget->Init(params); + widget->Init(std::move(params)); SetBackground(views::CreateSolidBackground(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_DialogBackground)));
diff --git a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc index 8e23380..c23dda72 100644 --- a/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc +++ b/chrome/browser/ui/views/send_tab_to_self/send_tab_to_self_bubble_view_impl_unittest.cc
@@ -60,7 +60,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget_ = std::make_unique<views::Widget>(); - anchor_widget_->Init(params); + anchor_widget_->Init(std::move(params)); profile_.reset(new TestingProfile); controller_ = std::make_unique<SendTabToSelfBubbleControllerMock>();
diff --git a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view_unittest.cc b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view_unittest.cc index 86fa518..d2f42d3c 100644 --- a/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/sharing/click_to_call/click_to_call_dialog_view_unittest.cc
@@ -77,7 +77,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget_ = std::make_unique<views::Widget>(); - anchor_widget_->Init(params); + anchor_widget_->Init(std::move(params)); controller_ = std::make_unique<ClickToCallSharingDialogControllerMock>( web_contents_.get());
diff --git a/chrome/browser/ui/views/status_bubble_views.cc b/chrome/browser/ui/views/status_bubble_views.cc index 8b848a6..86c6093 100644 --- a/chrome/browser/ui/views/status_bubble_views.cc +++ b/chrome/browser/ui/views/status_bubble_views.cc
@@ -690,15 +690,16 @@ params.parent = frame->GetNativeView(); params.context = frame->GetNativeWindow(); params.name = "StatusBubble"; - popup_->Init(params); +#if defined(OS_CHROMEOS) + params.init_properties_container.SetProperty(ash::kHideInOverviewKey, true); + params.init_properties_container.SetProperty(ash::kHideInDeskMiniViewKey, + true); +#endif // defined(OS_CHROMEOS) + popup_->Init(std::move(params)); // We do our own animation and don't want any from the system. popup_->SetVisibilityChangedAnimationsEnabled(false); popup_->SetOpacity(0.f); popup_->SetContentsView(view_); -#if defined(OS_CHROMEOS) - popup_->GetNativeWindow()->SetProperty(ash::kHideInOverviewKey, true); - popup_->GetNativeWindow()->SetProperty(ash::kHideInDeskMiniViewKey, true); -#endif RepositionPopup(); } }
diff --git a/chrome/browser/ui/views/status_icons/status_icon_linux_x11.cc b/chrome/browser/ui/views/status_icons/status_icon_linux_x11.cc index f078708..58f1ae5 100644 --- a/chrome/browser/ui/views/status_icons/status_icon_linux_x11.cc +++ b/chrome/browser/ui/views/status_icons/status_icon_linux_x11.cc
@@ -103,7 +103,7 @@ // creating a compositor would only be wasteful of resources. params.force_software_compositing = true; - widget_->Init(params); + widget_->Init(std::move(params)); Window window = host_->GetAcceleratedWidget(); DCHECK(window);
diff --git a/chrome/browser/ui/views/subtle_notification_view.cc b/chrome/browser/ui/views/subtle_notification_view.cc index 15b769c0..750d106 100644 --- a/chrome/browser/ui/views/subtle_notification_view.cc +++ b/chrome/browser/ui/views/subtle_notification_view.cc
@@ -176,7 +176,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = parent_view; params.accept_events = false; - popup->Init(params); + popup->Init(std::move(params)); popup->SetContentsView(view); // We set layout manager to nullptr to prevent the widget from sizing its // contents to the same size as itself. This prevents the widget contents from
diff --git a/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc b/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc index 11135f1..b0c83d2 100644 --- a/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc +++ b/chrome/browser/ui/views/sync/one_click_signin_dialog_view_unittest.cc
@@ -34,7 +34,7 @@ anchor_widget_ = new views::Widget; views::Widget::InitParams widget_params = CreateParams(views::Widget::InitParams::TYPE_WINDOW); - anchor_widget_->Init(widget_params); + anchor_widget_->Init(std::move(widget_params)); anchor_widget_->Show(); }
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc index 46e1a67..bb7b46f 100644 --- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc
@@ -163,8 +163,8 @@ DISALLOW_COPY_AND_ASSIGN(TabHoverCardBubbleViewBrowserTest); }; -// Fails on win7 (dbg): http://crbug.com/932402. -#if defined(OS_WIN) && !defined(NDEBUG) +// Fails on win: http://crbug.com/932402. +#if defined(OS_WIN) #define MAYBE_InvokeUi_tab_hover_card DISABLED_InvokeUi_tab_hover_card #else #define MAYBE_InvokeUi_tab_hover_card InvokeUi_tab_hover_card
diff --git a/chrome/browser/ui/views/tabs/tab_strip.cc b/chrome/browser/ui/views/tabs/tab_strip.cc index 8732124..6b37b6f0 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.cc +++ b/chrome/browser/ui/views/tabs/tab_strip.cc
@@ -1871,34 +1871,6 @@ CompleteAnimationAndLayout(); } -bool TabStrip::OnMouseWheel(const ui::MouseWheelEvent& event) { - // Change the selected tab on horizontal wheel scrolls. - // Honor wheel scrolls over the tabs themselves, but not the NTB/surrounding - // space. - if ((!event.x_offset() && !event.IsShiftDown()) || tab_count() < 2 || - !FindTabHitByPoint(event.location())) - return false; - - accumulated_horizontal_scroll_ += - (event.x_offset() ? event.x_offset() : event.y_offset()); - - int horizontal_offset = - accumulated_horizontal_scroll_ / ui::MouseWheelEvent::kWheelDelta; - if (!horizontal_offset) - return true; - - accumulated_horizontal_scroll_ %= ui::MouseWheelEvent::kWheelDelta; - - int new_active_index = - (controller_->GetActiveIndex() + horizontal_offset) % tab_count(); - if (new_active_index < 0) - new_active_index += tab_count(); - - DCHECK(IsValidModelIndex(new_active_index)); - controller_->SelectTab(new_active_index, event); - return true; -} - void TabStrip::PaintChildren(const views::PaintInfo& paint_info) { // This is used to log to UMA. NO EARLY RETURNS! base::ElapsedTimer paint_timer; @@ -2747,7 +2719,7 @@ params.accept_events = false; params.bounds = gfx::Rect(g_drop_indicator_width, g_drop_indicator_height); params.context = context->GetNativeWindow(); - arrow_window->Init(params); + arrow_window->Init(std::move(params)); arrow_window->SetContentsView(arrow_view); }
diff --git a/chrome/browser/ui/views/tabs/tab_strip.h b/chrome/browser/ui/views/tabs/tab_strip.h index ceb6cd0..a052adc 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.h +++ b/chrome/browser/ui/views/tabs/tab_strip.h
@@ -282,7 +282,6 @@ // views::AccessiblePaneView: void Layout() override; - bool OnMouseWheel(const ui::MouseWheelEvent& event) override; void PaintChildren(const views::PaintInfo& paint_info) override; const char* GetClassName() const override; gfx::Size CalculatePreferredSize() const override; @@ -640,10 +639,6 @@ // Number of mouse moves. int mouse_move_count_ = 0; - // Accumulatated offsets from thumb wheel. Used to throttle horizontal - // scroll from thumb wheel. - int accumulated_horizontal_scroll_ = 0; - // Timer used when a tab is closed and we need to relayout. Only used when a // tab close comes from a touch device. base::OneShotTimer resize_layout_timer_;
diff --git a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc index 58ee660..74f7711 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc +++ b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc
@@ -147,7 +147,7 @@ init_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(parent); } @@ -975,52 +975,6 @@ EXPECT_EQ(first_tab, tab_strip_->GetEventHandlerForPoint(tab_center)); } -// Switch selected tabs on horizontal scroll events. -TEST_P(TabStripTest, HorizontalScroll) { - tab_strip_->SetBounds(0, 0, 200, 20); - - for (int i = 0; i < 3; i++) - controller_->AddTab(i, true /* is_active */); - - Tab* tab = tab_strip_->tab_at(0); - gfx::Point tab_center = tab->bounds().CenterPoint(); - - for (int i = 0; i < tab_strip_->tab_count(); ++i) { - ui::MouseWheelEvent wheel_event( - gfx::Vector2d(ui::MouseWheelEvent::kWheelDelta, 0), tab_center, - tab_center, ui::EventTimeForNow(), 0, 0); - tab_strip_->OnMouseWheel(wheel_event); - EXPECT_EQ(i, controller_->GetActiveIndex()); - } - - controller_->SelectTab(0, dummy_event_); - for (int i = tab_strip_->tab_count() - 1; i >= 0; --i) { - ui::MouseWheelEvent wheel_event( - gfx::Vector2d(-ui::MouseWheelEvent::kWheelDelta, 0), tab_center, - tab_center, ui::EventTimeForNow(), 0, 0); - tab_strip_->OnMouseWheel(wheel_event); - EXPECT_EQ(i, controller_->GetActiveIndex()); - } - - // When offset is smaller than kWheelDelta, we don't scroll immediately. - // We wait offset until accumulated offset gets bigger than kWheelDelta. - const int small_offset = ui::MouseWheelEvent::kWheelDelta / 3; - int next_accumulated_offset = small_offset; - while (next_accumulated_offset < ui::MouseWheelEvent::kWheelDelta) { - ui::MouseWheelEvent wheel_event(gfx::Vector2d(small_offset, 0), tab_center, - tab_center, ui::EventTimeForNow(), 0, 0); - tab_strip_->OnMouseWheel(wheel_event); - - EXPECT_EQ(0, controller_->GetActiveIndex()); - next_accumulated_offset += small_offset; - } - - ui::MouseWheelEvent wheel_event(gfx::Vector2d(small_offset, 0), tab_center, - tab_center, ui::EventTimeForNow(), 0, 0); - tab_strip_->OnMouseWheel(wheel_event); - EXPECT_EQ(1, controller_->GetActiveIndex()); -} - TEST_P(TabStripTest, AnimationOnTabAdd) { tab_strip_->SetBounds(0, 0, 1000, 100); // Show widget to enable animations.
diff --git a/chrome/browser/ui/views/tabs/tab_unittest.cc b/chrome/browser/ui/views/tabs/tab_unittest.cc index 137de91..f996184 100644 --- a/chrome/browser/ui/views/tabs/tab_unittest.cc +++ b/chrome/browser/ui/views/tabs/tab_unittest.cc
@@ -322,7 +322,7 @@ Widget::InitParams params(CreateParams(Widget::InitParams::TYPE_WINDOW)); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds.SetRect(10, 20, 300, 400); - widget->Init(params); + widget->Init(std::move(params)); } private: @@ -360,7 +360,7 @@ init_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 400, 400); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(&parent_); }
diff --git a/chrome/browser/ui/views/toolbar/toolbar_action_view_unittest.cc b/chrome/browser/ui/views/toolbar/toolbar_action_view_unittest.cc index d14e29d6..400e9fdc 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_action_view_unittest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_action_view_unittest.cc
@@ -107,7 +107,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); } void TearDown() override {
diff --git a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc index 6db55858..c021fe36 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_actions_bar_bubble_views_unittest.cc
@@ -52,7 +52,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - anchor_widget->Init(params); + anchor_widget->Init(std::move(params)); anchor_widget->Show(); return anchor_widget; }
diff --git a/chrome/browser/ui/views/toolbar/toolbar_button_unittest.cc b/chrome/browser/ui/views/toolbar/toolbar_button_unittest.cc index 69b42aae..611048ba 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_button_unittest.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_button_unittest.cc
@@ -66,7 +66,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = context; widget_ = std::make_unique<views::Widget>(); - widget_->Init(params); + widget_->Init(std::move(params)); } ~TestParentView() override = default;
diff --git a/chrome/browser/ui/views/translate/translate_bubble_view_unittest.cc b/chrome/browser/ui/views/translate/translate_bubble_view_unittest.cc index e3f9ea3..acc1034 100644 --- a/chrome/browser/ui/views/translate/translate_bubble_view_unittest.cc +++ b/chrome/browser/ui/views/translate/translate_bubble_view_unittest.cc
@@ -163,7 +163,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; anchor_widget_.reset(new views::Widget()); - anchor_widget_->Init(params); + anchor_widget_->Init(std::move(params)); anchor_widget_->Show(); mock_model_ = new MockTranslateBubbleModel(
diff --git a/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.cc b/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.cc index 07a76c2..9ee19606 100644 --- a/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.cc +++ b/chrome/browser/ui/views/try_chrome_dialog_win/try_chrome_dialog.cc
@@ -1039,7 +1039,7 @@ params.name = "TryChromeDialog"; popup_ = new views::Widget; popup_->AddObserver(this); - popup_->Init(params); + popup_->Init(std::move(params)); auto contents_view = std::make_unique<ClickableView>(); contents_view->SetBackground(
diff --git a/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc b/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc index 6fcd5cd..ce6790a8e 100644 --- a/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc +++ b/chrome/browser/ui/webui/chromeos/system_web_dialog_delegate.cc
@@ -162,8 +162,9 @@ if (!parent && GetDialogModalType() == ui::MODAL_TYPE_NONE) extra_params.z_order = ui::ZOrderLevel::kFloatingWindow; AdjustWidgetInitParams(&extra_params); - dialog_window_ = chrome::ShowWebDialogWithParams(parent, browser_context, - this, &extra_params); + dialog_window_ = chrome::ShowWebDialogWithParams( + parent, browser_context, this, + base::make_optional<views::Widget::InitParams>(std::move(extra_params))); } void SystemWebDialogDelegate::ShowSystemDialog(gfx::NativeWindow parent) {
diff --git a/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chrome/browser/ui/webui/settings/search_engines_handler.cc index 24247be5..4a32018 100644 --- a/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chrome/browser/ui/webui/settings/search_engines_handler.cc
@@ -195,8 +195,8 @@ "keyword", table_model->GetText(index, IDS_SEARCH_ENGINES_EDITOR_KEYWORD_COLUMN)); Profile* profile = Profile::FromWebUI(web_ui()); - dict->SetString("url", template_url->url_ref().DisplayURL( - UIThreadSearchTermsData(profile))); + dict->SetString( + "url", template_url->url_ref().DisplayURL(UIThreadSearchTermsData())); dict->SetBoolean("urlLocked", template_url->prepopulate_id() > 0); GURL icon_url = template_url->favicon_url(); if (icon_url.is_valid())
diff --git a/chrome/browser/vr/OWNERS b/chrome/browser/vr/OWNERS index d7d4c40..5a930f06 100644 --- a/chrome/browser/vr/OWNERS +++ b/chrome/browser/vr/OWNERS
@@ -5,7 +5,6 @@ # WebXR-related. klausw@chromium.org -billorr@chromium.org # Browser Test-related. bsheedy@chromium.org
diff --git a/chrome/browser/vr/service/OWNERS b/chrome/browser/vr/service/OWNERS index bff1dd1a..ca0010e0 100644 --- a/chrome/browser/vr/service/OWNERS +++ b/chrome/browser/vr/service/OWNERS
@@ -1,5 +1,4 @@ alcooper@chromium.org -billorr@chromium.org # TEAM: xr-dev@chromium.org # COMPONENT: Blink>WebXR
diff --git a/chrome/browser/web_launch/web_launch_files_helper.cc b/chrome/browser/web_launch/web_launch_files_helper.cc index 452fc4d..118839e7 100644 --- a/chrome/browser/web_launch/web_launch_files_helper.cc +++ b/chrome/browser/web_launch/web_launch_files_helper.cc
@@ -88,7 +88,7 @@ ->GetNativeFileSystemEntryFactory(); content::NativeFileSystemEntryFactory::BindingContext context( - url::Origin::Create(launch_url), + url::Origin::Create(launch_url), launch_url, web_contents->GetMainFrame()->GetProcess()->GetID(), web_contents->GetMainFrame()->GetRoutingID());
diff --git a/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc b/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc index 471ab9a..29fede5 100644 --- a/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc +++ b/chrome/chrome_cleaner/executables/chrome_cleaner_main.cc
@@ -47,7 +47,7 @@ #include "chrome/chrome_cleaner/engines/target/engine_delegate_factory.h" #include "chrome/chrome_cleaner/engines/target/sandbox_setup.h" #include "chrome/chrome_cleaner/executables/shutdown_sequence.h" -#include "chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h" +#include "chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h" #include "chrome/chrome_cleaner/ipc/mojo_task_runner.h" #include "chrome/chrome_cleaner/ipc/sandbox.h" #include "chrome/chrome_cleaner/logging/logging_service_api.h" @@ -437,6 +437,16 @@ const chrome_cleaner::Settings* settings = chrome_cleaner::Settings::GetInstance(); + if (settings->execution_mode() == ExecutionMode::kNone) { + ::MessageBox(nullptr, + L"Manually running this program is no longer supported. " + L"Please visit " + L"https://support.google.com/chrome/?p=chrome_cleanup_tool " + L"for more information.", + L"Error", MB_OK | MB_ICONERROR | MB_TOPMOST); + return chrome_cleaner::RESULT_CODE_MANUAL_EXECUTION_BY_USER; + } + // Process priority modification has to be done before threads are created // because they inherit process' priority. if (settings->execution_mode() == ExecutionMode::kScanning) { @@ -575,22 +585,29 @@ // Only create the IPC if both the Mojo pipe token and the parent pipe handle // have been sent by Chrome. If either switch is not present, it will not be // connected to the parent process. + // This pointer is leaked, in order to simplify this object's lifetime. chrome_cleaner::ChromePromptIPC* chrome_prompt_ipc = nullptr; + if (settings->execution_mode() == ExecutionMode::kScanning) { - // Scanning mode is only used by Chrome and all necessary mojo pipe flags + // Scanning mode is only used by Chrome and all necessary IPC flags // must have been passed on the command line. - if (settings->chrome_mojo_pipe_token().empty() || - !settings->has_parent_pipe_handle()) { + if (!settings->switches_valid_for_ipc()) { return ReturnWithResultCode( chrome_cleaner::RESULT_CODE_INVALID_IPC_SWITCHES, executable_path, ®istry_logger, rebooter.get()); } - const std::string chrome_mojo_pipe_token = - settings->chrome_mojo_pipe_token(); - // This pointer is leaked, in order to simplify this object's lifetime. - chrome_prompt_ipc = new chrome_cleaner::ChromePromptIPC( - chrome_mojo_pipe_token, shutdown_sequence.mojo_task_runner); + if (settings->prompt_using_mojo()) { + chrome_prompt_ipc = new chrome_cleaner::MojoChromePromptIPC( + settings->chrome_mojo_pipe_token(), + shutdown_sequence.mojo_task_runner); + } else { + // Proto prompt support is not complete yet so only mojo is supported. + return ReturnWithResultCode( + chrome_cleaner::RESULT_CODE_INVALID_IPC_SWITCHES, executable_path, + ®istry_logger, rebooter.get()); + } + } else if (!settings->chrome_mojo_pipe_token().empty() || settings->has_parent_pipe_handle()) { return ReturnWithResultCode( @@ -598,16 +615,6 @@ executable_path, ®istry_logger, rebooter.get()); } - if (settings->execution_mode() == ExecutionMode::kNone) { - ::MessageBox(NULL, - L"Manually running this program is no longer supported. " - L"Please visit " - L"https://support.google.com/chrome/?p=chrome_cleanup_tool " - L"for more information.", - L"Error", MB_OK | MB_ICONERROR | MB_TOPMOST); - return chrome_cleaner::RESULT_CODE_MANUAL_EXECUTION_BY_USER; - } - // If immediate elevation is not required, the process will restart elevated // after the user accepts to run cleanup. if (settings->execution_mode() != ExecutionMode::kScanning &&
diff --git a/chrome/chrome_cleaner/ipc/BUILD.gn b/chrome/chrome_cleaner/ipc/BUILD.gn index a1f7f331..18572cc 100644 --- a/chrome/chrome_cleaner/ipc/BUILD.gn +++ b/chrome/chrome_cleaner/ipc/BUILD.gn
@@ -19,6 +19,8 @@ sources = [ "chrome_prompt_ipc.cc", "chrome_prompt_ipc.h", + "mojo_chrome_prompt_ipc.cc", + "mojo_chrome_prompt_ipc.h", ] deps = [
diff --git a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.cc b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.cc index ec492e4d8..944ab4d 100644 --- a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.cc +++ b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.cc
@@ -4,219 +4,10 @@ #include "chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h" -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "base/sequenced_task_runner.h" -#include "base/threading/sequenced_task_runner_handle.h" -#include "mojo/public/cpp/platform/platform_channel.h" -#include "mojo/public/cpp/system/invitation.h" -#include "mojo/public/cpp/system/message_pipe.h" - namespace chrome_cleaner { -namespace { +ChromePromptIPC::ChromePromptIPC() = default; -void OnTryDeleteExtensionsCallback( - base::OnceClosure delete_allowed_callback, - base::OnceClosure delete_not_allowed_callback, - uint32_t version) { - if (version >= 3) { - std::move(delete_allowed_callback).Run(); - } else { - std::move(delete_not_allowed_callback).Run(); - } -} - -} // namespace - -ChromePromptIPC::ChromePromptIPC(const std::string& chrome_mojo_pipe_token, - scoped_refptr<MojoTaskRunner> task_runner) - : task_runner_(std::move(task_runner)), - chrome_mojo_pipe_token_(chrome_mojo_pipe_token) { - // Accesses to |state_| must happen on |task_runner_|'s sequence, which is - // not the construction sequence. - DETACH_FROM_SEQUENCE(sequence_checker_); -} - -void ChromePromptIPC::Initialize(ErrorHandler* error_handler) { - DCHECK(!chrome_mojo_pipe_token_.empty()); - DCHECK(task_runner_); - - error_handler_ = error_handler; - - // No need to retain this object, since it will live until the process - // finishes. - task_runner_->PostTask( - FROM_HERE, base::BindOnce(&ChromePromptIPC::InitializeChromePromptPtr, - base::Unretained(this))); -} - -ChromePromptIPC::~ChromePromptIPC() { - // This object is only destroyed when the cleaner process ends. At this point - // we don't need to close the IPC, since the broken connection message will - // be received by Chrome anyway, and we can simply leak the pointer. - chrome_prompt_service_.release(); // Leaked. -} - -void ChromePromptIPC::PostPromptUserTask( - const std::vector<base::FilePath>& files_to_delete, - const std::vector<base::string16>& registry_keys, - const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::PromptUserCallback callback) { - DCHECK(task_runner_); - task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &ChromePromptIPC::RunPromptUserTask, base::Unretained(this), - files_to_delete, registry_keys, extension_ids, - base::BindOnce(&ChromePromptIPC::OnChromeResponseReceived, - base::Unretained(this), std::move(callback)))); -} - -void ChromePromptIPC::PostDisableExtensionsTask( - const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::DisableExtensionsCallback callback) { - DCHECK(task_runner_); - task_runner_->PostTask( - FROM_HERE, - base::BindOnce( - &ChromePromptIPC::RunDisableExtensionsTask, base::Unretained(this), - extension_ids, - base::BindOnce(&ChromePromptIPC::OnChromeResponseReceivedExtensions, - base::Unretained(this), std::move(callback)))); -} - -void ChromePromptIPC::TryDeleteExtensions( - base::OnceClosure delete_allowed_callback, - base::OnceClosure delete_not_allowed_callback) { - const auto& version_callback = base::BindRepeating( - &chrome_cleaner::OnTryDeleteExtensionsCallback, - AdaptCallbackForRepeating(std::move(delete_allowed_callback)), - AdaptCallbackForRepeating(std::move(delete_not_allowed_callback))); - - (*chrome_prompt_service_).QueryVersion(std::move(version_callback)); -} - -void ChromePromptIPC::OnChromeResponseReceived( - mojom::ChromePrompt::PromptUserCallback callback, - mojom::PromptAcceptance prompt_acceptance) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(State::kWaitingForResponseFromChrome, state_); - - state_ = State::kDoneInteraction; - std::move(callback).Run(prompt_acceptance); -} - -void ChromePromptIPC::OnChromeResponseReceivedExtensions( - mojom::ChromePrompt::DisableExtensionsCallback callback, - bool extensions_disabled_callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(State::kDoneInteraction, state_); - - std::move(callback).Run(extensions_disabled_callback); -} - -void ChromePromptIPC::OnConnectionError() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_NE(State::kUninitialized, state_); - - if (!error_handler_) - return; - - if (state_ == State::kDoneInteraction) { - error_handler_->OnConnectionClosedAfterDone(); - } else { - state_ = State::kDoneInteraction; - error_handler_->OnConnectionClosed(); - } -} - -void ChromePromptIPC::InitializeChromePromptPtr() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(State::kUninitialized, state_); - - auto channel_endpoint = - mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( - *base::CommandLine::ForCurrentProcess()); - auto incoming_invitation = - mojo::IncomingInvitation::Accept(std::move(channel_endpoint)); - - mojo::ScopedMessagePipeHandle message_pipe_handle = - incoming_invitation.ExtractMessagePipe(chrome_mojo_pipe_token_); - - chrome_prompt_service_.reset(new chrome_cleaner::mojom::ChromePromptPtr); - chrome_prompt_service_->Bind(chrome_cleaner::mojom::ChromePromptPtrInfo( - std::move(message_pipe_handle), 0)); - // No need to retain this object, since it will live until the process - // finishes. - chrome_prompt_service_->set_connection_error_handler(base::BindOnce( - &ChromePromptIPC::OnConnectionError, base::Unretained(this))); - state_ = State::kWaitingForScanResults; -} - -void ChromePromptIPC::PromptUserCheckVersion( - const std::vector<base::FilePath>& files_to_delete, - const std::vector<base::string16>& registry_keys, - const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::PromptUserCallback callback, - uint32_t version) { - if (version >= 3) { - (*chrome_prompt_service_) - ->PromptUser(std::move(files_to_delete), std::move(registry_keys), - std::move(extension_ids), std::move(callback)); - } else { - // Before version 3 the delete extensions interface wasn't implemented. - // So we need to not notify the user that there are extensions to be - // deleted. - (*chrome_prompt_service_) - ->PromptUser(std::move(files_to_delete), std::move(registry_keys), - base::nullopt, std::move(callback)); - } -} - -void ChromePromptIPC::RunPromptUserTask( - const std::vector<base::FilePath>& files_to_delete, - const std::vector<base::string16>& registry_keys, - const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::PromptUserCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(chrome_prompt_service_); - DCHECK(state_ != State::kUninitialized); - DCHECK(state_ != State::kWaitingForResponseFromChrome); - - // This is a corner case, in which we receive the disconnect message on the - // IPC thread right before this task is posted. In that case, this function - // will be a no-op. - if (state_ == State::kDoneInteraction) - return; - - state_ = State::kWaitingForResponseFromChrome; - - const auto& version_callback = base::BindRepeating( - &ChromePromptIPC::PromptUserCheckVersion, base::Unretained(this), - std::move(files_to_delete), std::move(registry_keys), - // Uses the AdaptCallbackForRepeating because we are bound by the mojo API - // to use a RepeatingCallback even though this only should be called once. - std::move(extension_ids), AdaptCallbackForRepeating(std::move(callback))); - (*chrome_prompt_service_).QueryVersion(version_callback); -} - -void ChromePromptIPC::RunDisableExtensionsTask( - const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::DisableExtensionsCallback callback) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(chrome_prompt_service_); - DCHECK(state_ == State::kDoneInteraction); - - (*chrome_prompt_service_) - ->DisableExtensions(std::move(extension_ids), std::move(callback)); -} +ChromePromptIPC::~ChromePromptIPC() = default; } // namespace chrome_cleaner
diff --git a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h index a059178..ad216e5 100644 --- a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h +++ b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h
@@ -5,44 +5,25 @@ #ifndef CHROME_CHROME_CLEANER_IPC_CHROME_PROMPT_IPC_H_ #define CHROME_CHROME_CLEANER_IPC_CHROME_PROMPT_IPC_H_ -#include <memory> #include <string> #include <vector> #include "base/callback_forward.h" -#include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "base/strings/string16.h" -#include "base/threading/thread.h" -#include "chrome/chrome_cleaner/ipc/mojo_task_runner.h" + +// This is kept in the base class for now to provide access to mojom enums which +// will be used in all classes. #include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" namespace chrome_cleaner { -// Simple wrapper to control lifetime of the ChromePromptPtr object and post -// tasks in the IPC thread kept by the MojoTaskRunner. Once created, this -// object lives until the cleaner process ends. -// -// Simple usage: -// scoped_refptr<MojoTaskRunner> task_runner = MojoTaskRunner::Create(); -// const std::string chrome_mojo_pipe_token = -// Settings::GetInstance()->chrome_mojo_pipe_token(); -// ChromePromptIPC* chrome_prompt_ipc = -// new ChromePromptIPC(chrome_mojo_pipe_token, task_runner); -// ChromePromptIPC::ErrorHandler error_handler = ...; -// chrome_prompt_ipc->Initialize(&error_handler); -// ... -// std::vector<base::FilePath> files_to_delete = ...; -// std::vector<base::string16> registry_keys = ...; -// chrome_prompt_ipc->PostPromptUserTask( -// files_to_delete, registry_keys, -// base::BindOnce(&ReceivePromptResult)); -// -// void ReceivePromptResult(mojom::PromptAcceptance prompt_acceptance) { -// ... -// } +// Defines the interface necessary to connect the "ui" and Chrome. The choice of +// IPC mechanism is left to the child classes. class ChromePromptIPC { public: + ChromePromptIPC(); + // Interface for connection error handling, which can change depending on the // context objects of this class are used, such as in the main cleaner or in // tests. Methods of this class will be called on the IPC controller's @@ -61,13 +42,10 @@ virtual void OnConnectionClosedAfterDone() = 0; }; - ChromePromptIPC(const std::string& chrome_mojo_pipe_token, - scoped_refptr<MojoTaskRunner> task_runner); - - // Initializes |chrome_prompt_service_| in the IPC controller's thread and - // sets |error_handler| as the connection error handler. This object doesn't - // own the error handler pointer. - virtual void Initialize(ErrorHandler* error_handler); + // Sets |error_handler| as the connection error handler and completes whatever + // initialization that needs to be done separately from construction. This + // object doesn't own the error handler pointer. + virtual void Initialize(ErrorHandler* error_handler) = 0; // Posts a PromptUser() task to the IPC controller's thread. Internal state // must be State:kWaitingForScanResults when the posted task runs. Once the @@ -78,28 +56,23 @@ const std::vector<base::FilePath>& files_to_delete, const std::vector<base::string16>& registry_keys, const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::PromptUserCallback callback); + mojom::ChromePrompt::PromptUserCallback callback) = 0; // Posts a PromptDisableExtensions() task to the IPC controller's thread. // Internal state must be State::kDoneInteraction when the posted task runs. virtual void PostDisableExtensionsTask( const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::DisableExtensionsCallback callback); + mojom::ChromePrompt::DisableExtensionsCallback callback) = 0; - // Queries Chrome for its version of the ChromePrompt interface. If version - // >= 3 calls |delete_allowed_callback|. Calls |delete_not_allowed_callback| - // otherwise. + // Calls |delete_allowed_callback| if the IPC version supports deleting + // extensions, |delete_not_allowed_callback| otherwise. virtual void TryDeleteExtensions( base::OnceClosure delete_allowed_callback, - base::OnceClosure delete_not_allowed_callback); + base::OnceClosure delete_not_allowed_callback) = 0; protected: - // The destructor is only called by tests for doubles of this class. In the - // cleaner, this object leaks, so we don't bother closing the connection - // (Chrome will receive the signal anyway once the cleaner process ends). virtual ~ChromePromptIPC(); - private: enum class State { // The IPC has not been initialized. kUninitialized, @@ -112,52 +85,43 @@ kDoneInteraction, }; - // Initializes |chrome_prompt_service_| and sets the connection error - // handler. This must be executed in the IPC controller's thread. - void InitializeChromePromptPtr(); - - // Runs |chrome_prompt_service_->PromptUser()|. Must be called on the IPC - // thread. virtual void RunPromptUserTask( const std::vector<base::FilePath>& files_to_delete, const std::vector<base::string16>& registry_keys, const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::PromptUserCallback callback); + mojom::ChromePrompt::PromptUserCallback callback) = 0; virtual void RunDisableExtensionsTask( const std::vector<base::string16>& extension_ids, - mojom::ChromePrompt::DisableExtensionsCallback callback); + mojom::ChromePrompt::DisableExtensionsCallback callback) = 0; // Callback for ChromePrompt::PromptUser, internal state must be // State::kWaitingForResponseFromChrome. Invokes callback(prompt_acceptance) // and transitions to state State::kDoneInteraction. - void OnChromeResponseReceived( + virtual void OnChromeResponseReceived( mojom::ChromePrompt::PromptUserCallback callback, - mojom::PromptAcceptance prompt_acceptance); + mojom::PromptAcceptance prompt_acceptance) = 0; // Callback for ChromePrompt::DisableExtensions, internal state must be // State::kDoneInteraction. Invokes callback(extensions_deleted_callback). - void OnChromeResponseReceivedExtensions( + virtual void OnChromeResponseReceivedExtensions( mojom::ChromePrompt::DisableExtensionsCallback callback, - bool extensions_deleted_callback); + bool extensions_deleted_callback) = 0; // Connection error handler. Invokes either // error_handler_->OnConnectionClosed() or // error_handler_->OnConnectionClosedAfterDone(), depending on the internal // state. - void OnConnectionError(); + virtual void OnConnectionError() = 0; - void PromptUserCheckVersion( + virtual void PromptUserCheckVersion( const std::vector<base::FilePath>& files_to_delete, const std::vector<base::string16>& registry_keys, const std::vector<base::string16>& extension_ids, mojom::ChromePrompt::PromptUserCallback callback, - uint32_t version); + uint32_t version) = 0; State state_ = State::kUninitialized; - scoped_refptr<MojoTaskRunner> task_runner_; - std::string chrome_mojo_pipe_token_; - std::unique_ptr<mojom::ChromePromptPtr> chrome_prompt_service_; ErrorHandler* error_handler_ = nullptr; // Ensures that all accesses to state_ after initialization are done on the
diff --git a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc_unittest.cc b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc_unittest.cc index ad3f1bd..88206d8 100644 --- a/chrome/chrome_cleaner/ipc/chrome_prompt_ipc_unittest.cc +++ b/chrome/chrome_cleaner/ipc/chrome_prompt_ipc_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/chrome_cleaner/ipc/chrome_prompt_ipc.h" +#include "chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h" #include <memory> #include <tuple> @@ -308,8 +308,8 @@ }), on_done_run_loop.QuitClosure()); - ChromePromptIPC* chrome_prompt_ipc = - new ChromePromptIPC(child_process->mojo_pipe_token(), mojo_task_runner); + ChromePromptIPC* chrome_prompt_ipc = new MojoChromePromptIPC( + child_process->mojo_pipe_token(), mojo_task_runner); chrome_prompt_ipc->Initialize(&error_handler); if (child_process->expected_parent_disconnected() ==
diff --git a/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.cc b/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.cc index 25535b3..187191c3 100644 --- a/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.cc +++ b/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.cc
@@ -9,7 +9,7 @@ namespace chrome_cleaner { MockChromePromptIPC::MockChromePromptIPC() - : ChromePromptIPC(std::string(), nullptr) {} + : MojoChromePromptIPC(std::string(), nullptr) {} MockChromePromptIPC::~MockChromePromptIPC() = default;
diff --git a/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.h b/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.h index 6f3f771c..77b5bd7 100644 --- a/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.h +++ b/chrome/chrome_cleaner/ipc/mock_chrome_prompt_ipc.h
@@ -8,13 +8,13 @@ #include <memory> #include <vector> -#include "chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h" +#include "chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h" #include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" #include "testing/gmock/include/gmock/gmock.h" namespace chrome_cleaner { -class MockChromePromptIPC : public ChromePromptIPC { +class MockChromePromptIPC : public MojoChromePromptIPC { public: MockChromePromptIPC(); ~MockChromePromptIPC() override;
diff --git a/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.cc b/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.cc new file mode 100644 index 0000000..16f5f9b --- /dev/null +++ b/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.cc
@@ -0,0 +1,224 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h" + +#include <utility> + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback_helpers.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/sequenced_task_runner.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "mojo/public/cpp/platform/platform_channel.h" +#include "mojo/public/cpp/system/invitation.h" +#include "mojo/public/cpp/system/message_pipe.h" + +namespace chrome_cleaner { + +namespace { + +void OnTryDeleteExtensionsCallback( + base::OnceClosure delete_allowed_callback, + base::OnceClosure delete_not_allowed_callback, + uint32_t version) { + if (version >= 3) { + std::move(delete_allowed_callback).Run(); + } else { + std::move(delete_not_allowed_callback).Run(); + } +} + +} // namespace + +MojoChromePromptIPC::MojoChromePromptIPC( + const std::string& chrome_mojo_pipe_token, + scoped_refptr<MojoTaskRunner> task_runner) + : task_runner_(std::move(task_runner)), + chrome_mojo_pipe_token_(chrome_mojo_pipe_token) { + // Accesses to |state_| must happen on |task_runner_|'s sequence, which is + // not the construction sequence. + DETACH_FROM_SEQUENCE(sequence_checker_); +} + +void MojoChromePromptIPC::Initialize(ErrorHandler* error_handler) { + DCHECK(!chrome_mojo_pipe_token_.empty()); + DCHECK(task_runner_); + + error_handler_ = error_handler; + + // No need to retain this object, since it will live until the process + // finishes. + task_runner_->PostTask( + FROM_HERE, base::BindOnce(&MojoChromePromptIPC::InitializeChromePromptPtr, + base::Unretained(this))); +} + +MojoChromePromptIPC::~MojoChromePromptIPC() { + // This object is only destroyed when the cleaner process ends. At this point + // we don't need to close the IPC, since the broken connection message will + // be received by Chrome anyway, and we can simply leak the pointer. + chrome_prompt_service_.release(); // Leaked. +} + +void MojoChromePromptIPC::PostPromptUserTask( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback) { + DCHECK(task_runner_); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &MojoChromePromptIPC::RunPromptUserTask, base::Unretained(this), + files_to_delete, registry_keys, extension_ids, + base::BindOnce(&MojoChromePromptIPC::OnChromeResponseReceived, + base::Unretained(this), std::move(callback)))); +} + +void MojoChromePromptIPC::PostDisableExtensionsTask( + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::DisableExtensionsCallback callback) { + DCHECK(task_runner_); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &MojoChromePromptIPC::RunDisableExtensionsTask, + base::Unretained(this), extension_ids, + base::BindOnce( + &MojoChromePromptIPC::OnChromeResponseReceivedExtensions, + base::Unretained(this), std::move(callback)))); +} + +void MojoChromePromptIPC::TryDeleteExtensions( + base::OnceClosure delete_allowed_callback, + base::OnceClosure delete_not_allowed_callback) { + const auto& version_callback = base::BindRepeating( + &chrome_cleaner::OnTryDeleteExtensionsCallback, + AdaptCallbackForRepeating(std::move(delete_allowed_callback)), + AdaptCallbackForRepeating(std::move(delete_not_allowed_callback))); + + (*chrome_prompt_service_).QueryVersion(std::move(version_callback)); +} + +void MojoChromePromptIPC::OnChromeResponseReceived( + mojom::ChromePrompt::PromptUserCallback callback, + mojom::PromptAcceptance prompt_acceptance) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_EQ(State::kWaitingForResponseFromChrome, state_); + + state_ = State::kDoneInteraction; + std::move(callback).Run(prompt_acceptance); +} + +void MojoChromePromptIPC::OnChromeResponseReceivedExtensions( + mojom::ChromePrompt::DisableExtensionsCallback callback, + bool extensions_disabled_callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_EQ(State::kDoneInteraction, state_); + + std::move(callback).Run(extensions_disabled_callback); +} + +void MojoChromePromptIPC::OnConnectionError() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_NE(State::kUninitialized, state_); + + if (!error_handler_) + return; + + if (state_ == State::kDoneInteraction) { + error_handler_->OnConnectionClosedAfterDone(); + } else { + state_ = State::kDoneInteraction; + error_handler_->OnConnectionClosed(); + } +} + +void MojoChromePromptIPC::InitializeChromePromptPtr() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_EQ(State::kUninitialized, state_); + + auto channel_endpoint = + mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( + *base::CommandLine::ForCurrentProcess()); + auto incoming_invitation = + mojo::IncomingInvitation::Accept(std::move(channel_endpoint)); + + mojo::ScopedMessagePipeHandle message_pipe_handle = + incoming_invitation.ExtractMessagePipe(chrome_mojo_pipe_token_); + + chrome_prompt_service_.reset(new chrome_cleaner::mojom::ChromePromptPtr); + chrome_prompt_service_->Bind(chrome_cleaner::mojom::ChromePromptPtrInfo( + std::move(message_pipe_handle), 0)); + // No need to retain this object, since it will live until the process + // finishes. + chrome_prompt_service_->set_connection_error_handler(base::BindOnce( + &MojoChromePromptIPC::OnConnectionError, base::Unretained(this))); + state_ = State::kWaitingForScanResults; +} + +void MojoChromePromptIPC::PromptUserCheckVersion( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback, + uint32_t version) { + if (version >= 3) { + (*chrome_prompt_service_) + ->PromptUser(std::move(files_to_delete), std::move(registry_keys), + std::move(extension_ids), std::move(callback)); + } else { + // Before version 3 the delete extensions interface wasn't implemented. + // So we need to not notify the user that there are extensions to be + // deleted. + (*chrome_prompt_service_) + ->PromptUser(std::move(files_to_delete), std::move(registry_keys), + base::nullopt, std::move(callback)); + } +} + +void MojoChromePromptIPC::RunPromptUserTask( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(chrome_prompt_service_); + DCHECK(state_ != State::kUninitialized); + DCHECK(state_ != State::kWaitingForResponseFromChrome); + + // This is a corner case, in which we receive the disconnect message on the + // IPC thread right before this task is posted. In that case, this function + // will be a no-op. + if (state_ == State::kDoneInteraction) + return; + + state_ = State::kWaitingForResponseFromChrome; + + const auto& version_callback = base::BindRepeating( + &MojoChromePromptIPC::PromptUserCheckVersion, base::Unretained(this), + std::move(files_to_delete), std::move(registry_keys), + // Uses the AdaptCallbackForRepeating because we are bound by the mojo API + // to use a RepeatingCallback even though this only should be called once. + std::move(extension_ids), AdaptCallbackForRepeating(std::move(callback))); + (*chrome_prompt_service_).QueryVersion(version_callback); +} + +void MojoChromePromptIPC::RunDisableExtensionsTask( + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::DisableExtensionsCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(chrome_prompt_service_); + DCHECK(state_ == State::kDoneInteraction); + + (*chrome_prompt_service_) + ->DisableExtensions(std::move(extension_ids), std::move(callback)); +} + +} // namespace chrome_cleaner
diff --git a/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h b/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h new file mode 100644 index 0000000..be2d66b --- /dev/null +++ b/chrome/chrome_cleaner/ipc/mojo_chrome_prompt_ipc.h
@@ -0,0 +1,134 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_CHROME_CLEANER_IPC_MOJO_CHROME_PROMPT_IPC_H_ +#define CHROME_CHROME_CLEANER_IPC_MOJO_CHROME_PROMPT_IPC_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "base/callback_forward.h" +#include "base/memory/ref_counted.h" +#include "base/sequence_checker.h" +#include "base/strings/string16.h" +#include "chrome/chrome_cleaner/ipc/chrome_prompt_ipc.h" +#include "chrome/chrome_cleaner/ipc/mojo_task_runner.h" +#include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" + +namespace chrome_cleaner { + +// Simple wrapper to control lifetime of the ChromePromptPtr object and post +// tasks in the IPC thread kept by the MojoTaskRunner. Once created, this +// object lives until the cleaner process ends. +// +// Sample usage: +// scoped_refptr<MojoTaskRunner> task_runner = MojoTaskRunner::Create(); +// const std::string chrome_mojo_pipe_token = +// Settings::GetInstance()->chrome_mojo_pipe_token(); +// ChromePromptIPC* chrome_prompt_ipc = +// new MojoChromePromptIPC(chrome_mojo_pipe_token, task_runner); +// ChromePromptIPC::ErrorHandler error_handler = ...; +// chrome_prompt_ipc->Initialize(&error_handler); +// ... +// std::vector<base::FilePath> files_to_delete = ...; +// std::vector<base::string16> registry_keys = ...; +// chrome_prompt_ipc->PostPromptUserTask( +// files_to_delete, registry_keys, +// base::BindOnce(&ReceivePromptResult)); +// +// void ReceivePromptResult(mojom::PromptAcceptance prompt_acceptance) { +// ... +// } +class MojoChromePromptIPC : public ChromePromptIPC { + public: + MojoChromePromptIPC(const std::string& chrome_mojo_pipe_token, + scoped_refptr<MojoTaskRunner> task_runner); + + // Initializes |chrome_prompt_service_| in the IPC controller's thread and + // sets |error_handler| as the connection error handler. This object doesn't + // own the error handler pointer. + void Initialize(ChromePromptIPC::ErrorHandler* error_handler) override; + + // Posts a PromptUser() task to the IPC controller's thread. Internal state + // must be State:kWaitingForScanResults when the posted task runs. Once the + // response from Chrome is received, |callback| will run on the IPC + // controller's thread; clients of this class are responsible for posting + // response on the right thread. + void PostPromptUserTask( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback) override; + + // Posts a PromptDisableExtensions() task to the IPC controller's thread. + // Internal state must be State::kDoneInteraction when the posted task runs. + void PostDisableExtensionsTask( + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::DisableExtensionsCallback callback) override; + + // Queries Chrome for its version of the ChromePrompt interface. If version + // >= 3 calls |delete_allowed_callback|. Calls |delete_not_allowed_callback| + // otherwise. + void TryDeleteExtensions( + base::OnceClosure delete_allowed_callback, + base::OnceClosure delete_not_allowed_callback) override; + + protected: + // The destructor is only called by tests for doubles of this class. In the + // cleaner, this object leaks, so we don't bother closing the connection + // (Chrome will receive the signal anyway once the cleaner process ends). + ~MojoChromePromptIPC() override; + + // Initializes |chrome_prompt_service_| and sets the connection error + // handler. This must be executed in the IPC controller's thread. + void InitializeChromePromptPtr(); + + // Runs |chrome_prompt_service_->PromptUser()|. Must be called on the IPC + // thread. + void RunPromptUserTask( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback) override; + + void RunDisableExtensionsTask( + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::DisableExtensionsCallback callback) override; + + // Callback for ChromePrompt::PromptUser, internal state must be + // State::kWaitingForResponseFromChrome. Invokes callback(prompt_acceptance) + // and transitions to state State::kDoneInteraction. + void OnChromeResponseReceived( + mojom::ChromePrompt::PromptUserCallback callback, + mojom::PromptAcceptance prompt_acceptance) override; + + // Callback for ChromePrompt::DisableExtensions, internal state must be + // State::kDoneInteraction. Invokes callback(extensions_deleted_callback). + void OnChromeResponseReceivedExtensions( + mojom::ChromePrompt::DisableExtensionsCallback callback, + bool extensions_deleted_callback) override; + + // Connection error handler. Invokes either + // error_handler_->OnConnectionClosed() or + // error_handler_->OnConnectionClosedAfterDone(), depending on the internal + // state. + void OnConnectionError() override; + + void PromptUserCheckVersion( + const std::vector<base::FilePath>& files_to_delete, + const std::vector<base::string16>& registry_keys, + const std::vector<base::string16>& extension_ids, + mojom::ChromePrompt::PromptUserCallback callback, + uint32_t version) override; + + private: + scoped_refptr<MojoTaskRunner> task_runner_; + std::string chrome_mojo_pipe_token_; + std::unique_ptr<mojom::ChromePromptPtr> chrome_prompt_service_; +}; + +} // namespace chrome_cleaner + +#endif // CHROME_CHROME_CLEANER_IPC_MOJO_CHROME_PROMPT_IPC_H_
diff --git a/chrome/chrome_cleaner/settings/settings.cc b/chrome/chrome_cleaner/settings/settings.cc index a7819df0..f51448cc 100644 --- a/chrome/chrome_cleaner/settings/settings.cc +++ b/chrome/chrome_cleaner/settings/settings.cc
@@ -12,6 +12,7 @@ #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" +#include "base/win/win_util.h" #include "chrome/chrome_cleaner/buildflags.h" #include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h" #include "chrome/chrome_cleaner/settings/engine_settings.h" @@ -287,6 +288,44 @@ return chrome_mojo_pipe_token_; } +bool Settings::prompt_using_mojo() const { + return prompt_using_mojo_; +} + +bool Settings::switches_valid_for_ipc() const { + // IPC is only used in scanning mode. In other modes ignore the flags. + if (execution_mode() != ExecutionMode::kScanning) { + return true; + } + + // Only one IPC mechanism can be used. + if (prompt_using_mojo_ && prompt_using_proto_) { + return false; + } + + // At least one IPC mechanism has to be used. + if (!prompt_using_mojo_ && !prompt_using_proto_) { + return false; + } + + // Mojo use requires two flags. + if (prompt_using_mojo_) { + if (chrome_mojo_pipe_token().empty() || !has_parent_pipe_handle()) { + return false; + } + } + + // Proto use requires two flags. + if (prompt_using_proto_) { + if (prompt_response_read_handle_ == INVALID_HANDLE_VALUE || + prompt_request_write_handle_ == INVALID_HANDLE_VALUE) { + return false; + } + } + + return true; +} + bool Settings::has_parent_pipe_handle() const { return has_parent_pipe_handle_; } @@ -362,10 +401,33 @@ GetLogsUploadAllowed(command_line, target_binary, execution_mode_); logs_collection_enabled_ = GetLogsCollectionEnabled(command_line, target_binary, execution_mode_); + + // Mojo related. chrome_mojo_pipe_token_ = command_line.GetSwitchValueASCII( chrome_cleaner::kChromeMojoPipeTokenSwitch); has_parent_pipe_handle_ = command_line.HasSwitch(mojo::PlatformChannel::kHandleSwitch); + if (!chrome_mojo_pipe_token_.empty() || has_parent_pipe_handle_) { + prompt_using_mojo_ = true; + } + + // Proto related. + uint32_t handle_value; + if (base::StringToUint(command_line.GetSwitchValueNative( + chrome_cleaner::kChromeReadHandleSwitch), + &handle_value)) { + prompt_response_read_handle_ = base::win::Uint32ToHandle(handle_value); + } + if (base::StringToUint(command_line.GetSwitchValueNative( + chrome_cleaner::kChromeWriteHandleSwitch), + &handle_value)) { + prompt_request_write_handle_ = base::win::Uint32ToHandle(handle_value); + } + + if (prompt_response_read_handle_ != INVALID_HANDLE_VALUE || + prompt_request_write_handle_ != INVALID_HANDLE_VALUE) { + prompt_using_proto_ = true; + } #if !BUILDFLAG(IS_OFFICIAL_CHROME_CLEANER_BUILD) remove_report_only_uws_ = command_line.HasSwitch(kRemoveScanOnlyUwS);
diff --git a/chrome/chrome_cleaner/settings/settings.h b/chrome/chrome_cleaner/settings/settings.h index 380b861c..2ee3407 100644 --- a/chrome/chrome_cleaner/settings/settings.h +++ b/chrome/chrome_cleaner/settings/settings.h
@@ -77,6 +77,10 @@ virtual bool has_parent_pipe_handle() const; + virtual bool prompt_using_mojo() const; + + virtual bool switches_valid_for_ipc() const; + // Returns the execution mode sent by Chrome if valid, or kNone if // kExecutionModeSwitch is not present or the corresponding value is invalid. virtual ExecutionMode execution_mode() const; @@ -178,6 +182,12 @@ // Mojo related settings. std::string chrome_mojo_pipe_token_; bool has_parent_pipe_handle_ = false; + bool prompt_using_mojo_ = false; + + // Proto related settings. + bool prompt_using_proto_ = false; + HANDLE prompt_response_read_handle_ = INVALID_HANDLE_VALUE; + HANDLE prompt_request_write_handle_ = INVALID_HANDLE_VALUE; // Engine selection settings. Engine::Name engine_ = Engine::UNKNOWN;
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index b12bf4e..3bf72b5b 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -139,7 +139,7 @@ "google_url_loader_throttle.h", "heap_profiler_controller.cc", "heap_profiler_controller.h", - "instant_struct_traits.h", + "instant_mojom_traits.h", "logging_chrome.cc", "logging_chrome.h", "mac/app_shim_launch.h",
diff --git a/chrome/common/OWNERS b/chrome/common/OWNERS index 144ecfa..163695ae 100644 --- a/chrome/common/OWNERS +++ b/chrome/common/OWNERS
@@ -23,8 +23,8 @@ per-file *_type_converter*.*=set noparent per-file *_type_converter*.*=file://ipc/SECURITY_OWNERS -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/chrome/common/common_message_generator.h b/chrome/common/common_message_generator.h index c97dc83..05eb5b8 100644 --- a/chrome/common/common_message_generator.h +++ b/chrome/common/common_message_generator.h
@@ -5,7 +5,7 @@ // Multiply-included file, hence no include guard. #include "chrome/common/common_param_traits_macros.h" -#include "chrome/common/instant_struct_traits.h" +#include "chrome/common/instant_mojom_traits.h" #include "services/network/public/cpp/p2p_param_traits.h" #undef CHROME_COMMON_MAC_APP_SHIM_PARAM_TRAITS_H_ #include "chrome/common/mac/app_shim_param_traits.h"
diff --git a/chrome/common/extensions/OWNERS b/chrome/common/extensions/OWNERS index 9210e90..fe353c7 100644 --- a/chrome/common/extensions/OWNERS +++ b/chrome/common/extensions/OWNERS
@@ -6,8 +6,8 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS # COMPONENT: Platform>Extensions # TEAM: chromium-extensions@chromium.org
diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index eb5041d..6094725 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json
@@ -814,7 +814,8 @@ }, "windows": [{ "dependencies": ["api:tabs"], - "contexts": ["blessed_extension"] + "contexts": ["blessed_extension"], + "disallow_for_service_workers": false }, { "channel": "stable", "contexts": ["webui"],
diff --git a/chrome/common/instant_struct_traits.h b/chrome/common/instant_mojom_traits.h similarity index 100% rename from chrome/common/instant_struct_traits.h rename to chrome/common/instant_mojom_traits.h
diff --git a/chrome/common/search.typemap b/chrome/common/search.typemap index 7e8030e3..0f7ae511 100644 --- a/chrome/common/search.typemap +++ b/chrome/common/search.typemap
@@ -9,7 +9,7 @@ "//components/ntp_tiles/ntp_tile_impression.h", "//components/omnibox/common/omnibox_focus_state.h", ] -traits_headers = [ "//chrome/common/instant_struct_traits.h" ] +traits_headers = [ "//chrome/common/instant_mojom_traits.h" ] deps = [ "//chrome/common", "//ipc",
diff --git a/chrome/services/isolated_xr_device/OWNERS b/chrome/services/isolated_xr_device/OWNERS index 776883c..b95d4bd6 100644 --- a/chrome/services/isolated_xr_device/OWNERS +++ b/chrome/services/isolated_xr_device/OWNERS
@@ -1,5 +1,4 @@ alcooper@chromium.org -billorr@chromium.org ddorwin@chromium.org klausw@chromium.org
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 093f589e..402d173 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1075,6 +1075,7 @@ "../browser/sessions/tab_restore_service_browsertest.cc", "../browser/sessions/tab_restore_service_load_waiter.cc", "../browser/sessions/tab_restore_service_load_waiter.h", + "../browser/sharing/click_to_call/click_to_call_browsertest.cc", "../browser/signin/consistency_cookie_browsertest.cc", "../browser/site_isolation/chrome_site_per_process_browsertest.cc", "../browser/site_isolation/site_details_browsertest.cc", @@ -1421,7 +1422,7 @@ [ "../browser/ssl/captive_portal_blocking_page_browsertest.cc" ] } - if (!is_android) { + if (!is_android && !is_chromeos) { sources += [ "../browser/external_protocol/external_protocol_handler_browsertest.cc", ] @@ -1938,7 +1939,7 @@ "../browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc", "../browser/chromeos/arc/auth/arc_auth_service_browsertest.cc", "../browser/chromeos/arc/auth/arc_robot_auth_code_fetcher_browsertest.cc", - "../browser/chromeos/arc/enterprise/arc_cert_store_bridge_browsertest.cc", + "../browser/chromeos/arc/enterprise/cert_store/arc_cert_store_bridge_browsertest.cc", "../browser/chromeos/arc/intent_helper/arc_settings_service_browsertest.cc", "../browser/chromeos/arc/user_session/arc_user_session_service_browsertest.cc", "../browser/chromeos/attestation/attestation_policy_browsertest.cc", @@ -2860,7 +2861,6 @@ "../browser/google/google_search_domain_mixing_metrics_emitter_factory_unittest.cc", "../browser/google/google_search_domain_mixing_metrics_emitter_unittest.cc", "../browser/google/google_update_settings_unittest.cc", - "../browser/google/google_url_tracker_factory_unittest.cc", "../browser/history/android/android_cache_database_unittest.cc", "../browser/history/android/android_history_provider_service_unittest.cc", "../browser/history/android/android_provider_backend_unittest.cc", @@ -2978,6 +2978,7 @@ "../browser/performance_manager/decorators/frozen_frame_aggregator_unittest.cc", "../browser/performance_manager/decorators/page_almost_idle_decorator_unittest.cc", "../browser/performance_manager/frame_priority/frame_priority_unittest.cc", + "../browser/performance_manager/frame_priority/override_vote_aggregator_unittest.cc", "../browser/performance_manager/frame_priority/unittest_util.cc", "../browser/performance_manager/frame_priority/unittest_util.h", "../browser/performance_manager/graph/frame_node_impl_unittest.cc",
diff --git a/chrome/test/base/dialog_test_browser_window.cc b/chrome/test/base/dialog_test_browser_window.cc index d1110de3..394b1cd 100644 --- a/chrome/test/base/dialog_test_browser_window.cc +++ b/chrome/test/base/dialog_test_browser_window.cc
@@ -22,7 +22,7 @@ host_window_.reset(new views::Widget); views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - host_window_->Init(params); + host_window_->Init(std::move(params)); // Leave the window hidden: unit tests shouldn't need it to be visible. #endif }
diff --git a/chrome/test/base/in_process_browser_test.cc b/chrome/test/base/in_process_browser_test.cc index 2cfff5c..5b2aa98 100644 --- a/chrome/test/base/in_process_browser_test.cc +++ b/chrome/test/base/in_process_browser_test.cc
@@ -308,7 +308,11 @@ #if defined(OS_WIN) com_initializer_.reset(); #endif - + if (::testing::UnitTest::GetInstance() + ->current_test_info() + ->result() + ->Skipped()) + return; BrowserTestBase::TearDown(); OSCryptMocker::TearDown(); ChromeContentBrowserClient::SetDefaultQuotaSettingsForTesting(nullptr);
diff --git a/chrome/test/base/test_browser_window_aura.cc b/chrome/test/base/test_browser_window_aura.cc index 42a0683..3b12773 100644 --- a/chrome/test/base/test_browser_window_aura.cc +++ b/chrome/test/base/test_browser_window_aura.cc
@@ -92,7 +92,7 @@ params.bounds = gfx::Rect(5, 5, 20, 20); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = parent; - widget_->Init(params); + widget_->Init(std::move(params)); } TestBrowserWindowViews::~TestBrowserWindowViews() {}
diff --git a/chrome/test/data/android/contextmenu/context_menu_test.html b/chrome/test/data/android/contextmenu/context_menu_test.html index a5c807e..ca08702 100644 --- a/chrome/test/data/android/contextmenu/context_menu_test.html +++ b/chrome/test/data/android/contextmenu/context_menu_test.html
@@ -10,7 +10,7 @@ <a href="test_link2.html" id="testLink2">Test Link 2></a><br /> - <a href="test_link.html" id="testImageLink"><img src="test_image.png"></a><br /> + <a href="test_link.html" id="testImageLink"><img src="test_image.png"></a><br /><br /> <a href="mailto:someone1@example.com,someone2@example.com?Subject=EmailTest" id="testEmail">EmailTest</a><br />
diff --git a/chrome/test/data/extensions/api_test/tabs/current_window/manifest.json b/chrome/test/data/extensions/api_test/tabs/current_window/manifest.json index 8d3bdb02..b417c5e 100644 --- a/chrome/test/data/extensions/api_test/tabs/current_window/manifest.json +++ b/chrome/test/data/extensions/api_test/tabs/current_window/manifest.json
@@ -2,6 +2,6 @@ "name": "tabs/current_window", "version": "0.1", "manifest_version": 2, - "background": { "scripts": ["background.js"] }, + "background": { "scripts": ["background.js"], "persistent": false}, "permissions": ["tabs"] }
diff --git a/chrome/test/media_router/media_router_base_browsertest.cc b/chrome/test/media_router/media_router_base_browsertest.cc index 43331c3..bebc08b 100644 --- a/chrome/test/media_router/media_router_base_browsertest.cc +++ b/chrome/test/media_router/media_router_base_browsertest.cc
@@ -39,6 +39,8 @@ } void MediaRouterBaseBrowserTest::SetUp() { + if (BrowserTestBase::ShouldSkipManualTests()) + GTEST_SKIP(); ParseCommandLine(); ExtensionBrowserTest::SetUp(); }
diff --git a/chrome/test/remoting/remote_desktop_browsertest.cc b/chrome/test/remoting/remote_desktop_browsertest.cc index 34345ab3..2b2ae90 100644 --- a/chrome/test/remoting/remote_desktop_browsertest.cc +++ b/chrome/test/remoting/remote_desktop_browsertest.cc
@@ -66,6 +66,8 @@ RemoteDesktopBrowserTest::~RemoteDesktopBrowserTest() {} void RemoteDesktopBrowserTest::SetUp() { + if (BrowserTestBase::ShouldSkipManualTests()) + GTEST_SKIP(); ParseCommandLine(); PlatformAppBrowserTest::SetUp(); }
diff --git a/chrome/test/views/accessibility_checker_unittest.cc b/chrome/test/views/accessibility_checker_unittest.cc index 97cc9f4c..3c520fd 100644 --- a/chrome/test/views/accessibility_checker_unittest.cc +++ b/chrome/test/views/accessibility_checker_unittest.cc
@@ -23,7 +23,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); params.context = GetContext(); - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); // Add the button.
diff --git a/chromecast/bindings/bindings_manager_cast.cc b/chromecast/bindings/bindings_manager_cast.cc index a65e589..ba4251a9c 100644 --- a/chromecast/bindings/bindings_manager_cast.cc +++ b/chromecast/bindings/bindings_manager_cast.cc
@@ -15,7 +15,7 @@ #include "mojo/public/cpp/bindings/connector.h" #include "third_party/blink/public/common/messaging/string_message_codec.h" #include "third_party/blink/public/common/messaging/transferable_message.h" -#include "third_party/blink/public/common/messaging/transferable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" namespace chromecast {
diff --git a/chromecast/bindings/bindings_manager_cast_browsertest.cc b/chromecast/bindings/bindings_manager_cast_browsertest.cc index 504f79aaf..fe99d318 100644 --- a/chromecast/bindings/bindings_manager_cast_browsertest.cc +++ b/chromecast/bindings/bindings_manager_cast_browsertest.cc
@@ -34,7 +34,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/messaging/string_message_codec.h" #include "third_party/blink/public/common/messaging/transferable_message.h" -#include "third_party/blink/public/common/messaging/transferable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "url/gurl.h"
diff --git a/chromecast/browser/cast_web_contents_browsertest.cc b/chromecast/browser/cast_web_contents_browsertest.cc index 992949b..07e85d9 100644 --- a/chromecast/browser/cast_web_contents_browsertest.cc +++ b/chromecast/browser/cast_web_contents_browsertest.cc
@@ -42,7 +42,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/messaging/string_message_codec.h" #include "third_party/blink/public/common/messaging/transferable_message.h" -#include "third_party/blink/public/common/messaging/transferable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "url/gurl.h"
diff --git a/chromecast/browser/extensions/api/tabs/tabs_api.cc b/chromecast/browser/extensions/api/tabs/tabs_api.cc index 46ee1f5..039e255 100644 --- a/chromecast/browser/extensions/api/tabs/tabs_api.cc +++ b/chromecast/browser/extensions/api/tabs/tabs_api.cc
@@ -762,8 +762,12 @@ bool ExecuteCodeInTabFunction::CanExecuteScriptOnPage(std::string* error) { const CastWebContents* webview = GetWebViewForTab(execute_tab_id_); + if (!webview) { + *error = ErrorUtils::FormatErrorMessage( + keys::kTabIndexNotFoundError, base::NumberToString(execute_tab_id_)); + return false; + } - CHECK(webview); content::WebContents* contents = webview->web_contents(); int frame_id = details_->frame_id ? *details_->frame_id
diff --git a/chromecast/graphics/accessibility/partial_magnification_controller.cc b/chromecast/graphics/accessibility/partial_magnification_controller.cc index 66e5e2a..10d8c165 100644 --- a/chromecast/graphics/accessibility/partial_magnification_controller.cc +++ b/chromecast/graphics/accessibility/partial_magnification_controller.cc
@@ -313,7 +313,7 @@ params.bounds = GetBounds(mouse); params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.parent = root_window; - host_widget_->Init(params); + host_widget_->Init(std::move(params)); host_widget_->set_focus_on_creation(false); host_widget_->Show();
diff --git a/chromecast/graphics/cast_views_test.cc b/chromecast/graphics/cast_views_test.cc index b9f785d..14eeb71 100644 --- a/chromecast/graphics/cast_views_test.cc +++ b/chromecast/graphics/cast_views_test.cc
@@ -31,7 +31,7 @@ params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; params.bounds = bounds; std::unique_ptr<views::Widget> widget(new views::Widget); - widget->Init(params); + widget->Init(std::move(params)); widget->SetOpacity(0.6); widget->SetContentsView(progress_bar); window_manager->SetWindowId(widget->GetNativeView(),
diff --git a/components/BUILD.gn b/components/BUILD.gn index 2025126..19b8b90 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -98,7 +98,7 @@ "//components/flags_ui:unit_tests", "//components/gcm_driver:unit_tests", "//components/gcm_driver/crypto:unit_tests", - "//components/google/core/browser:unit_tests", + "//components/google/core/common:unit_tests", "//components/grpc_support/test:unit_tests", "//components/gwp_asan:unit_tests", "//components/history/core/browser:unit_tests",
diff --git a/components/arc/BUILD.gn b/components/arc/BUILD.gn index b8b2b203..e6c1164 100644 --- a/components/arc/BUILD.gn +++ b/components/arc/BUILD.gn
@@ -102,7 +102,7 @@ "//chromeos/network", "//components/account_id", "//components/exo", - "//components/google/core/browser", + "//components/google/core/common", "//components/onc", "//components/prefs", "//components/session_manager/core",
diff --git a/components/arc/arc_features_parser.cc b/components/arc/arc_features_parser.cc index 8c031c1..1235e2d3 100644 --- a/components/arc/arc_features_parser.cc +++ b/components/arc/arc_features_parser.cc
@@ -141,8 +141,9 @@ void ArcFeaturesParser::GetArcFeatures( base::OnceCallback<void(base::Optional<ArcFeatures>)> callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&ReadOnFileThread, base::FilePath(kArcFeaturesJsonFile)), std::move(callback)); }
diff --git a/components/arc/common/BUILD.gn b/components/arc/common/BUILD.gn index 9026142..f09ab1d 100644 --- a/components/arc/common/BUILD.gn +++ b/components/arc/common/BUILD.gn
@@ -47,6 +47,7 @@ "policy.mojom", "power.mojom", "print.mojom", + "print_common.mojom", "print_spooler.mojom", "process.mojom", "property.mojom",
diff --git a/components/arc/common/print.mojom b/components/arc/common/print.mojom index f74d468c..42597d5 100644 --- a/components/arc/common/print.mojom +++ b/components/arc/common/print.mojom
@@ -6,123 +6,7 @@ module arc.mojom; -// android.print.PageRange -struct PrintPageRange { - // First page inclusive. - int32 start; - // Last page inclusive. - int32 end; -}; - -// android.print.PrintAttributes.MediaSize -struct PrintMediaSize { - // Id unique among media sizes. - string id; - // Localized label. - string label; - int32 width_mils; - int32 height_mils; -}; - -// android.print.PrintAttributes.Resolution -struct PrintResolution { - // Id unique among resolutions. - string id; - // Localized label. - string label; - int32 horizontal_dpi; - int32 vertical_dpi; -}; - -// android.print.PrintAttributes.Margins -struct PrintMargins { - int32 left_mils; - int32 top_mils; - int32 right_mils; - int32 bottom_mils; -}; - -// android.print.PrintAttributes.COLOR_MODE_* -[Extensible] -enum PrintColorMode { - MONOCHROME = 1, - COLOR = 2, -}; - -// android.print.PrintAttributes.DUPLEX_MODE_* -[Extensible] -enum PrintDuplexMode { - NONE = 1, - LONG_EDGE = 2, - SHORT_EDGE = 4, -}; - -// android.print.PrintDocumentInfo.CONTENT_TYPE_* -[Extensible] -enum PrintContentType { - UNKNOWN = -1, - DOCUMENT = 0, - PHOTO = 1, -}; - -// android.print.PrintAttributes -struct PrintAttributes { - PrintMediaSize? media_size; - PrintResolution? resolution; - PrintMargins? min_margins; - PrintColorMode color_mode; - PrintDuplexMode duplex_mode; -}; - -struct PrintJobRequest { - // android.printservice.PrintJob fields: - array<int8> id; - string label; - string? printer_id; - int64 creation_time; - int32 copies; - array<PrintPageRange> pages; - PrintAttributes attributes; - // android.print.PrintDocumentInfo fields: - string document_name; - int32 document_page_count; - PrintContentType content_type; - int64 data_size; - // android.printservice.PrintDocument fields: - handle? data; -}; - -// android.print.PrinterInfo.STATUS_* -[Extensible] -enum PrinterStatus { - IDLE = 1, - BUSY = 2, - UNAVAILABLE = 3, -}; - -// android.print.PrinterCapabilitiesInfo -struct PrinterCapabilities { - array<PrintMediaSize> media_sizes; - array<PrintResolution> resolutions; - PrintMargins min_margins; - PrintColorMode color_modes; - PrintDuplexMode duplex_modes; - PrintAttributes defaults; -}; - -// android.print.PrinterInfo -struct PrinterInfo { - // Id unique among printers. - string id; - // Localized name. - string name; - PrinterStatus status; - // Localized description. - string? description; - // Intent for provider-specific settings. - string? info_intent; - PrinterCapabilities? capabilities; -}; +import "components/arc/common/print_common.mojom"; // android.printservice.PrinterDiscoverySession implementation. // This is called by container when printing is requested and printer discovery
diff --git a/components/arc/common/print.typemap b/components/arc/common/print.typemap index c8bb925..3c96575 100644 --- a/components/arc/common/print.typemap +++ b/components/arc/common/print.typemap
@@ -1,12 +1,12 @@ -mojom = "//components/arc/common/print.mojom" +mojom = "//components/arc/common/print_common.mojom" public_headers = [ "//printing/backend/print_backend.h", "//printing/page_range.h", "//ui/gfx/geometry/size.h", ] -traits_headers = [ "//chrome/browser/chromeos/arc/print/print_struct_traits.h" ] +traits_headers = [ "//chrome/browser/chromeos/arc/print/print_mojom_traits.h" ] sources = [ - "//chrome/browser/chromeos/arc/print/print_struct_traits.cc", + "//chrome/browser/chromeos/arc/print/print_mojom_traits.cc", ] deps = [] public_deps = [
diff --git a/components/arc/common/print_common.mojom b/components/arc/common/print_common.mojom new file mode 100644 index 0000000..006181d --- /dev/null +++ b/components/arc/common/print_common.mojom
@@ -0,0 +1,123 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module arc.mojom; + +// android.print.PageRange +struct PrintPageRange { + // First page inclusive. + int32 start; + // Last page inclusive. + int32 end; +}; + +// android.print.PrintAttributes.MediaSize +struct PrintMediaSize { + // Id unique among media sizes. + string id; + // Localized label. + string label; + int32 width_mils; + int32 height_mils; +}; + +// android.print.PrintAttributes.Resolution +struct PrintResolution { + // Id unique among resolutions. + string id; + // Localized label. + string label; + int32 horizontal_dpi; + int32 vertical_dpi; +}; + +// android.print.PrintAttributes.Margins +struct PrintMargins { + int32 left_mils; + int32 top_mils; + int32 right_mils; + int32 bottom_mils; +}; + +// android.print.PrintAttributes.COLOR_MODE_* +[Extensible] +enum PrintColorMode { + MONOCHROME = 1, + COLOR = 2, +}; + +// android.print.PrintAttributes.DUPLEX_MODE_* +[Extensible] +enum PrintDuplexMode { + NONE = 1, + LONG_EDGE = 2, + SHORT_EDGE = 4, +}; + +// android.print.PrintDocumentInfo.CONTENT_TYPE_* +[Extensible] +enum PrintContentType { + UNKNOWN = -1, + DOCUMENT = 0, + PHOTO = 1, +}; + +// android.print.PrintAttributes +struct PrintAttributes { + PrintMediaSize? media_size; + PrintResolution? resolution; + PrintMargins? min_margins; + PrintColorMode color_mode; + PrintDuplexMode duplex_mode; +}; + +struct PrintJobRequest { + // android.printservice.PrintJob fields: + array<int8> id; + string label; + string? printer_id; + int64 creation_time; + int32 copies; + array<PrintPageRange> pages; + PrintAttributes attributes; + // android.print.PrintDocumentInfo fields: + string document_name; + int32 document_page_count; + PrintContentType content_type; + int64 data_size; + // android.printservice.PrintDocument fields: + handle? data; +}; + +// android.print.PrinterInfo.STATUS_* +[Extensible] +enum PrinterStatus { + IDLE = 1, + BUSY = 2, + UNAVAILABLE = 3, +}; + +// android.print.PrinterCapabilitiesInfo +struct PrinterCapabilities { + array<PrintMediaSize> media_sizes; + array<PrintResolution> resolutions; + PrintMargins min_margins; + PrintColorMode color_modes; + PrintDuplexMode duplex_modes; + PrintAttributes defaults; +}; + +// android.print.PrinterInfo +struct PrinterInfo { + // Id unique among printers. + string id; + // Localized name. + string name; + PrinterStatus status; + // Localized description. + string? description; + // Intent for provider-specific settings. + string? info_intent; + PrinterCapabilities? capabilities; +};
diff --git a/components/arc/common/print_spooler.mojom b/components/arc/common/print_spooler.mojom index 81c415b..21d7e1fd 100644 --- a/components/arc/common/print_spooler.mojom +++ b/components/arc/common/print_spooler.mojom
@@ -6,13 +6,15 @@ module arc.mojom; +import "components/arc/common/print_common.mojom"; + // Next method ID: 0 interface PrintSpoolerHost { - // TODO(jschettler): Add methods to open and close print preview + // TODO(jschettler): Add methods to open and close Chrome print preview. }; // Next method ID: 1 interface PrintSpoolerInstance { // Establishes full-duplex communication with the host. [MinVersion=0] Init@0(PrintSpoolerHost host_ptr) => (); -}; \ No newline at end of file +};
diff --git a/components/arc/crash_collector/arc_crash_collector_bridge.cc b/components/arc/crash_collector/arc_crash_collector_bridge.cc index a265482..8cc5dbc 100644 --- a/components/arc/crash_collector/arc_crash_collector_bridge.cc +++ b/components/arc/crash_collector/arc_crash_collector_bridge.cc
@@ -91,8 +91,8 @@ void ArcCrashCollectorBridge::DumpCrash(const std::string& type, mojo::ScopedHandle pipe) { - base::PostTaskWithTraits( - FROM_HERE, {base::WithBaseSyncPrimitives()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::WithBaseSyncPrimitives()}, base::BindOnce(&RunCrashReporter, type, device_, board_, cpu_abi_, mojo::UnwrapPlatformHandle(std::move(pipe)).TakeFD())); }
diff --git a/components/arc/session/arc_session_impl.cc b/components/arc/session/arc_session_impl.cc index 04efc71..bc9e1d72 100644 --- a/components/arc/session/arc_session_impl.cc +++ b/components/arc/session/arc_session_impl.cc
@@ -160,8 +160,8 @@ weak_factory_(this) {} void ArcSessionDelegateImpl::CreateSocket(CreateSocketCallback callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ArcSessionDelegateImpl::CreateSocketInternal), std::move(callback)); } @@ -181,8 +181,8 @@ // For production, |socket_fd| passed from session_manager is either a valid // socket or a valid file descriptor (/dev/null). For testing, |socket_fd| // might be invalid. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ArcSessionDelegateImpl::ConnectMojoInternal, std::move(socket_fd), std::move(cancel_fd)), base::BindOnce(&ArcSessionDelegateImpl::OnMojoConnected, @@ -201,8 +201,8 @@ void ArcSessionDelegateImpl::GetFreeDiskSpace( GetFreeDiskSpaceCallback callback) { - PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, base::FilePath("/home")), std::move(callback));
diff --git a/components/arc/session/arc_vm_client_adapter.cc b/components/arc/session/arc_vm_client_adapter.cc index 2cd1ba7..c834d1b 100644 --- a/components/arc/session/arc_vm_client_adapter.cc +++ b/components/arc/session/arc_vm_client_adapter.cc
@@ -107,8 +107,8 @@ VLOG(1) << "Concierge service started for arcvm."; // TODO(cmtm): Export host-side /data to the VM, and remove the call. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, base::FilePath(kHomeDirectory)), base::BindOnce(&ArcVmClientAdapter::CreateDiskImageAfterSizeCheck,
diff --git a/components/assist_ranker/ranker_model_loader_impl.cc b/components/assist_ranker/ranker_model_loader_impl.cc index ad8dd63..abbc1c6 100644 --- a/components/assist_ranker/ranker_model_loader_impl.cc +++ b/components/assist_ranker/ranker_model_loader_impl.cc
@@ -95,8 +95,9 @@ base::FilePath model_path, GURL model_url, std::string uma_prefix) - : background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + : background_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), validate_model_cb_(std::move(validate_model_cb)), on_model_available_cb_(std::move(on_model_available_cb)),
diff --git a/components/autofill/core/browser/address_normalizer_impl.cc b/components/autofill/core/browser/address_normalizer_impl.cc index 7d47f05..2d5ce94e 100644 --- a/components/autofill/core/browser/address_normalizer_impl.cc +++ b/components/autofill/core/browser/address_normalizer_impl.cc
@@ -156,8 +156,9 @@ // shutdown. This is important to prevent an access race when the destructor // of |storage| accesses an ObserverList that lives on the current sequence. // https://crbug.com/829122 - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce( &CreateAddressValidator, std::move(source), DeleteOnTaskRunnerStorageUniquePtr(
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index b9a4403..57fe5e7 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -552,8 +552,9 @@ // so that we can safely pass the address to the first callback regardless of // the (undefined) order in which the callback parameters are computed. FormStructure* raw_form = form_structure.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&AutofillManager::DeterminePossibleFieldTypesForUpload, copied_profiles, copied_credit_cards, app_locale_, raw_form),
diff --git a/components/autofill/core/browser/autofill_metrics.cc b/components/autofill/core/browser/autofill_metrics.cc index 0943546..ec1ecad6 100644 --- a/components/autofill/core/browser/autofill_metrics.cc +++ b/components/autofill/core/browser/autofill_metrics.cc
@@ -651,14 +651,6 @@ } // static -void AutofillMetrics::LogPaymentsCustomerDataBillingIdStatus( - BillingIdStatus status) { - DCHECK_LE(status, BillingIdStatus::kMaxValue); - UMA_HISTOGRAM_ENUMERATION("Autofill.PaymentsCustomerDataBillingIdStatus", - status); -} - -// static void AutofillMetrics::LogCardUploadDecisionMetrics( int upload_decision_metrics) { DCHECK(upload_decision_metrics);
diff --git a/components/autofill/core/browser/autofill_metrics.h b/components/autofill/core/browser/autofill_metrics.h index 310b308..4429de73 100644 --- a/components/autofill/core/browser/autofill_metrics.h +++ b/components/autofill/core/browser/autofill_metrics.h
@@ -53,13 +53,6 @@ AUTOFILL_FORM_SUBMITTED_STATE_ENUM_SIZE, }; - enum class BillingIdStatus { - MISSING = 0, - PARSE_ERROR = 1, - VALID = 2, - kMaxValue = VALID, - }; - enum CardUploadDecisionMetric { // All the required conditions were satisfied using either the form fields // or we prompted the user to fix one or more conditions in the card upload @@ -946,9 +939,6 @@ // from its prefilled value or not. static void LogSaveCardCardholderNameWasEdited(bool edited); - // Logs the PaymentsCustomerData billing ID status at the time of use. - static void LogPaymentsCustomerDataBillingIdStatus(BillingIdStatus status); - // |upload_decision_metrics| is a bitmask of |CardUploadDecisionMetric|. static void LogCardUploadDecisionMetrics(int upload_decision_metrics); static void LogCreditCardInfoBarMetric(
diff --git a/components/autofill/core/browser/payments/credit_card_access_manager.cc b/components/autofill/core/browser/payments/credit_card_access_manager.cc index 4b8aa4ed..7ccfef4 100644 --- a/components/autofill/core/browser/payments/credit_card_access_manager.cc +++ b/components/autofill/core/browser/payments/credit_card_access_manager.cc
@@ -223,8 +223,8 @@ if (AuthenticationRequiresUnmaskDetails()) { // Wait for |ready_to_start_authentication_| to be signaled by // OnDidGetUnmaskDetails() or until timeout before calling Authenticate(). - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&WaitForEvent, &ready_to_start_authentication_), base::BindOnce(&CreditCardAccessManager::Authenticate, weak_ptr_factory_.GetWeakPtr()));
diff --git a/components/autofill/core/browser/payments/full_card_request.cc b/components/autofill/core/browser/payments/full_card_request.cc index 181aa224..b2df094 100644 --- a/components/autofill/core/browser/payments/full_card_request.cc +++ b/components/autofill/core/browser/payments/full_card_request.cc
@@ -89,8 +89,8 @@ card.ShouldUpdateExpiration(AutofillClock::Now())); if (should_unmask_card_) { payments_client_->Prepare(); - request_->billing_customer_number = GetBillingCustomerId( - personal_data_manager_, /*should_log_validity=*/true); + request_->billing_customer_number = + GetBillingCustomerId(personal_data_manager_); } request_->fido_assertion_info = std::move(fido_assertion_info);
diff --git a/components/autofill/core/browser/payments/payments_util.cc b/components/autofill/core/browser/payments/payments_util.cc index 59876db..7437638a 100644 --- a/components/autofill/core/browser/payments/payments_util.cc +++ b/components/autofill/core/browser/payments/payments_util.cc
@@ -6,7 +6,6 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" -#include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/personal_data_manager.h" @@ -17,8 +16,7 @@ constexpr int kCustomerHasNoBillingCustomerNumber = 0; } -int64_t GetBillingCustomerId(PersonalDataManager* personal_data_manager, - bool should_log_validity) { +int64_t GetBillingCustomerId(PersonalDataManager* personal_data_manager) { DCHECK(personal_data_manager); // Get billing customer ID from the synced PaymentsCustomerData. @@ -28,21 +26,7 @@ int64_t billing_customer_id = 0; if (base::StringToInt64(base::StringPiece(customer_data->customer_id), &billing_customer_id)) { - if (should_log_validity) { - AutofillMetrics::LogPaymentsCustomerDataBillingIdStatus( - AutofillMetrics::BillingIdStatus::VALID); - } return billing_customer_id; - } else { - if (should_log_validity) { - AutofillMetrics::LogPaymentsCustomerDataBillingIdStatus( - AutofillMetrics::BillingIdStatus::PARSE_ERROR); - } - } - } else { - if (should_log_validity) { - AutofillMetrics::LogPaymentsCustomerDataBillingIdStatus( - AutofillMetrics::BillingIdStatus::MISSING); } } return kCustomerHasNoBillingCustomerNumber;
diff --git a/components/autofill/core/browser/payments/payments_util.h b/components/autofill/core/browser/payments/payments_util.h index b384e03..2e2cf76 100644 --- a/components/autofill/core/browser/payments/payments_util.h +++ b/components/autofill/core/browser/payments/payments_util.h
@@ -18,10 +18,8 @@ // Returns the billing customer ID (a.k.a. the customer number) for the Google // Payments account for this user. Obtains it from the synced data. Returns 0 -// if the customer ID was not found. If |should_log_validity| is true, will -// report on the validity state of the customer ID in PaymentsCustomerData. -int64_t GetBillingCustomerId(PersonalDataManager* personal_data_manager, - bool should_log_validity = false); +// if the customer ID was not found. +int64_t GetBillingCustomerId(PersonalDataManager* personal_data_manager); // Returns if the customer has an existing Google payments account. bool HasGooglePaymentsAccount(PersonalDataManager* personal_data_manager);
diff --git a/components/autofill/core/browser/payments/payments_util_unittest.cc b/components/autofill/core/browser/payments/payments_util_unittest.cc index 631d321..27a324939 100644 --- a/components/autofill/core/browser/payments/payments_util_unittest.cc +++ b/components/autofill/core/browser/payments/payments_util_unittest.cc
@@ -7,8 +7,6 @@ #include "base/guid.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" -#include "base/test/metrics/histogram_tester.h" -#include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/test_personal_data_manager.h" @@ -30,43 +28,23 @@ }; TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_Normal) { - base::HistogramTester histogram_tester; - personal_data_manager_.SetPaymentsCustomerData( std::make_unique<PaymentsCustomerData>(/*customer_id=*/"123456")); - EXPECT_EQ(123456, GetBillingCustomerId(&personal_data_manager_, - /*should_log_validity=*/true)); - - histogram_tester.ExpectUniqueSample( - "Autofill.PaymentsCustomerDataBillingIdStatus", - AutofillMetrics::BillingIdStatus::VALID, 1); + EXPECT_EQ(123456, GetBillingCustomerId(&personal_data_manager_)); } TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_Garbage) { - base::HistogramTester histogram_tester; - personal_data_manager_.SetPaymentsCustomerData( std::make_unique<PaymentsCustomerData>(/*customer_id=*/"garbage")); - EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_, - /*should_log_validity=*/true)); - - histogram_tester.ExpectUniqueSample( - "Autofill.PaymentsCustomerDataBillingIdStatus", - AutofillMetrics::BillingIdStatus::PARSE_ERROR, 1); + EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_)); } TEST_F(PaymentsUtilTest, GetBillingCustomerId_PaymentsCustomerData_NoData) { - base::HistogramTester histogram_tester; - // Explictly do not set PaymentsCustomerData. Nothing crashes and the returned // customer ID is 0. - EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_, - /*should_log_validity=*/true)); - histogram_tester.ExpectUniqueSample( - "Autofill.PaymentsCustomerDataBillingIdStatus", - AutofillMetrics::BillingIdStatus::MISSING, 1); + EXPECT_EQ(0, GetBillingCustomerId(&personal_data_manager_)); } TEST_F(PaymentsUtilTest, HasGooglePaymentsAccount_Normal) {
diff --git a/components/autofill/core/browser/payments/strike_database.cc b/components/autofill/core/browser/payments/strike_database.cc index 0ed9e17b..0860cd0 100644 --- a/components/autofill/core/browser/payments/strike_database.cc +++ b/components/autofill/core/browser/payments/strike_database.cc
@@ -30,8 +30,8 @@ auto strike_database_path = profile_path.Append(FILE_PATH_LITERAL("AutofillStrikeDatabase")); - auto database_task_runner = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + auto database_task_runner = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); db_ = db_provider->GetDB<StrikeData>(
diff --git a/components/autofill/core/browser/webdata/web_data_service_unittest.cc b/components/autofill/core/browser/webdata/web_data_service_unittest.cc index bd6f8605..842588b 100644 --- a/components/autofill/core/browser/webdata/web_data_service_unittest.cc +++ b/components/autofill/core/browser/webdata/web_data_service_unittest.cc
@@ -101,8 +101,8 @@ // TODO(pkasting): http://crbug.com/740773 This should likely be sequenced, // not single-threaded; it's also possible the various uses of this below // should each use their own sequences instead of sharing this one. - auto db_task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({base::MayBlock()}); + auto db_task_runner = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock()}); wdbs_ = new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), db_task_runner); wdbs_->AddTable(std::make_unique<AutofillTable>());
diff --git a/components/autofill/ios/browser/fake_autofill_agent.mm b/components/autofill/ios/browser/fake_autofill_agent.mm index 2f5f8cb5..1f5793c0 100644 --- a/components/autofill/ios/browser/fake_autofill_agent.mm +++ b/components/autofill/ios/browser/fake_autofill_agent.mm
@@ -69,7 +69,7 @@ webState:(web::WebState*)webState completionHandler: (SuggestionsAvailableCompletion)completion { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ NSString* key = [self keyForFormName:formName fieldIdentifier:fieldIdentifier @@ -86,13 +86,12 @@ frameID:(NSString*)frameID webState:(web::WebState*)webState completionHandler:(SuggestionsReadyCompletion)completion { - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ - NSString* key = [self keyForFormName:formName - fieldIdentifier:fieldIdentifier - frameID:frameID]; - completion(_suggestionsByFormAndFieldName[key], self); - })); + base::PostTask(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ + NSString* key = [self keyForFormName:formName + fieldIdentifier:fieldIdentifier + frameID:frameID]; + completion(_suggestionsByFormAndFieldName[key], self); + })); } - (void)didSelectSuggestion:(FormSuggestion*)suggestion @@ -100,14 +99,13 @@ fieldIdentifier:(NSString*)fieldIdentifier frameID:(NSString*)frameID completionHandler:(SuggestionHandledCompletion)completion { - base::PostTaskWithTraits( - FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ - NSString* key = [self keyForFormName:formName - fieldIdentifier:fieldIdentifier - frameID:frameID]; - _selectedSuggestionByFormAndFieldName[key] = suggestion; - completion(); - })); + base::PostTask(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ + NSString* key = [self keyForFormName:formName + fieldIdentifier:fieldIdentifier + frameID:frameID]; + _selectedSuggestionByFormAndFieldName[key] = suggestion; + completion(); + })); } #pragma mark - Private Methods
diff --git a/components/autofill/ios/browser/fake_js_autofill_manager.mm b/components/autofill/ios/browser/fake_js_autofill_manager.mm index daff0e61..fa5c6e04b 100644 --- a/components/autofill/ios/browser/fake_js_autofill_manager.mm +++ b/components/autofill/ios/browser/fake_js_autofill_manager.mm
@@ -25,16 +25,14 @@ fieldIdentifier:(NSString*)fieldIdentifier inFrame:(web::WebFrame*)frame completionHandler:(ProceduralBlock)completionHandler { - base::PostTaskWithTraits(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ - _lastClearedFormName = [formName copy]; - _lastClearedFieldIdentifier = - [fieldIdentifier copy]; - _lastClearedFrameIdentifier = - frame ? base::SysUTF8ToNSString( - frame->GetFrameId()) - : nil; - completionHandler(); - })); + base::PostTask(FROM_HERE, {web::WebThread::UI}, base::BindOnce(^{ + _lastClearedFormName = [formName copy]; + _lastClearedFieldIdentifier = [fieldIdentifier copy]; + _lastClearedFrameIdentifier = + frame ? base::SysUTF8ToNSString(frame->GetFrameId()) + : nil; + completionHandler(); + })); } @end
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc index 764236a..72a2d52a 100644 --- a/components/autofill_assistant/browser/controller.cc +++ b/components/autofill_assistant/browser/controller.cc
@@ -563,11 +563,10 @@ if (periodic_script_check_scheduled_) return; periodic_script_check_scheduled_ = true; - base::PostDelayedTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&Controller::OnPeriodicScriptCheck, - weak_ptr_factory_.GetWeakPtr()), - settings_.periodic_script_check_interval); + base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&Controller::OnPeriodicScriptCheck, + weak_ptr_factory_.GetWeakPtr()), + settings_.periodic_script_check_interval); } void Controller::StopPeriodicScriptChecks() { @@ -597,11 +596,10 @@ } script_tracker()->CheckScripts(); - base::PostDelayedTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&Controller::OnPeriodicScriptCheck, - weak_ptr_factory_.GetWeakPtr()), - settings_.periodic_script_check_interval); + base::PostDelayedTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&Controller::OnPeriodicScriptCheck, + weak_ptr_factory_.GetWeakPtr()), + settings_.periodic_script_check_interval); } void Controller::OnGetScripts(const GURL& url,
diff --git a/components/autofill_assistant/browser/devtools/devtools_client.cc b/components/autofill_assistant/browser/devtools/devtools_client.cc index 4627fb6..3570c88 100644 --- a/components/autofill_assistant/browser/devtools/devtools_client.cc +++ b/components/autofill_assistant/browser/devtools/devtools_client.cc
@@ -29,8 +29,8 @@ renderer_crashed_(false), next_message_id_(0), weak_ptr_factory_(this) { - browser_main_thread_ = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + browser_main_thread_ = + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); agent_host_->AttachClient(this); }
diff --git a/components/autofill_assistant/browser/web_controller.cc b/components/autofill_assistant/browser/web_controller.cc index a9494a1..f00fe157 100644 --- a/components/autofill_assistant/browser/web_controller.cc +++ b/components/autofill_assistant/browser/web_controller.cc
@@ -590,7 +590,7 @@ } --remaining_rounds_; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &WebController::ElementPositionGetter::GetAndWaitBoxModelStable, @@ -608,7 +608,7 @@ } --remaining_rounds_; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &WebController::ElementPositionGetter::GetAndWaitBoxModelStable, @@ -1734,7 +1734,7 @@ } if (delay && delay_in_millisecond > 0) { - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&WebController::DispatchKeyboardTextDownEvent, weak_ptr_factory_.GetWeakPtr(), codepoints, index, @@ -2105,7 +2105,7 @@ return; } - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&WebController::WaitForDocumentToBecomeInteractive, weak_ptr_factory_.GetWeakPtr(), --remaining_rounds,
diff --git a/components/browser_watcher/watcher_metrics_provider_win.cc b/components/browser_watcher/watcher_metrics_provider_win.cc index b59f2b5a..905c96e1 100644 --- a/components/browser_watcher/watcher_metrics_provider_win.cc +++ b/components/browser_watcher/watcher_metrics_provider_win.cc
@@ -168,8 +168,8 @@ // Returns a task runner appropriate for running background tasks that perform // file I/O. scoped_refptr<base::TaskRunner> CreateBackgroundTaskRunner() { - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); }
diff --git a/components/cast_channel/cast_socket.cc b/components/cast_channel/cast_socket.cc index 8a5bbda..26ef514 100644 --- a/components/cast_channel/cast_socket.cc +++ b/components/cast_channel/cast_socket.cc
@@ -66,7 +66,7 @@ mojo::ScopedDataPipeConsumerHandle receive_stream, mojo::ScopedDataPipeProducerHandle send_stream) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(std::move(callback), result, local_addr, peer_addr, std::move(receive_stream), std::move(send_stream))); @@ -378,13 +378,12 @@ VLOG_WITH_CONNECTION(1) << "DoTcpConnect"; SetConnectState(ConnectionState::TCP_CONNECT_COMPLETE); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(ConnectOnUIThread, network_context_getter_, - net::AddressList(open_params_.ip_endpoint), - mojo::MakeRequest(&tcp_socket_), - base::BindOnce(&CastSocketImpl::OnConnect, - weak_factory_.GetWeakPtr()))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(ConnectOnUIThread, network_context_getter_, + net::AddressList(open_params_.ip_endpoint), + mojo::MakeRequest(&tcp_socket_), + base::BindOnce(&CastSocketImpl::OnConnect, + weak_factory_.GetWeakPtr()))); return net::ERR_IO_PENDING; }
diff --git a/components/cast_channel/cast_socket_service.cc b/components/cast_channel/cast_socket_service.cc index 201d19a..68776040 100644 --- a/components/cast_channel/cast_socket_service.cc +++ b/components/cast_channel/cast_socket_service.cc
@@ -23,8 +23,8 @@ // (1) ChromeURLRequestContextGetter::GetURLRequestContext, which is // called by CastMediaSinkServiceImpl, must run on IO thread. (2) Parts of // CastChannel extension API functions run on IO thread. - task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})) {} + task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})) {} // This is a leaky singleton and the dtor won't be called. CastSocketService::~CastSocketService() = default;
diff --git a/components/cdm/browser/cdm_message_filter_android.cc b/components/cdm/browser/cdm_message_filter_android.cc index ac36132..b5672631 100644 --- a/components/cdm/browser/cdm_message_filter_android.cc +++ b/components/cdm/browser/cdm_message_filter_android.cc
@@ -140,8 +140,9 @@ bool can_persist_data, bool force_to_support_secure_codecs) : BrowserMessageFilter(EncryptedMediaMsgStart), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})), + task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})), can_persist_data_(can_persist_data), force_to_support_secure_codecs_(force_to_support_secure_codecs) {}
diff --git a/components/component_updater/component_installer.cc b/components/component_updater/component_installer.cc index 2cf32b9c..e1e5fd2 100644 --- a/components/component_updater/component_installer.cc +++ b/components/component_updater/component_installer.cc
@@ -64,8 +64,8 @@ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Some components may affect user visible features, hence USER_VISIBLE. - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); if (!installer_policy_) {
diff --git a/components/component_updater/crl_set_remover.cc b/components/component_updater/crl_set_remover.cc index 2598e7d..d05e0c0 100644 --- a/components/component_updater/crl_set_remover.cc +++ b/components/component_updater/crl_set_remover.cc
@@ -11,8 +11,9 @@ namespace component_updater { void DeleteLegacyCRLSet(const base::FilePath& user_data_dir) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(base::IgnoreResult(&base::DeleteFile), user_data_dir.Append( FILE_PATH_LITERAL("Certificate Revocation Lists")),
diff --git a/components/crash/content/browser/child_process_crash_observer_android.cc b/components/crash/content/browser/child_process_crash_observer_android.cc index 814f704..16e202a4 100644 --- a/components/crash/content/browser/child_process_crash_observer_android.cc +++ b/components/crash/content/browser/child_process_crash_observer_android.cc
@@ -15,8 +15,8 @@ namespace crash_reporter { ChildProcessCrashObserver::ChildProcessCrashObserver() { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}); } ChildProcessCrashObserver::~ChildProcessCrashObserver() = default;
diff --git a/components/crash/content/browser/crash_handler_host_linux.cc b/components/crash/content/browser/crash_handler_host_linux.cc index 328ef3721..543ad7b 100644 --- a/components/crash/content/browser/crash_handler_host_linux.cc +++ b/components/crash/content/browser/crash_handler_host_linux.cc
@@ -118,8 +118,9 @@ upload_(upload), #endif fd_watch_controller_(FROM_HERE), - blocking_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE})) { + blocking_task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE})) { int fds[2]; // We use SOCK_SEQPACKET rather than SOCK_DGRAM to prevent the process from // sending datagrams to other sockets on the system. The sandbox may prevent @@ -136,7 +137,7 @@ process_socket_ = fds[0]; browser_socket_ = fds[1]; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CrashHandlerHostLinux::Init, base::Unretained(this))); } @@ -525,7 +526,7 @@ } int CrashHandlerHost::GetDeathSignalSocket() { - static bool initialized = base::PostTaskWithTraits( + static bool initialized = base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CrashHandlerHost::Init, base::Unretained(this))); DCHECK(initialized);
diff --git a/components/cronet/cronet_global_state_stubs.cc b/components/cronet/cronet_global_state_stubs.cc index 539fdf7..b0cedb38 100644 --- a/components/cronet/cronet_global_state_stubs.cc +++ b/components/cronet/cronet_global_state_stubs.cc
@@ -37,7 +37,7 @@ // ThreadPoolInstance themselves. base::ThreadPoolInstance::CreateAndStartWithDefaultParams("cronet"); - return base::CreateSingleThreadTaskRunnerWithTraits({}); + return base::CreateSingleThreadTaskRunner({base::ThreadPool()}); } base::SingleThreadTaskRunner* InitTaskRunner() {
diff --git a/components/data_reduction_proxy/content/common/data_reduction_proxy_url_loader_throttle_unittest.cc b/components/data_reduction_proxy/content/common/data_reduction_proxy_url_loader_throttle_unittest.cc index b4b3882..b479deda 100644 --- a/components/data_reduction_proxy/content/common/data_reduction_proxy_url_loader_throttle_unittest.cc +++ b/components/data_reduction_proxy/content/common/data_reduction_proxy_url_loader_throttle_unittest.cc
@@ -156,8 +156,7 @@ (net::HttpRequestHeaders()), manager.get()); throttle->DetachFromCurrentSequence(); - auto task_runner = - base::CreateSequencedTaskRunnerWithTraits(base::TaskTraits()); + auto task_runner = base::CreateSequencedTaskRunner({base::ThreadPool()}); task_runner->DeleteSoon(FROM_HERE, throttle.release()); }
diff --git a/components/dom_distiller/standalone/content_extractor_browsertest.cc b/components/dom_distiller/standalone/content_extractor_browsertest.cc index 4c45a46..345d2951 100644 --- a/components/dom_distiller/standalone/content_extractor_browsertest.cc +++ b/components/dom_distiller/standalone/content_extractor_browsertest.cc
@@ -132,7 +132,7 @@ const base::FilePath& db_path, const FileToUrlMap& file_to_url_map) { scoped_refptr<base::SequencedTaskRunner> background_task_runner = - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}); // Setting up PrefService for DistilledPagePrefs. DistilledPagePrefs::RegisterProfilePrefs(pref_service->registry());
diff --git a/components/download/database/download_db_impl.cc b/components/download/database/download_db_impl.cc index b1a5ca6..37aef16 100644 --- a/components/download/database/download_db_impl.cc +++ b/components/download/database/download_db_impl.cc
@@ -52,13 +52,12 @@ download_namespace, database_dir, leveldb_proto::ProtoDatabaseProvider::CreateUniqueDB< - download_pb::DownloadDBEntry>( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), - // USER_VISIBLE because it is required to display - // chrome://downloads. https://crbug.com/976223 - base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}))) {} + download_pb::DownloadDBEntry>(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + // USER_VISIBLE because it is required to display + // chrome://downloads. https://crbug.com/976223 + base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}))) {} DownloadDBImpl::DownloadDBImpl( DownloadNamespace download_namespace,
diff --git a/components/download/internal/common/download_item_impl.cc b/components/download/internal/common/download_item_impl.cc index 859d001..f0c6c33 100644 --- a/components/download/internal/common/download_item_impl.cc +++ b/components/download/internal/common/download_item_impl.cc
@@ -586,7 +586,9 @@ if (auto_resume_count_ >= kMaxAutoResumeAttempts) return; - ResumeInterruptedDownload(ResumptionRequestSource::USER); + ResumeInterruptedDownload(user_resume + ? ResumptionRequestSource::USER + : ResumptionRequestSource::AUTOMATIC); UpdateObservers(); return;
diff --git a/components/drive/file_system/operation_test_base.cc b/components/drive/file_system/operation_test_base.cc index 55c659c..c9c38f63 100644 --- a/components/drive/file_system/operation_test_base.cc +++ b/components/drive/file_system/operation_test_base.cc
@@ -62,7 +62,7 @@ void OperationTestBase::SetUp() { blocking_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}); pref_service_ = std::make_unique<TestingPrefServiceSimple>(); test_util::RegisterDrivePrefs(pref_service_->registry());
diff --git a/components/drive/file_write_watcher_unittest.cc b/components/drive/file_write_watcher_unittest.cc index c59fbd5..de1192a 100644 --- a/components/drive/file_write_watcher_unittest.cc +++ b/components/drive/file_write_watcher_unittest.cc
@@ -91,7 +91,7 @@ // Set up the watcher. scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}); FileWriteWatcher watcher(task_runner.get()); watcher.DisableDelayForTesting();
diff --git a/components/exo/data_offer.cc b/components/exo/data_offer.cc index 3301fbd..8300bb9 100644 --- a/components/exo/data_offer.cc +++ b/components/exo/data_offer.cc
@@ -74,8 +74,9 @@ void WriteFileDescriptor(base::ScopedFD fd, scoped_refptr<base::RefCountedMemory> memory) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&WriteFileDescriptorOnWorkerThread, std::move(fd), std::move(memory))); } @@ -157,8 +158,9 @@ void ReadPNGFromClipboard(base::ScopedFD fd) { const SkBitmap sk_bitmap = ui::Clipboard::GetForCurrentThread()->ReadImage( ui::ClipboardType::kCopyPaste); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&SendAsPNGOnWorkerThread, std::move(fd), std::move(sk_bitmap))); }
diff --git a/components/exo/data_offer.h b/components/exo/data_offer.h index c891e900..d3c53c03 100644 --- a/components/exo/data_offer.h +++ b/components/exo/data_offer.h
@@ -42,7 +42,7 @@ }; DataOffer(DataOfferDelegate* delegate, Purpose purpose); - ~DataOffer(); + ~DataOffer() override; void AddObserver(DataOfferObserver* observer); void RemoveObserver(DataOfferObserver* observer);
diff --git a/components/exo/data_source.cc b/components/exo/data_source.cc index 93b0b33..65bac63 100644 --- a/components/exo/data_source.cc +++ b/components/exo/data_source.cc
@@ -215,9 +215,9 @@ PCHECK(base::CreatePipe(&read_fd, &write_fd)); delegate_->OnSend(mime_type, std::move(write_fd)); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&ReadDataOnWorkerThread, std::move(read_fd)), base::BindOnce(&DataSource::OnDataRead,
diff --git a/components/exo/fullscreen_shell_surface.cc b/components/exo/fullscreen_shell_surface.cc index 310e0db..961d062 100644 --- a/components/exo/fullscreen_shell_surface.cc +++ b/components/exo/fullscreen_shell_surface.cc
@@ -212,7 +212,7 @@ params.bounds = gfx::Rect(params.parent->bounds().size()); widget_ = new views::Widget(); - widget_->Init(params); + widget_->Init(std::move(params)); aura::Window* window = widget_->GetNativeWindow(); window->SetName("FullscreenShellSurface");
diff --git a/components/exo/shell_surface_base.cc b/components/exo/shell_surface_base.cc index 9d4bc44..2cc63241 100644 --- a/components/exo/shell_surface_base.cc +++ b/components/exo/shell_surface_base.cc
@@ -889,7 +889,7 @@ : views::Widget::InitParams::ACTIVATABLE_NO; // Note: NativeWidget owns this widget. widget_ = new ShellSurfaceWidget; - widget_->Init(params); + widget_->Init(std::move(params)); aura::Window* window = widget_->GetNativeWindow(); window->SetName("ExoShellSurface");
diff --git a/components/exo/surface.h b/components/exo/surface.h index a99c0bb..2feb1f3 100644 --- a/components/exo/surface.h +++ b/components/exo/surface.h
@@ -67,7 +67,7 @@ using PropertyDeallocator = void (*)(int64_t value); Surface(); - ~Surface(); + ~Surface() override; // Type-checking downcast routine. static Surface* AsSurface(const aura::Window* window);
diff --git a/components/exo/wayland/zaura_shell_unittest.cc b/components/exo/wayland/zaura_shell_unittest.cc index 8b08f93..de042dc 100644 --- a/components/exo/wayland/zaura_shell_unittest.cc +++ b/components/exo/wayland/zaura_shell_unittest.cc
@@ -203,7 +203,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = CurrentContext(); params.bounds = gfx::Rect(0, 0, 100, 100); - lock_widget->Init(params); + lock_widget->Init(std::move(params)); ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), ash::kShellWindowId_LockScreenContainer) ->AddChild(lock_widget->GetNativeView());
diff --git a/components/favicon/core/large_icon_service_impl.cc b/components/favicon/core/large_icon_service_impl.cc index 254f5af..bec51440 100644 --- a/components/favicon/core/large_icon_service_impl.cc +++ b/components/favicon/core/large_icon_service_impl.cc
@@ -308,8 +308,9 @@ desired_size_in_pixel_(desired_size_in_pixel), raw_bitmap_callback_(std::move(raw_bitmap_callback)), image_callback_(std::move(image_callback)), - background_task_runner_(base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + background_task_runner_(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), tracker_(tracker), fallback_icon_style_(
diff --git a/components/feed/core/feed_content_database.cc b/components/feed/core/feed_content_database.cc index 359ebbb..da4d432 100644 --- a/components/feed/core/feed_content_database.cc +++ b/components/feed/core/feed_content_database.cc
@@ -54,8 +54,9 @@ : FeedContentDatabase(proto_database_provider->GetDB<ContentStorageProto>( leveldb_proto::ProtoDbType::FEED_CONTENT_DATABASE, database_folder.AppendASCII(kContentDatabaseFolder), - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}))) {} FeedContentDatabase::FeedContentDatabase(
diff --git a/components/feed/core/feed_journal_database.cc b/components/feed/core/feed_journal_database.cc index c0f8105..0030fad 100644 --- a/components/feed/core/feed_journal_database.cc +++ b/components/feed/core/feed_journal_database.cc
@@ -42,8 +42,9 @@ : FeedJournalDatabase(proto_database_provider->GetDB<JournalStorageProto>( leveldb_proto::ProtoDbType::FEED_JOURNAL_DATABASE, database_folder.AppendASCII(kJournalDatabaseFolder), - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}))) {} FeedJournalDatabase::FeedJournalDatabase(
diff --git a/components/feedback/anonymizer_tool.cc b/components/feedback/anonymizer_tool.cc index 4f77281..64384c02 100644 --- a/components/feedback/anonymizer_tool.cc +++ b/components/feedback/anonymizer_tool.cc
@@ -7,6 +7,7 @@ #include <memory> #include <utility> +#include "base/files/file_path.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -351,6 +352,14 @@ base::size(args)); } +// The following MAC addresses will not be anonymized as they are not specific +// to a device but have general meanings. +const char* const kNonAnonymizedMacAddresses[] = { + "00:00:00:00:00:00", // ARP failure result MAC. + "ff:ff:ff:ff:ff:ff", // Broadcast MAC. +}; +constexpr size_t kNumNonAnonymizedMacs = base::size(kNonAnonymizedMacAddresses); + } // namespace AnonymizerTool::AnonymizerTool(const char* const* first_party_extension_ids) @@ -359,6 +368,9 @@ custom_patterns_without_context_( base::size(kCustomPatternsWithoutContext)) { DETACH_FROM_SEQUENCE(sequence_checker_); + // Identity-map these, so we don't mangle them. + for (const char* mac : kNonAnonymizedMacAddresses) + mac_addresses_[mac] = mac; } AnonymizerTool::~AnonymizerTool() { @@ -371,6 +383,7 @@ << "This is an expensive operation. Do not execute this on the UI " "thread."; std::string anonymized = AnonymizeMACAddresses(input); + anonymized = AnonymizeAndroidAppStoragePaths(std::move(anonymized)); anonymized = AnonymizeCustomPatterns(std::move(anonymized)); return anonymized; } @@ -417,10 +430,9 @@ if (replacement_mac.empty()) { // If not found, build up a replacement MAC address by generating a new // NIC part. - int mac_id = mac_addresses_.size(); - replacement_mac = base::StringPrintf( - "%s:%02x:%02x:%02x", oui_string.c_str(), (mac_id & 0x00ff0000) >> 16, - (mac_id & 0x0000ff00) >> 8, (mac_id & 0x000000ff)); + int mac_id = mac_addresses_.size() - kNumNonAnonymizedMacs; + replacement_mac = base::StringPrintf("[MAC OUI=%s IFACE=%d]", + oui_string.c_str(), mac_id); mac_addresses_[mac] = replacement_mac; } @@ -432,6 +444,62 @@ return result; } +std::string AnonymizerTool::AnonymizeAndroidAppStoragePaths( + const std::string& input) { + // We only use this on Chrome OS and there's differences in the API for + // FilePath on Windows which prevents this from compiling, so only enable this + // code for Chrome OS. +#if defined(OS_CHROMEOS) + std::string result; + result.reserve(input.size()); + + // This is for anonymizing 'android_app_storage' output. When the path starts + // either /home/root/<hash>/data/data/<package_name>/ or + // /home/root/<hash>/data/user_de/<number>/<package_name>/, this function will + // anonymize path components following <package_name>/. + RE2* path_re = GetRegExp( + "(?m)(\\t/home/root/[\\da-f]+/android-data/data/" + "(data|user_de/\\d+)/[^/\\n]+)(" + "/[^\\n]+)"); + + // Keep consuming, building up a result string as we go. + re2::StringPiece text(input); + re2::StringPiece skipped, path_prefix, ignored, app_specific; + while (FindAndConsumeAndGetSkipped(&text, *path_re, &skipped, &path_prefix, + &ignored, &app_specific)) { + // We can record these parts as-is. + skipped.AppendToString(&result); + path_prefix.AppendToString(&result); + + // |app_specific| has to be anonymized. First, convert it into components, + // and then anonymize each component as follows: + // - If the component has a non-ASCII character, change it to '*'. + // - Otherwise, remove all the characters in the component but the first + // one. + // - If the original component has 2 or more bytes, add '_'. + const base::FilePath path(app_specific.as_string()); + std::vector<std::string> components; + path.GetComponents(&components); + DCHECK(!components.empty()); + + auto it = components.begin() + 1; // ignore the leading slash + for (; it != components.end(); ++it) { + const auto& component = *it; + DCHECK(!component.empty()); + result += '/'; + result += (base::IsStringASCII(component) ? component[0] : '*'); + if (component.length() > 1) + result += '_'; + } + } + + text.AppendToString(&result); + return result; +#else + return input; +#endif // defined(OS_CHROMEOS) +} + std::string AnonymizerTool::AnonymizeCustomPatterns(std::string input) { for (size_t i = 0; i < base::size(kCustomPatternsWithContext); i++) { input =
diff --git a/components/feedback/anonymizer_tool.h b/components/feedback/anonymizer_tool.h index 9aea4ba..963eb0e4 100644 --- a/components/feedback/anonymizer_tool.h +++ b/components/feedback/anonymizer_tool.h
@@ -50,6 +50,7 @@ re2::RE2* GetRegExp(const std::string& pattern); std::string AnonymizeMACAddresses(const std::string& input); + std::string AnonymizeAndroidAppStoragePaths(const std::string& input); std::string AnonymizeCustomPatterns(std::string input); std::string AnonymizeCustomPatternWithContext( const std::string& input,
diff --git a/components/feedback/anonymizer_tool_unittest.cc b/components/feedback/anonymizer_tool_unittest.cc index 7a8faecb..63fafea 100644 --- a/components/feedback/anonymizer_tool_unittest.cc +++ b/components/feedback/anonymizer_tool_unittest.cc
@@ -19,6 +19,10 @@ return anonymizer_.AnonymizeMACAddresses(input); } + std::string AnonymizeAndroidAppStoragePaths(const std::string& input) { + return anonymizer_.AnonymizeAndroidAppStoragePaths(input); + } + std::string AnonymizeCustomPatterns(const std::string& input) { return anonymizer_.AnonymizeCustomPatterns(input); } @@ -46,7 +50,8 @@ EXPECT_EQ("foo\nbar\n", anonymizer_.Anonymize("foo\nbar\n")); // Make sure MAC address anonymization is invoked. - EXPECT_EQ("02:46:8a:00:00:01", anonymizer_.Anonymize("02:46:8a:ce:13:57")); + EXPECT_EQ("[MAC OUI=02:46:8a IFACE=1]", + anonymizer_.Anonymize("02:46:8a:ce:13:57")); // Make sure custom pattern anonymization is invoked. EXPECT_EQ("Cell ID: '1'", AnonymizeCustomPatterns("Cell ID: 'A1B2'")); @@ -72,21 +77,24 @@ EXPECT_EQ("", AnonymizeMACAddresses("")); EXPECT_EQ("foo\nbar\n", AnonymizeMACAddresses("foo\nbar\n")); EXPECT_EQ("11:22:33:44:55", AnonymizeMACAddresses("11:22:33:44:55")); - EXPECT_EQ("aa:bb:cc:00:00:01", AnonymizeMACAddresses("aa:bb:cc:dd:ee:ff")); + EXPECT_EQ("[MAC OUI=aa:bb:cc IFACE=1]", + AnonymizeMACAddresses("aa:bb:cc:dd:ee:ff")); + EXPECT_EQ("00:00:00:00:00:00", AnonymizeMACAddresses("00:00:00:00:00:00")); + EXPECT_EQ("ff:ff:ff:ff:ff:ff", AnonymizeMACAddresses("ff:ff:ff:ff:ff:ff")); EXPECT_EQ( - "BSSID: aa:bb:cc:00:00:01 in the middle\n" - "bb:cc:dd:00:00:02 start of line\n" - "end of line aa:bb:cc:00:00:01\n" + "BSSID: [MAC OUI=aa:bb:cc IFACE=1] in the middle\n" + "[MAC OUI=bb:cc:dd IFACE=2] start of line\n" + "end of line [MAC OUI=aa:bb:cc IFACE=1]\n" "no match across lines aa:bb:cc:\n" "dd:ee:ff two on the same line:\n" - "x bb:cc:dd:00:00:02 cc:dd:ee:00:00:03 x\n", + "x [MAC OUI=bb:cc:dd IFACE=2] [MAC OUI=cc:dd:ee IFACE=3] x\n", AnonymizeMACAddresses("BSSID: aa:bb:cc:dd:ee:ff in the middle\n" "bb:cc:dd:ee:ff:00 start of line\n" "end of line aa:bb:cc:dd:ee:ff\n" "no match across lines aa:bb:cc:\n" "dd:ee:ff two on the same line:\n" "x bb:cc:dd:ee:ff:00 cc:dd:ee:ff:00:11 x\n")); - EXPECT_EQ("Remember bb:cc:dd:00:00:02?", + EXPECT_EQ("Remember [MAC OUI=bb:cc:dd IFACE=2]?", AnonymizeMACAddresses("Remember bB:Cc:DD:ee:ff:00?")); } @@ -216,149 +224,157 @@ // of pairs, and then convert that to two strings which become the input and // output of the anonymizer. std::pair<std::string, std::string> data[] = { - {"aaaaaaaa [SSID=123aaaaaa]aaaaa", // SSID. - "aaaaaaaa [SSID=1]aaaaa"}, - {"aaaaaaaahttp://tets.comaaaaaaa", // URL. - "aaaaaaaa<URL: 1>"}, - {"aaaaaemail@example.comaaa", // Email address. - "<email: 1>"}, - {"example@@1234", // No PII, it is not invalid email address. - "example@@1234"}, - {"255.255.155.2", // IP address. - "<IPv4: 1>"}, - {"255.255.155.255", // IP address. - "<IPv4: 2>"}, - {"127.0.0.1", // IPv4 loopback. - "<127.0.0.0/8: 3>"}, - {"127.255.0.1", // IPv4 loopback. - "<127.0.0.0/8: 4>"}, - {"0.0.0.0", // Any IPv4. - "<0.0.0.0/8: 5>"}, - {"0.255.255.255", // Any IPv4. - "<0.0.0.0/8: 6>"}, - {"10.10.10.100", // IPv4 private class A. - "<10.0.0.0/8: 7>"}, - {"10.10.10.100", // Intentional duplicate. - "<10.0.0.0/8: 7>"}, - {"10.10.10.101", // IPv4 private class A. - "<10.0.0.0/8: 8>"}, - {"10.255.255.255", // IPv4 private class A. - "<10.0.0.0/8: 9>"}, - {"172.16.0.0", // IPv4 private class B. - "<172.16.0.0/12: 10>"}, - {"172.31.255.255", // IPv4 private class B. - "<172.16.0.0/12: 11>"}, - {"172.11.5.5", // IP address. - "<IPv4: 12>"}, - {"172.111.5.5", // IP address. - "<IPv4: 13>"}, - {"192.168.0.0", // IPv4 private class C. - "<192.168.0.0/16: 14>"}, - {"192.168.255.255", // IPv4 private class C. - "<192.168.0.0/16: 15>"}, - {"192.169.2.120", // IP address. - "<IPv4: 16>"}, - {"169.254.0.1", // Link local. - "<169.254.0.0/16: 17>"}, - {"169.200.0.1", // IP address. - "<IPv4: 18>"}, - {"fe80::", // Link local. - "<fe80::/10: 1>"}, - {"fe80::ffff", // Link local. - "<fe80::/10: 2>"}, - {"febf:ffff::ffff", // Link local. - "<fe80::/10: 3>"}, - {"fecc::1111", // IP address. - "<IPv6: 4>"}, - {"224.0.0.24", // Multicast. - "<224.0.0.0/4: 19>"}, - {"240.0.0.0", // IP address. - "<IPv4: 20>"}, - {"255.255.255.255", // Broadcast. - "255.255.255.255"}, - {"100.115.92.92", // ChromeOS. - "100.115.92.92"}, - {"100.115.91.92", // IP address. - "<IPv4: 23>"}, - {"1.1.1.1", // DNS - "1.1.1.1"}, - {"8.8.8.8", // DNS - "8.8.8.8"}, - {"8.8.4.4", // DNS - "8.8.4.4"}, - {"8.8.8.4", // IP address. - "<IPv4: 27>"}, - {"255.255.259.255", // Not an IP address. - "255.255.259.255"}, - {"255.300.255.255", // Not an IP address. - "255.300.255.255"}, - {"aaaa123.123.45.4aaa", // IP address. - "aaaa<IPv4: 28>aaa"}, - {"11:11;11::11", // IP address. - "11:11;<IPv6: 5>"}, - {"11::11", // IP address. - "<IPv6: 5>"}, - {"11:11:abcdef:0:0:0:0:0", // No PII. - "11:11:abcdef:0:0:0:0:0"}, - {"::", // Unspecified. - "::"}, - {"::1", // Local host. - "::1"}, - {"Instance::Set", // Ignore match, no PII. - "Instance::Set"}, - {"Instant::ff", // Ignore match, no PII. - "Instant::ff"}, - {"net::ERR_CONN_TIMEOUT", // Ignore match, no PII. - "net::ERR_CONN_TIMEOUT"}, - {"ff01::1", // All nodes address (interface local). - "ff01::1"}, - {"ff01::2", // All routers (interface local). - "ff01::2"}, - {"ff01::3", // Multicast (interface local). - "<ff01::/16: 13>"}, - {"ff02::1", // All nodes address (link local). - "ff02::1"}, - {"ff02::2", // All routers (link local). - "ff02::2"}, - {"ff02::3", // Multicast (link local). - "<ff02::/16: 16>"}, - {"ff02::fb", // mDNSv6 (link local). - "<ff02::/16: 17>"}, - {"ff08::fb", // mDNSv6. - "<IPv6: 18>"}, - {"ff0f::101", // All NTP servers. - "<IPv6: 19>"}, - {"::ffff:cb0c:10ea", // IPv4-mapped IPV6 (IP address). - "<IPv6: 20>"}, - {"::ffff:a0a:a0a", // IPv4-mapped IPV6 (private class A). - "<M 10.0.0.0/8: 21>"}, - {"::ffff:a0a:a0a", // Intentional duplicate. - "<M 10.0.0.0/8: 21>"}, - {"::ffff:ac1e:1e1e", // IPv4-mapped IPV6 (private class B). - "<M 172.16.0.0/12: 22>"}, - {"::ffff:c0a8:640a", // IPv4-mapped IPV6 (private class C). - "<M 192.168.0.0/16: 23>"}, - {"::ffff:6473:5c01", // IPv4-mapped IPV6 (Chrome). - "<M 100.115.92.1: 24>"}, - {"64:ff9b::a0a:a0a", // IPv4-translated 6to4 IPV6 (private class A). - "<T 10.0.0.0/8: 25>"}, - {"64:ff9b::6473:5c01", // IPv4-translated 6to4 IPV6 (Chrome). - "<T 100.115.92.1: 26>"}, - {"::0101:ffff:c0a8:640a", // IP address. - "<IPv6: 27>"}, - {"aa:aa:aa:aa:aa:aa", // MAC address (BSSID). - "aa:aa:aa:00:00:01"}, - {"chrome://resources/foo", // Secure chrome resource, whitelisted. - "chrome://resources/foo"}, - {"chrome://settings/crisper.js", // Whitelisted settings URLs. - "chrome://settings/crisper.js"}, - // Whitelisted first party extension. - {"chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js", - "chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js"}, - {"chrome://resources/f?user=bar", // Potentially PII in parameter. - "<URL: 2>"}, - {"chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js?bar=x", - "<URL: 3>"}, // Potentially PII in parameter. + {"aaaaaaaa [SSID=123aaaaaa]aaaaa", // SSID. + "aaaaaaaa [SSID=1]aaaaa"}, + {"aaaaaaaahttp://tets.comaaaaaaa", // URL. + "aaaaaaaa<URL: 1>"}, + {"aaaaaemail@example.comaaa", // Email address. + "<email: 1>"}, + {"example@@1234", // No PII, it is not invalid email address. + "example@@1234"}, + {"255.255.155.2", // IP address. + "<IPv4: 1>"}, + {"255.255.155.255", // IP address. + "<IPv4: 2>"}, + {"127.0.0.1", // IPv4 loopback. + "<127.0.0.0/8: 3>"}, + {"127.255.0.1", // IPv4 loopback. + "<127.0.0.0/8: 4>"}, + {"0.0.0.0", // Any IPv4. + "<0.0.0.0/8: 5>"}, + {"0.255.255.255", // Any IPv4. + "<0.0.0.0/8: 6>"}, + {"10.10.10.100", // IPv4 private class A. + "<10.0.0.0/8: 7>"}, + {"10.10.10.100", // Intentional duplicate. + "<10.0.0.0/8: 7>"}, + {"10.10.10.101", // IPv4 private class A. + "<10.0.0.0/8: 8>"}, + {"10.255.255.255", // IPv4 private class A. + "<10.0.0.0/8: 9>"}, + {"172.16.0.0", // IPv4 private class B. + "<172.16.0.0/12: 10>"}, + {"172.31.255.255", // IPv4 private class B. + "<172.16.0.0/12: 11>"}, + {"172.11.5.5", // IP address. + "<IPv4: 12>"}, + {"172.111.5.5", // IP address. + "<IPv4: 13>"}, + {"192.168.0.0", // IPv4 private class C. + "<192.168.0.0/16: 14>"}, + {"192.168.255.255", // IPv4 private class C. + "<192.168.0.0/16: 15>"}, + {"192.169.2.120", // IP address. + "<IPv4: 16>"}, + {"169.254.0.1", // Link local. + "<169.254.0.0/16: 17>"}, + {"169.200.0.1", // IP address. + "<IPv4: 18>"}, + {"fe80::", // Link local. + "<fe80::/10: 1>"}, + {"fe80::ffff", // Link local. + "<fe80::/10: 2>"}, + {"febf:ffff::ffff", // Link local. + "<fe80::/10: 3>"}, + {"fecc::1111", // IP address. + "<IPv6: 4>"}, + {"224.0.0.24", // Multicast. + "<224.0.0.0/4: 19>"}, + {"240.0.0.0", // IP address. + "<IPv4: 20>"}, + {"255.255.255.255", // Broadcast. + "255.255.255.255"}, + {"100.115.92.92", // ChromeOS. + "100.115.92.92"}, + {"100.115.91.92", // IP address. + "<IPv4: 23>"}, + {"1.1.1.1", // DNS + "1.1.1.1"}, + {"8.8.8.8", // DNS + "8.8.8.8"}, + {"8.8.4.4", // DNS + "8.8.4.4"}, + {"8.8.8.4", // IP address. + "<IPv4: 27>"}, + {"255.255.259.255", // Not an IP address. + "255.255.259.255"}, + {"255.300.255.255", // Not an IP address. + "255.300.255.255"}, + {"aaaa123.123.45.4aaa", // IP address. + "aaaa<IPv4: 28>aaa"}, + {"11:11;11::11", // IP address. + "11:11;<IPv6: 5>"}, + {"11::11", // IP address. + "<IPv6: 5>"}, + {"11:11:abcdef:0:0:0:0:0", // No PII. + "11:11:abcdef:0:0:0:0:0"}, + {"::", // Unspecified. + "::"}, + {"::1", // Local host. + "::1"}, + {"Instance::Set", // Ignore match, no PII. + "Instance::Set"}, + {"Instant::ff", // Ignore match, no PII. + "Instant::ff"}, + {"net::ERR_CONN_TIMEOUT", // Ignore match, no PII. + "net::ERR_CONN_TIMEOUT"}, + {"ff01::1", // All nodes address (interface local). + "ff01::1"}, + {"ff01::2", // All routers (interface local). + "ff01::2"}, + {"ff01::3", // Multicast (interface local). + "<ff01::/16: 13>"}, + {"ff02::1", // All nodes address (link local). + "ff02::1"}, + {"ff02::2", // All routers (link local). + "ff02::2"}, + {"ff02::3", // Multicast (link local). + "<ff02::/16: 16>"}, + {"ff02::fb", // mDNSv6 (link local). + "<ff02::/16: 17>"}, + {"ff08::fb", // mDNSv6. + "<IPv6: 18>"}, + {"ff0f::101", // All NTP servers. + "<IPv6: 19>"}, + {"::ffff:cb0c:10ea", // IPv4-mapped IPV6 (IP address). + "<IPv6: 20>"}, + {"::ffff:a0a:a0a", // IPv4-mapped IPV6 (private class A). + "<M 10.0.0.0/8: 21>"}, + {"::ffff:a0a:a0a", // Intentional duplicate. + "<M 10.0.0.0/8: 21>"}, + {"::ffff:ac1e:1e1e", // IPv4-mapped IPV6 (private class B). + "<M 172.16.0.0/12: 22>"}, + {"::ffff:c0a8:640a", // IPv4-mapped IPV6 (private class C). + "<M 192.168.0.0/16: 23>"}, + {"::ffff:6473:5c01", // IPv4-mapped IPV6 (Chrome). + "<M 100.115.92.1: 24>"}, + {"64:ff9b::a0a:a0a", // IPv4-translated 6to4 IPV6 (private class A). + "<T 10.0.0.0/8: 25>"}, + {"64:ff9b::6473:5c01", // IPv4-translated 6to4 IPV6 (Chrome). + "<T 100.115.92.1: 26>"}, + {"::0101:ffff:c0a8:640a", // IP address. + "<IPv6: 27>"}, + {"aa:aa:aa:aa:aa:aa", // MAC address (BSSID). + "[MAC OUI=aa:aa:aa IFACE=1]"}, + {"chrome://resources/foo", // Secure chrome resource, whitelisted. + "chrome://resources/foo"}, + {"chrome://settings/crisper.js", // Whitelisted settings URLs. + "chrome://settings/crisper.js"}, + // Whitelisted first party extension. + {"chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js", + "chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js"}, + {"chrome://resources/f?user=bar", // Potentially PII in parameter. + "<URL: 2>"}, + {"chrome-extension://nkoccljplnhpfnfiajclkommnmllphnl/foobar.js?bar=x", + "<URL: 3>"}, // Potentially PII in parameter. +#if defined(OS_CHROMEOS) // We only anonymize Android paths on Chrome OS. + // Allowed android storage path. + {"112K\t/home/root/deadbeef1234/android-data/data/system_de", + "112K\t/home/root/deadbeef1234/android-data/data/system_de"}, + // Anonymized app-specific storage path. + {"8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/de", + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/d_"}, +#endif // defined(OS_CHROMEOS) }; std::string anon_input; std::string anon_output; @@ -369,4 +385,53 @@ EXPECT_EQ(anon_output, anonymizer_.Anonymize(anon_input)); } +#if defined(OS_CHROMEOS) // We only anonymize Android paths on Chrome OS. +TEST_F(AnonymizerToolTest, AnonymizeAndroidAppStoragePaths) { + EXPECT_EQ("", AnonymizeAndroidAppStoragePaths("")); + EXPECT_EQ("foo\nbar\n", AnonymizeAndroidAppStoragePaths("foo\nbar\n")); + + constexpr char kDuOutput[] = + "112K\t/home/root/deadbeef1234/android-data/data/system_de\n" + // /data/data will be modified by the anonymizer. + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pack.age1/bc\n" + "24K\t/home/root/deadbeef1234/android-data/data/data/pack.age1\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/de\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/de/" + "\xe3\x81\x82\n" + "8.1K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/de/" + "\xe3\x81\x82\xe3\x81\x83\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/ef\n" + "24K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2\n" + // /data/app won't. + "8.0K\t/home/root/deadbeef1234/android-data/data/app/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/app/pack.age1/bc\n" + "24K\t/home/root/deadbeef1234/android-data/data/app/pack.age1\n" + // /data/user_de will. + "8.0K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1/bc\n" + "24K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1\n" + "78M\t/home/root/deadbeef1234/android-data/data/data\n"; + constexpr char kDuOutputRedacted[] = + "112K\t/home/root/deadbeef1234/android-data/data/system_de\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pack.age1/b_\n" + "24K\t/home/root/deadbeef1234/android-data/data/data/pack.age1\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/d_\n" + // The non-ASCII directory names will become '*_'. + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/d_/*_\n" + "8.1K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/d_/*_\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2/e_\n" + "24K\t/home/root/deadbeef1234/android-data/data/data/pa.ckage2\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/app/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/app/pack.age1/bc\n" + "24K\t/home/root/deadbeef1234/android-data/data/app/pack.age1\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1/a\n" + "8.0K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1/b_\n" + "24K\t/home/root/deadbeef1234/android-data/data/user_de/0/pack.age1\n" + "78M\t/home/root/deadbeef1234/android-data/data/data\n"; + EXPECT_EQ(kDuOutputRedacted, AnonymizeAndroidAppStoragePaths(kDuOutput)); +} +#endif // defined(OS_CHROMEOS) + } // namespace feedback
diff --git a/components/feedback/feedback_data.cc b/components/feedback/feedback_data.cc index 91cc10eb..0264e5a 100644 --- a/components/feedback/feedback_data.cc +++ b/components/feedback/feedback_data.cc
@@ -69,8 +69,9 @@ } ++pending_op_count_; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&FeedbackData::CompressLogs, this), base::BindOnce(&FeedbackData::OnCompressComplete, this)); } @@ -79,8 +80,9 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); ++pending_op_count_; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&FeedbackData::CompressFile, this, base::FilePath(kHistogramsFilename), kHistogramsAttachmentName, std::move(histograms)), @@ -95,8 +97,9 @@ ++pending_op_count_; base::FilePath attached_file = base::FilePath::FromUTF8Unsafe(attached_filename_); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&FeedbackData::CompressFile, this, attached_file, std::string(), std::move(attached_filedata)), base::BindOnce(&FeedbackData::OnCompressComplete, this));
diff --git a/components/feedback/feedback_uploader_factory.cc b/components/feedback/feedback_uploader_factory.cc index 18788074..b8f034b 100644 --- a/components/feedback/feedback_uploader_factory.cc +++ b/components/feedback/feedback_uploader_factory.cc
@@ -32,8 +32,8 @@ FeedbackUploaderFactory::CreateUploaderTaskRunner() { // Uses a BLOCK_SHUTDOWN file task runner because we really don't want to // lose reports or corrupt their files. - return base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + return base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); }
diff --git a/components/feedback/system_logs/system_logs_fetcher.cc b/components/feedback/system_logs/system_logs_fetcher.cc index 62ed817..6b061a58 100644 --- a/components/feedback/system_logs/system_logs_fetcher.cc +++ b/components/feedback/system_logs/system_logs_fetcher.cc
@@ -51,9 +51,10 @@ const char* const first_party_extension_ids[]) : response_(std::make_unique<SystemLogsResponse>()), num_pending_requests_(0), - task_runner_for_anonymizer_(base::CreateSequencedTaskRunnerWithTraits( - {// User visible because this is called when the user is looking at - // the send feedback dialog, watching a spinner. + task_runner_for_anonymizer_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), // User visible because this is called when the + // user is looking at the send feedback dialog, + // watching a spinner. base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})) { if (scrub_data)
diff --git a/components/gcm_driver/fake_gcm_profile_service.cc b/components/gcm_driver/fake_gcm_profile_service.cc index dd4da997..c875d5c 100644 --- a/components/gcm_driver/fake_gcm_profile_service.cc +++ b/components/gcm_driver/fake_gcm_profile_service.cc
@@ -38,6 +38,16 @@ void OnDispatchMessage(const std::string& app_id, const IncomingMessage& message); + // instance_id::FakeGCMDriverForInstanceID overrides: + void SendWebPushMessage(const std::string& app_id, + const std::string& authorized_entity, + const std::string& p256dh, + const std::string& auth_secret, + const std::string& fcm_token, + crypto::ECPrivateKey* vapid_key, + gcm::WebPushMessage message, + SendWebPushMessageCallback callback) override; + protected: // FakeGCMDriver overrides: void RegisterImpl(const std::string& app_id, @@ -152,6 +162,21 @@ app_id, receiver_id, message)); } +void FakeGCMProfileService::CustomFakeGCMDriver::SendWebPushMessage( + const std::string& app_id, + const std::string& authorized_entity, + const std::string& p256dh, + const std::string& auth_secret, + const std::string& fcm_token, + crypto::ECPrivateKey* vapid_key, + gcm::WebPushMessage message, + SendWebPushMessageCallback callback) { + if (service_->collect_) { + service_->last_receiver_id_ = fcm_token; + service_->last_web_push_message_ = std::move(message); + } +} + void FakeGCMProfileService::CustomFakeGCMDriver::DoSend( const std::string& app_id, const std::string& receiver_id,
diff --git a/components/gcm_driver/fake_gcm_profile_service.h b/components/gcm_driver/fake_gcm_profile_service.h index 8302eb63..fd6cd549 100644 --- a/components/gcm_driver/fake_gcm_profile_service.h +++ b/components/gcm_driver/fake_gcm_profile_service.h
@@ -39,6 +39,10 @@ return last_sent_message_; } + const WebPushMessage& last_web_push_message() const { + return last_web_push_message_; + } + const std::string& last_receiver_id() const { return last_receiver_id_; } const std::string& last_registered_app_id() const { @@ -69,6 +73,7 @@ std::list<GCMClient::Result> unregister_responses_; OutgoingMessage last_sent_message_; std::string last_receiver_id_; + WebPushMessage last_web_push_message_; DISALLOW_COPY_AND_ASSIGN(FakeGCMProfileService); };
diff --git a/components/google/OWNERS b/components/google/OWNERS index 558e5509..1461f9d 100644 --- a/components/google/OWNERS +++ b/components/google/OWNERS
@@ -2,3 +2,4 @@ pkasting@chromium.org # COMPONENT: Internals +# TEAM: chromium-dev@chromium.org
diff --git a/components/google/core/browser/BUILD.gn b/components/google/core/browser/BUILD.gn deleted file mode 100644 index 22f7273..0000000 --- a/components/google/core/browser/BUILD.gn +++ /dev/null
@@ -1,49 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -static_library("browser") { - sources = [ - "google_pref_names.cc", - "google_pref_names.h", - "google_url_tracker.cc", - "google_url_tracker.h", - "google_url_tracker_client.cc", - "google_url_tracker_client.h", - ] - - public_deps = [ - "//base", - "//components/google/core/common", - "//components/keyed_service/core", - "//url", - ] - - deps = [ - "//components/pref_registry", - "//components/prefs", - "//components/strings", - "//services/network/public/cpp", - "//services/network/public/mojom", - ] -} - -source_set("unit_tests") { - testonly = true - - sources = [ - "google_url_tracker_unittest.cc", - "google_util_unittest.cc", - ] - - deps = [ - ":browser", - "//base", - "//components/prefs:test_support", - "//net:test_support", - "//services/network:test_support", - "//services/network/public/cpp", - "//services/network/public/mojom", - "//testing/gtest", - ] -}
diff --git a/components/google/core/browser/DEPS b/components/google/core/browser/DEPS deleted file mode 100644 index 5f1bc003..0000000 --- a/components/google/core/browser/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+components/keyed_service/core", - "+components/prefs", - "+components/pref_registry", - "+services/network/public", - "+services/network/test", -]
diff --git a/components/google/core/browser/OWNERS b/components/google/core/browser/OWNERS deleted file mode 100644 index 991eb9d1..0000000 --- a/components/google/core/browser/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -per-file google_tld_list.h=msramek@chromium.org -
diff --git a/components/google/core/browser/google_pref_names.cc b/components/google/core/browser/google_pref_names.cc deleted file mode 100644 index 92787d0..0000000 --- a/components/google/core/browser/google_pref_names.cc +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/google/core/browser/google_pref_names.h" - -namespace prefs { - -// String containing the last known Google URL. We re-detect this on startup in -// most cases, and use it to send traffic to the correct Google host or with the -// correct Google domain/country code for whatever location the user is in. -const char kLastKnownGoogleURL[] = "browser.last_known_google_url"; - -// String containing the last prompted Google URL. -const char kLastPromptedGoogleURL[] = "browser.last_prompted_google_url"; - -} // namespace prefs
diff --git a/components/google/core/browser/google_pref_names.h b/components/google/core/browser/google_pref_names.h deleted file mode 100644 index 2c58dd2..0000000 --- a/components/google/core/browser/google_pref_names.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_PREF_NAMES_H_ -#define COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_PREF_NAMES_H_ - -namespace prefs { - -// Alphabetical list of preference names specific to the Google -// component. Keep alphabetized, and document each in the .cc file. -extern const char kLastKnownGoogleURL[]; -extern const char kLastPromptedGoogleURL[]; - -} // namespace prefs - -#endif // COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_PREF_NAMES_H_
diff --git a/components/google/core/browser/google_url_tracker.cc b/components/google/core/browser/google_url_tracker.cc deleted file mode 100644 index cbc66da..0000000 --- a/components/google/core/browser/google_url_tracker.cc +++ /dev/null
@@ -1,226 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/google/core/browser/google_url_tracker.h" - -#include <utility> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/single_thread_task_runner.h" -#include "base/strings/string_util.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/common/google_switches.h" -#include "components/google/core/common/google_util.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/pref_service.h" -#include "net/base/load_flags.h" -#include "net/traffic_annotation/network_traffic_annotation.h" -#include "services/network/public/cpp/resource_request.h" -#include "services/network/public/cpp/simple_url_loader.h" - -const char GoogleURLTracker::kDefaultGoogleHomepage[] = - "https://www.google.com/"; -const char GoogleURLTracker::kSearchDomainCheckURL[] = - "https://www.google.com/searchdomaincheck?format=domain&type=chrome"; - -GoogleURLTracker::GoogleURLTracker( - std::unique_ptr<GoogleURLTrackerClient> client, - Mode mode, - network::NetworkConnectionTracker* network_connection_tracker) - : client_(std::move(client)), - network_connection_tracker_(network_connection_tracker), - google_url_( - mode == ALWAYS_DOT_COM_MODE - ? kDefaultGoogleHomepage - : client_->GetPrefs()->GetString(prefs::kLastKnownGoogleURL)), - in_startup_sleep_(true), - already_loaded_(false), - need_to_load_(false) { - network_connection_tracker_->AddNetworkConnectionObserver(this); - client_->set_google_url_tracker(this); - - // Because this function can be called during startup, when kicking off a URL - // load can eat up 20 ms of time, we delay five seconds, which is hopefully - // long enough to be after startup, but still get results back quickly. - // Ideally, instead of this timer, we'd do something like "check if the - // browser is starting up, and if so, come back later", but there is currently - // no function to do this. - // - // In ALWAYS_DOT_COM_MODE we do not nothing at all (but in unit tests - // /searchdomaincheck lookups might still be issued by calling FinishSleep - // manually). - if (mode == NORMAL_MODE) { - static const int kStartLoadDelayMS = 5000; - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&GoogleURLTracker::FinishSleep, - weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(kStartLoadDelayMS)); - } -} - -GoogleURLTracker::~GoogleURLTracker() { -} - -// static -void GoogleURLTracker::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) { - registry->RegisterStringPref(prefs::kLastKnownGoogleURL, - GoogleURLTracker::kDefaultGoogleHomepage); - registry->RegisterStringPref(prefs::kLastPromptedGoogleURL, std::string()); -} - -void GoogleURLTracker::RequestServerCheck() { - if (!simple_loader_) - SetNeedToLoad(); -} - -std::unique_ptr<GoogleURLTracker::Subscription> -GoogleURLTracker::RegisterCallback(const OnGoogleURLUpdatedCallback& cb) { - return callback_list_.Add(cb); -} - -void GoogleURLTracker::OnURLLoaderComplete( - std::unique_ptr<std::string> response_body) { - // Delete the loader. - simple_loader_.reset(); - - // Don't update the URL if the request didn't succeed. - if (!response_body) { - already_loaded_ = false; - return; - } - - // See if the response data was valid. It should be ".google.<TLD>". - base::TrimWhitespaceASCII(*response_body, base::TRIM_ALL, - response_body.get()); - if (!base::StartsWith(*response_body, ".google.", - base::CompareCase::INSENSITIVE_ASCII)) - return; - GURL url("https://www" + *response_body); - if (!url.is_valid() || (url.path().length() > 1) || url.has_query() || - url.has_ref() || - !google_util::IsGoogleDomainUrl(url, google_util::DISALLOW_SUBDOMAIN, - google_util::DISALLOW_NON_STANDARD_PORTS)) - return; - - if (url != google_url_) { - google_url_ = url; - client_->GetPrefs()->SetString(prefs::kLastKnownGoogleURL, - google_url_.spec()); - callback_list_.Notify(); - } -} - -void GoogleURLTracker::OnConnectionChanged( - network::mojom::ConnectionType type) { - // Ignore destructive signals. - if (type == network::mojom::ConnectionType::CONNECTION_NONE) - return; - already_loaded_ = false; - StartLoadIfDesirable(); -} - -void GoogleURLTracker::Shutdown() { - client_.reset(); - simple_loader_.reset(); - weak_ptr_factory_.InvalidateWeakPtrs(); - network_connection_tracker_->RemoveNetworkConnectionObserver(this); -} - -void GoogleURLTracker::SetNeedToLoad() { - need_to_load_ = true; - StartLoadIfDesirable(); -} - -void GoogleURLTracker::FinishSleep() { - in_startup_sleep_ = false; - StartLoadIfDesirable(); -} - -void GoogleURLTracker::StartLoadIfDesirable() { - // Bail if a load isn't appropriate right now. This function will be called - // again each time one of the preconditions changes, so we'll load - // immediately once all of them are met. - // - // See comments in header on the class, on RequestServerCheck(), and on the - // various members here for more detail on exactly what the conditions are. - if (in_startup_sleep_ || already_loaded_ || !need_to_load_) - return; - - // Some switches should disable the Google URL tracker entirely. If we can't - // do background networking, we can't do the necessary load, and if the user - // specified a Google base URL manually, we shouldn't bother to look up any - // alternatives or offer to switch to them. - if (!client_->IsBackgroundNetworkingEnabled() || - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kGoogleBaseURL)) - return; - - already_loaded_ = true; - net::NetworkTrafficAnnotationTag traffic_annotation = - net::DefineNetworkTrafficAnnotation("google_url_tracker", R"( - semantics { - sender: "Google URL Tracker" - description: - "When the user's default search engine is Google, or Google " - "services are used to resolve navigation errors, the browser needs " - "to know the ideal origin for requests to Google services. In " - "these cases the browser makes a request to a global Google " - "service that returns this origin, potentially taking into account " - "the user's cookies or IP address." - trigger: "Browser startup or network change." - data: "None." - destination: GOOGLE_OWNED_SERVICE - } - policy { - cookies_allowed: YES - cookies_store: "user" - setting: - "To disable this check, users can change the default search engine " - "to something other than Google, and disable 'Use a web service to " - "help resolve navigation errors' in Chromium's settings under " - "Privacy.\nAlternately, running Chromium with " - "--google-base-url=\"https://www.google.com/\" will disable this, " - "and force Chromium to use the specified URL for Google service " - "requests.\nFinally, running Chromium with " - "--disable-background-networking will disable this, as well as " - "various other features that make network requests automatically." - policy_exception_justification: - "Setting DefaultSearchProviderEnabled Chrome settings policy to " - "false suffices as a way of setting the default search engine to " - "not be Google. But there is no policy that controls navigation " - "error resolution." - })"); - auto resource_request = std::make_unique<network::ResourceRequest>(); - resource_request->url = GURL(kSearchDomainCheckURL); - // We don't want this load to set new entries in the cache or cookies, lest - // we alarm the user. - resource_request->load_flags = - (net::LOAD_DISABLE_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES); - simple_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), - traffic_annotation); - // Configure to retry at most kMaxRetries times for 5xx errors and network - // changes. - // A network change can propagate through Chrome in various stages, so it's - // possible for this code to be reached via OnNetworkChanged(), and then have - // the load we kick off be canceled due to e.g. the DNS server changing at a - // later time. In general it's not possible to ensure that by the time we - // reach here any requests we start won't be canceled in this fashion, so - // retrying is the best we can do. - static const int kMaxRetries = 5; - simple_loader_->SetRetryOptions( - kMaxRetries, - network::SimpleURLLoader::RetryMode::RETRY_ON_5XX | - network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); - simple_loader_->DownloadToString( - client_->GetURLLoaderFactory(), - base::BindOnce(&GoogleURLTracker::OnURLLoaderComplete, - base::Unretained(this)), - 2 * 1024 /* max_body_size */); -}
diff --git a/components/google/core/browser/google_url_tracker.h b/components/google/core/browser/google_url_tracker.h deleted file mode 100644 index f8d731f4..0000000 --- a/components/google/core/browser/google_url_tracker.h +++ /dev/null
@@ -1,137 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_URL_TRACKER_H_ -#define COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_URL_TRACKER_H_ - -#include <memory> - -#include "base/callback_forward.h" -#include "base/callback_list.h" -#include "base/feature_list.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "components/google/core/browser/google_url_tracker_client.h" -#include "components/keyed_service/core/keyed_service.h" -#include "services/network/public/cpp/network_connection_tracker.h" -#include "url/gurl.h" - -namespace user_prefs { -class PrefRegistrySyncable; -} - -namespace network { -class SimpleURLLoader; -} // namespace network - -// This object is responsible for checking the Google URL once per network -// change. The current value is saved to prefs. -// -// Most consumers should only call google_url(). Consumers who need to be -// notified when things change should use RegisterCallback(). -// -// To protect users' privacy and reduce server load, no updates will be -// performed (ever) unless at least one consumer registers interest by calling -// RequestServerCheck(). -class GoogleURLTracker - : public network::NetworkConnectionTracker::NetworkConnectionObserver, - public KeyedService { - public: - // Callback that is called when the Google URL is updated. - typedef base::Callback<void()> OnGoogleURLUpdatedCallback; - typedef base::CallbackList<void()> CallbackList; - typedef CallbackList::Subscription Subscription; - - // The mode of the tracker that controls how the tracker behaves and that must - // be passed to its constructor. - enum Mode { - // Use current local Google TLD. - // Defer network requests to update TLD until 5 seconds after - // creation, to avoid an expensive load during Chrome startup. - // - // TODO(https://crbug.com/973591): This is unused now. Remove it. - NORMAL_MODE, - - // Always use www.google.com. - ALWAYS_DOT_COM_MODE, - }; - - static const char kDefaultGoogleHomepage[]; - - // Only the GoogleURLTrackerFactory and tests should call this. - // |network_connection_tracker| should be the global singleton instance and - // should outlive the GoogleURLTracker object. - // Note: you *must* manually call Shutdown() before this instance gets - // destroyed if you want to create another instance in the same binary - // (e.g. in unit tests). - GoogleURLTracker( - std::unique_ptr<GoogleURLTrackerClient> client, - Mode mode, - network::NetworkConnectionTracker* network_connection_tracker); - - ~GoogleURLTracker() override; - - // Register user preferences for GoogleURLTracker. - static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); - - // Returns the current Google homepage URL. - const GURL& google_url() const { return google_url_; } - - // Requests that the tracker perform a server check to update the Google URL - // as necessary. This will happen at most once per network change, not sooner - // than five seconds after startup (checks requested before that time will - // occur then; checks requested afterwards will occur immediately, if no other - // checks have been made during this run). - void RequestServerCheck(); - - std::unique_ptr<Subscription> RegisterCallback( - const OnGoogleURLUpdatedCallback& cb); - - private: - friend class GoogleURLTrackerTest; - friend class SyncTest; - - static const char kSearchDomainCheckURL[]; - - void OnURLLoaderComplete(std::unique_ptr<std::string> response_body); - - // NetworkConnectionTracker::NetworkConnectionObserver: - void OnConnectionChanged(network::mojom::ConnectionType type) override; - - // KeyedService: - void Shutdown() override; - - // Sets |need_to_load_| and attempts to start a load. - void SetNeedToLoad(); - - // Called when the five second startup sleep has finished. Runs any pending - // load. - void FinishSleep(); - - // Starts the load of the up-to-date Google URL if we actually want to load - // it and can currently do so. - void StartLoadIfDesirable(); - - CallbackList callback_list_; - - std::unique_ptr<GoogleURLTrackerClient> client_; - network::NetworkConnectionTracker* network_connection_tracker_; - - GURL google_url_; - std::unique_ptr<network::SimpleURLLoader> simple_loader_; - bool in_startup_sleep_; // True if we're in the five-second "no loading" - // period that begins at browser start. - bool already_loaded_; // True if we've already loaded a URL once this run; - // we won't load again until after a restart. - bool need_to_load_; // True if a consumer actually wants us to load an - // updated URL. If this is never set, we won't - // bother to load anything. - // Consumers should register a callback via - // RegisterCallback(). - base::WeakPtrFactory<GoogleURLTracker> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(GoogleURLTracker); -}; - -#endif // COMPONENTS_GOOGLE_CORE_BROWSER_GOOGLE_URL_TRACKER_H_
diff --git a/components/google/core/browser/google_url_tracker_client.cc b/components/google/core/browser/google_url_tracker_client.cc deleted file mode 100644 index 5091fd6..0000000 --- a/components/google/core/browser/google_url_tracker_client.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/google/core/browser/google_url_tracker_client.h" - -GoogleURLTrackerClient::GoogleURLTrackerClient() - : google_url_tracker_(nullptr) {} - -GoogleURLTrackerClient::~GoogleURLTrackerClient() { -}
diff --git a/components/google/core/browser/google_url_tracker_client.h b/components/google/core/browser/google_url_tracker_client.h deleted file mode 100644 index 0ab7028..0000000 --- a/components/google/core/browser/google_url_tracker_client.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_H_ -#define COMPONENTS_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_H_ - -#include "base/macros.h" -#include "url/gurl.h" - -class GoogleURLTracker; -class PrefService; - -namespace network { -namespace mojom { -class URLLoaderFactory; -} -} - -// Interface by which GoogleURLTracker communicates with its embedder. -class GoogleURLTrackerClient { - public: - GoogleURLTrackerClient(); - virtual ~GoogleURLTrackerClient(); - - // Sets the GoogleURLTracker that is associated with this client. - void set_google_url_tracker(GoogleURLTracker* google_url_tracker) { - google_url_tracker_ = google_url_tracker; - } - - // Returns whether background networking is enabled. - virtual bool IsBackgroundNetworkingEnabled() = 0; - - // Returns the PrefService that the GoogleURLTracker should use. - virtual PrefService* GetPrefs() = 0; - - // Returns the URL loader factory that the GoogleURLTracker should use. - virtual network::mojom::URLLoaderFactory* GetURLLoaderFactory() = 0; - - protected: - GoogleURLTracker* google_url_tracker() { return google_url_tracker_; } - - private: - GoogleURLTracker* google_url_tracker_; - - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClient); -}; - -#endif // COMPONENTS_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_H_
diff --git a/components/google/core/browser/google_url_tracker_unittest.cc b/components/google/core/browser/google_url_tracker_unittest.cc deleted file mode 100644 index 12586c2c..0000000 --- a/components/google/core/browser/google_url_tracker_unittest.cc +++ /dev/null
@@ -1,360 +0,0 @@ -// 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. - -#include "components/google/core/browser/google_url_tracker.h" - -#include <memory> -#include <string> -#include <utility> - -#include "base/bind.h" -#include "base/macros.h" -#include "base/run_loop.h" -#include "base/test/bind_test_util.h" -#include "base/test/scoped_task_environment.h" -#include "base/threading/thread_task_runner_handle.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/browser/google_url_tracker_client.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/testing_pref_service.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" -#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "services/network/test/test_network_connection_tracker.h" -#include "services/network/test/test_url_loader_factory.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -// TestCallbackListener --------------------------------------------------- - -class TestCallbackListener { - public: - TestCallbackListener(); - virtual ~TestCallbackListener(); - - bool HasRegisteredCallback(); - void RegisterCallback(GoogleURLTracker* google_url_tracker); - - bool notified() const { return notified_; } - void clear_notified() { notified_ = false; } - - private: - void OnGoogleURLUpdated(); - - bool notified_; - std::unique_ptr<GoogleURLTracker::Subscription> - google_url_updated_subscription_; -}; - -TestCallbackListener::TestCallbackListener() : notified_(false) { -} - -TestCallbackListener::~TestCallbackListener() { -} - -void TestCallbackListener::OnGoogleURLUpdated() { - notified_ = true; -} - -bool TestCallbackListener::HasRegisteredCallback() { - return google_url_updated_subscription_.get(); -} - -void TestCallbackListener::RegisterCallback( - GoogleURLTracker* google_url_tracker) { - google_url_updated_subscription_ = - google_url_tracker->RegisterCallback(base::Bind( - &TestCallbackListener::OnGoogleURLUpdated, base::Unretained(this))); -} - - -// TestGoogleURLTrackerClient ------------------------------------------------- - -class TestGoogleURLTrackerClient : public GoogleURLTrackerClient { - public: - TestGoogleURLTrackerClient( - PrefService* prefs_, - network::TestURLLoaderFactory* test_url_loader_factory); - ~TestGoogleURLTrackerClient() override; - - bool IsBackgroundNetworkingEnabled() override; - PrefService* GetPrefs() override; - network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; - - private: - PrefService* prefs_; - scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; - - DISALLOW_COPY_AND_ASSIGN(TestGoogleURLTrackerClient); -}; - -TestGoogleURLTrackerClient::TestGoogleURLTrackerClient( - PrefService* prefs, - network::TestURLLoaderFactory* test_url_loader_factory) - : prefs_(prefs), - test_shared_loader_factory_( - base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( - test_url_loader_factory)) {} - -TestGoogleURLTrackerClient::~TestGoogleURLTrackerClient() { -} - -bool TestGoogleURLTrackerClient::IsBackgroundNetworkingEnabled() { - return true; -} - -PrefService* TestGoogleURLTrackerClient::GetPrefs() { - return prefs_; -} - -network::mojom::URLLoaderFactory* -TestGoogleURLTrackerClient::GetURLLoaderFactory() { - return test_shared_loader_factory_.get(); -} - -} // namespace - -// GoogleURLTrackerTest ------------------------------------------------------- - -class GoogleURLTrackerTest : public testing::Test { - protected: - GoogleURLTrackerTest(); - ~GoogleURLTrackerTest() override; - - // testing::Test - void SetUp() override; - void TearDown() override; - - void MockSearchDomainCheckResponse(const std::string& domain); - void RequestServerCheck(); - void FinishSleep(); - void NotifyNetworkChanged(); - void set_google_url(const GURL& url) { - google_url_tracker_->google_url_ = url; - } - GURL google_url() const { return google_url_tracker_->google_url(); } - bool listener_notified() const { return listener_.notified(); } - void clear_listener_notified() { listener_.clear_notified(); } - bool handled_request() const { return handled_request_; } - - GoogleURLTrackerClient* client() const { return client_; } - - private: - base::test::ScopedTaskEnvironment scoped_task_environment_; - TestingPrefServiceSimple prefs_; - network::TestURLLoaderFactory test_url_loader_factory_; - - GoogleURLTrackerClient* client_; - - std::unique_ptr<GoogleURLTracker> google_url_tracker_; - TestCallbackListener listener_; - - bool handled_request_ = false; -}; - -GoogleURLTrackerTest::GoogleURLTrackerTest() { - prefs_.registry()->RegisterStringPref( - prefs::kLastKnownGoogleURL, - GoogleURLTracker::kDefaultGoogleHomepage); -} - -GoogleURLTrackerTest::~GoogleURLTrackerTest() { -} - -void GoogleURLTrackerTest::SetUp() { - // Ownership is passed to google_url_tracker_, but a weak pointer is kept; - // this is safe since GoogleURLTracker keeps the client for its lifetime. - client_ = new TestGoogleURLTrackerClient(&prefs_, &test_url_loader_factory_); - std::unique_ptr<GoogleURLTrackerClient> client(client_); - google_url_tracker_.reset(new GoogleURLTracker( - std::move(client), GoogleURLTracker::ALWAYS_DOT_COM_MODE, - network::TestNetworkConnectionTracker::GetInstance())); -} - -void GoogleURLTrackerTest::TearDown() { - google_url_tracker_->Shutdown(); -} - -void GoogleURLTrackerTest::MockSearchDomainCheckResponse( - const std::string& domain) { - handled_request_ = false; - test_url_loader_factory_.SetInterceptor( - base::BindLambdaForTesting([&](const network::ResourceRequest& request) { - handled_request_ = true; - })); - test_url_loader_factory_.AddResponse(GoogleURLTracker::kSearchDomainCheckURL, - domain); -} - -void GoogleURLTrackerTest::RequestServerCheck() { - if (!listener_.HasRegisteredCallback()) - listener_.RegisterCallback(google_url_tracker_.get()); - google_url_tracker_->SetNeedToLoad(); - base::RunLoop().RunUntilIdle(); -} - -void GoogleURLTrackerTest::FinishSleep() { - google_url_tracker_->FinishSleep(); - base::RunLoop().RunUntilIdle(); -} - -void GoogleURLTrackerTest::NotifyNetworkChanged() { - network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType( - network::mojom::ConnectionType::CONNECTION_UNKNOWN); - base::RunLoop().RunUntilIdle(); -} - -// Tests ---------------------------------------------------------------------- - -TEST_F(GoogleURLTrackerTest, DontFetchWhenNoOneRequestsCheck) { - EXPECT_EQ(GURL(GoogleURLTracker::kDefaultGoogleHomepage), google_url()); - FinishSleep(); - // No one called RequestServerCheck() so nothing should have happened. - EXPECT_FALSE(handled_request()); - MockSearchDomainCheckResponse(".google.co.uk"); - EXPECT_EQ(GURL(GoogleURLTracker::kDefaultGoogleHomepage), google_url()); - EXPECT_FALSE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, Update) { - MockSearchDomainCheckResponse(".google.co.uk"); - - RequestServerCheck(); - EXPECT_FALSE(handled_request()); - EXPECT_EQ(GURL(GoogleURLTracker::kDefaultGoogleHomepage), google_url()); - EXPECT_FALSE(listener_notified()); - - FinishSleep(); - EXPECT_EQ(GURL("https://www.google.co.uk/"), google_url()); - EXPECT_TRUE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, DontUpdateWhenUnchanged) { - MockSearchDomainCheckResponse(".google.co.uk"); - - GURL original_google_url("https://www.google.co.uk/"); - set_google_url(original_google_url); - - RequestServerCheck(); - EXPECT_FALSE(handled_request()); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - FinishSleep(); - EXPECT_EQ(original_google_url, google_url()); - // No one should be notified, because the new URL matches the old. - EXPECT_FALSE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, DontUpdateOnBadReplies) { - GURL original_google_url("https://www.google.co.uk/"); - set_google_url(original_google_url); - - RequestServerCheck(); - EXPECT_FALSE(handled_request()); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Old-style URL string. - MockSearchDomainCheckResponse("https://www.google.com/"); - FinishSleep(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Not a Google domain. - MockSearchDomainCheckResponse(".google.evil.com"); - FinishSleep(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Doesn't start with .google. - MockSearchDomainCheckResponse(".mail.google.com"); - NotifyNetworkChanged(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Non-empty path. - MockSearchDomainCheckResponse(".google.com/search"); - NotifyNetworkChanged(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Non-empty query. - MockSearchDomainCheckResponse(".google.com/?q=foo"); - NotifyNetworkChanged(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Non-empty ref. - MockSearchDomainCheckResponse(".google.com/#anchor"); - NotifyNetworkChanged(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); - - // Complete garbage. - MockSearchDomainCheckResponse("HJ)*qF)_*&@f1"); - NotifyNetworkChanged(); - EXPECT_EQ(original_google_url, google_url()); - EXPECT_FALSE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, RefetchOnNetworkChange) { - MockSearchDomainCheckResponse(".google.co.uk"); - RequestServerCheck(); - FinishSleep(); - EXPECT_EQ(GURL("https://www.google.co.uk/"), google_url()); - EXPECT_TRUE(listener_notified()); - clear_listener_notified(); - - MockSearchDomainCheckResponse(".google.co.in"); - NotifyNetworkChanged(); - EXPECT_EQ(GURL("https://www.google.co.in/"), google_url()); - EXPECT_TRUE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, DontRefetchWhenNoOneRequestsCheck) { - MockSearchDomainCheckResponse(".google.co.uk"); - FinishSleep(); - NotifyNetworkChanged(); - // No one called RequestServerCheck() so nothing should have happened. - EXPECT_FALSE(handled_request()); - EXPECT_EQ(GURL(GoogleURLTracker::kDefaultGoogleHomepage), google_url()); - EXPECT_FALSE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, FetchOnLateRequest) { - MockSearchDomainCheckResponse(".google.co.jp"); - FinishSleep(); - NotifyNetworkChanged(); - - MockSearchDomainCheckResponse(".google.co.uk"); - RequestServerCheck(); - // The first request for a check should trigger a fetch if it hasn't happened - // already. - EXPECT_EQ(GURL("https://www.google.co.uk/"), google_url()); - EXPECT_TRUE(listener_notified()); -} - -TEST_F(GoogleURLTrackerTest, DontFetchTwiceOnLateRequests) { - MockSearchDomainCheckResponse(".google.co.jp"); - FinishSleep(); - NotifyNetworkChanged(); - - MockSearchDomainCheckResponse(".google.co.uk"); - RequestServerCheck(); - // The first request for a check should trigger a fetch if it hasn't happened - // already. - EXPECT_EQ(GURL("https://www.google.co.uk/"), google_url()); - EXPECT_TRUE(listener_notified()); - clear_listener_notified(); - - MockSearchDomainCheckResponse(".google.co.in"); - RequestServerCheck(); - // The second request should be ignored. - EXPECT_FALSE(handled_request()); - EXPECT_EQ(GURL("https://www.google.co.uk/"), google_url()); - EXPECT_FALSE(listener_notified()); -}
diff --git a/components/google/core/common/BUILD.gn b/components/google/core/common/BUILD.gn index d558cb1..07c78feb 100644 --- a/components/google/core/common/BUILD.gn +++ b/components/google/core/common/BUILD.gn
@@ -20,3 +20,17 @@ "//components/url_formatter", ] } + +source_set("unit_tests") { + testonly = true + + sources = [ + "google_util_unittest.cc", + ] + + deps = [ + ":common", + "//base", + "//testing/gtest", + ] +}
diff --git a/components/google/core/common/google_util.cc b/components/google/core/common/google_util.cc index 491ec0d..da46c95c 100644 --- a/components/google/core/common/google_util.cc +++ b/components/google/core/common/google_util.cc
@@ -145,6 +145,8 @@ // Global functions ----------------------------------------------------------- +const char kGoogleHomepageURL[] = "https://www.google.com/"; + bool HasGoogleSearchQueryParam(base::StringPiece str) { url::Component query(0, static_cast<int>(str.length())), key, value; while (url::ExtractQueryKeyValue(str.data(), &query, &key, &value)) {
diff --git a/components/google/core/common/google_util.h b/components/google/core/common/google_util.h index 70957e16..cda6b86 100644 --- a/components/google/core/common/google_util.h +++ b/components/google/core/common/google_util.h
@@ -17,6 +17,8 @@ // This namespace provides various helpers around handling Google-related URLs. namespace google_util { +extern const char kGoogleHomepageURL[]; + // True iff |str| contains a "q=" or "as_q=" query parameter with a non-empty // value. |str| should be a query or a hash fragment, without the ? or # (as // returned by GURL::query() or GURL::ref().
diff --git a/components/google/core/browser/google_util_unittest.cc b/components/google/core/common/google_util_unittest.cc similarity index 98% rename from components/google/core/browser/google_util_unittest.cc rename to components/google/core/common/google_util_unittest.cc index a51544a..b975048 100644 --- a/components/google/core/browser/google_util_unittest.cc +++ b/components/google/core/common/google_util_unittest.cc
@@ -7,9 +7,9 @@ #include "base/command_line.h" #include "base/macros.h" #include "base/strings/stringprintf.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_switches.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" using google_util::IsGoogleDomainUrl; @@ -44,7 +44,7 @@ TEST(GoogleUtilTest, GoodHomePagesNonSecure) { // Valid home page hosts. - EXPECT_TRUE(IsHomePage(GoogleURLTracker::kDefaultGoogleHomepage)); + EXPECT_TRUE(IsHomePage(google_util::kGoogleHomepageURL)); EXPECT_TRUE(IsHomePage("http://google.com")); EXPECT_TRUE(IsHomePage("http://www.google.com")); EXPECT_TRUE(IsHomePage("http://www.google.ca")); @@ -188,7 +188,7 @@ TEST(GoogleUtilTest, BadSearches) { // A home page URL should not be identified as a search URL. - EXPECT_FALSE(IsSearch(GoogleURLTracker::kDefaultGoogleHomepage)); + EXPECT_FALSE(IsSearch(google_util::kGoogleHomepageURL)); // Must be http or https. EXPECT_FALSE(IsSearch("ftp://www.google.com/search?q=something"));
diff --git a/components/heap_profiling/client_connection_manager.cc b/components/heap_profiling/client_connection_manager.cc index 1c5d77a..57c96d9 100644 --- a/components/heap_profiling/client_connection_manager.cc +++ b/components/heap_profiling/client_connection_manager.cc
@@ -244,7 +244,7 @@ } // The BrowserChildProcessHostIterator iterator must be used on the IO thread. - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&StartProfilingPidOnIOThread, controller_, pid)); } @@ -265,7 +265,7 @@ // Start profiling the current process. if (ShouldProfileNonRendererProcessType( mode_, content::ProcessType::PROCESS_TYPE_BROWSER)) { - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&StartProfilingBrowserProcessOnIOThread, controller_)); @@ -281,7 +281,7 @@ } } - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask( FROM_HERE, base::BindOnce(&StartProfilingNonRenderersIfNecessaryOnIOThread, @@ -305,7 +305,7 @@ void ClientConnectionManager::StartProfilingNonRendererChild( const content::ChildProcessData& data) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&StartProfilingNonRendererChildOnIOThread, controller_, data.Duplicate())); @@ -363,7 +363,7 @@ // Tell the child process to start profiling. ProfilingClientBinder client(host); - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&StartProfilingClientOnIOThread, controller_, std::move(client), host->GetProcess().Pid(),
diff --git a/components/heap_profiling/supervisor.cc b/components/heap_profiling/supervisor.cc index 712ba9bb..ba3950d 100644 --- a/components/heap_profiling/supervisor.cc +++ b/components/heap_profiling/supervisor.cc
@@ -71,7 +71,7 @@ DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); DCHECK(!started_); - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&Supervisor::StartServiceOnIOThread, base::Unretained(this), connector->Clone(), mode, stack_mode, @@ -93,7 +93,7 @@ DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); DCHECK(HasStarted()); - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}) ->PostTask(FROM_HERE, base::BindOnce(&Supervisor::GetProfiledPidsOnIOThread, base::Unretained(this), std::move(callback))); @@ -127,8 +127,7 @@ base::RefCountedString* in) { std::string result; result.swap(in->data()); - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(std::move(callback), true, std::move(result))); @@ -175,7 +174,7 @@ new Controller(std::move(connector), stack_mode, sampling_rate)); base::WeakPtr<Controller> controller_weak_ptr = controller_->GetWeakPtr(); - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(&Supervisor::FinishInitializationOnUIhread, base::Unretained(this), mode, @@ -208,8 +207,7 @@ auto post_result_to_ui_thread = base::BindOnce( [](GetProfiledPidsCallback callback, const std::vector<base::ProcessId>& result) { - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(std::move(callback), result)); }, std::move(callback));
diff --git a/components/heap_profiling/test_driver.cc b/components/heap_profiling/test_driver.cc index a8e5ee0f..3c73d6ef 100644 --- a/components/heap_profiling/test_driver.cc +++ b/components/heap_profiling/test_driver.cc
@@ -575,10 +575,9 @@ if (running_on_ui_thread_) { has_started_ = Supervisor::GetInstance()->HasStarted(); } else { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&TestDriver::GetHasStartedOnUIThread, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&TestDriver::GetHasStartedOnUIThread, + base::Unretained(this))); wait_for_ui_thread_.Wait(); } if (has_started_) { @@ -597,7 +596,7 @@ MakeTestAllocations(); CollectResults(true); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TestDriver::CheckOrStartProfilingOnUIThreadAndSignal, base::Unretained(this))); @@ -605,7 +604,7 @@ if (!initialization_success_) return false; if (ShouldProfileRenderer()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TestDriver:: @@ -614,13 +613,13 @@ wait_for_ui_thread_.Wait(); } if (ShouldProfileBrowser()) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&TestDriver::MakeTestAllocations, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&TestDriver::MakeTestAllocations, + base::Unretained(this))); } - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&TestDriver::CollectResults, - base::Unretained(this), false)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&TestDriver::CollectResults, + base::Unretained(this), false)); wait_for_ui_thread_.Wait(); }
diff --git a/components/history/core/browser/history_service.cc b/components/history/core/browser/history_service.cc index 58a42bc..c0a0a67 100644 --- a/components/history/core/browser/history_service.cc +++ b/components/history/core/browser/history_service.cc
@@ -905,8 +905,8 @@ } backend_task_runner_ = thread_->task_runner(); } else { - backend_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::WithBaseSyncPrimitives(), + backend_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); }
diff --git a/components/history/core/browser/top_sites_backend.cc b/components/history/core/browser/top_sites_backend.cc index 25e2be47..f1494701 100644 --- a/components/history/core/browser/top_sites_backend.cc +++ b/components/history/core/browser/top_sites_backend.cc
@@ -25,8 +25,8 @@ TopSitesBackend::TopSitesBackend() : db_(new TopSitesDatabase()), - db_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, + db_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::BLOCK_SHUTDOWN, base::MayBlock()})) { DCHECK(db_task_runner_); }
diff --git a/components/image_fetcher/core/cache/image_cache.cc b/components/image_fetcher/core/cache/image_cache.cc index 69bd29e..a69cecc9 100644 --- a/components/image_fetcher/core/cache/image_cache.cc +++ b/components/image_fetcher/core/cache/image_cache.cc
@@ -143,11 +143,11 @@ ImageFetcherEvent::kCacheStartupEvictionStarted); // Once all the queued requests are taken care of, run eviction. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::BEST_EFFORT}, - base::BindOnce(OnStartupEvictionQueued), - base::BindOnce(&ImageCache::RunEvictionOnStartup, - weak_ptr_factory_.GetWeakPtr())); + base::PostTaskAndReply(FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT}, + base::BindOnce(OnStartupEvictionQueued), + base::BindOnce(&ImageCache::RunEvictionOnStartup, + weak_ptr_factory_.GetWeakPtr())); } void ImageCache::SaveImageImpl(const std::string& url,
diff --git a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm index b56c03ab..6c113fd 100644 --- a/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm +++ b/components/image_fetcher/ios/ios_image_data_fetcher_wrapper.mm
@@ -66,9 +66,10 @@ // The image is a webp image. RequestMetadata webp_metadata = metadata; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, { + base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, },
diff --git a/components/image_fetcher/ios/ios_image_decoder_impl.mm b/components/image_fetcher/ios/ios_image_decoder_impl.mm index aca5ea3..cab9ce3 100644 --- a/components/image_fetcher/ios/ios_image_decoder_impl.mm +++ b/components/image_fetcher/ios/ios_image_decoder_impl.mm
@@ -41,8 +41,9 @@ // The task runner used to decode images if necessary. const scoped_refptr<base::TaskRunner> task_runner_ = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); // The WeakPtrFactory is used to cancel callbacks if ImageFetcher is
diff --git a/components/keyed_service/core/refcounted_keyed_service.h b/components/keyed_service/core/refcounted_keyed_service.h index 24f7d9e..043b52a 100644 --- a/components/keyed_service/core/refcounted_keyed_service.h +++ b/components/keyed_service/core/refcounted_keyed_service.h
@@ -52,7 +52,7 @@ // If you need your service to be deleted on a specific sequence (for example, // you're converting a service that used content::DeleteOnThread<IO>), then // use this constructor with a reference to the SequencedTaskRunner (e.g., you - // can get it from base::CreateSequencedTaskRunnerWithTraits). + // can get it from base::CreateSequencedTaskRunner). explicit RefcountedKeyedService( scoped_refptr<base::SequencedTaskRunner> task_runner);
diff --git a/components/language/content/browser/geo_language_provider.cc b/components/language/content/browser/geo_language_provider.cc index a2cde93e..f0d3fb9 100644 --- a/components/language/content/browser/geo_language_provider.cc +++ b/components/language/content/browser/geo_language_provider.cc
@@ -32,8 +32,9 @@ GeoLanguageProvider::GeoLanguageProvider() : creation_task_runner_(base::SequencedTaskRunnerHandle::Get()), - background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + background_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), prefs_(nullptr) { // Constructor is not required to run on |background_task_runner_|:
diff --git a/components/language_usage_metrics/OWNERS b/components/language_usage_metrics/OWNERS index bb5c3afc..29abffbbe 100644 --- a/components/language_usage_metrics/OWNERS +++ b/components/language_usage_metrics/OWNERS
@@ -1 +1,2 @@ file://components/translate/OWNERS +# COMPONENT: UI>Browser>Language
diff --git a/components/leveldb_proto/internal/shared_proto_database.cc b/components/leveldb_proto/internal/shared_proto_database.cc index 6c897a90..dff092f 100644 --- a/components/leveldb_proto/internal/shared_proto_database.cc +++ b/components/leveldb_proto/internal/shared_proto_database.cc
@@ -54,8 +54,9 @@ SharedProtoDatabase::SharedProtoDatabase(const std::string& client_db_id, const base::FilePath& db_dir) - : task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), db_dir_(db_dir), db_(std::make_unique<LevelDB>(client_db_id.c_str())),
diff --git a/components/login/secure_module_util_chromeos.cc b/components/login/secure_module_util_chromeos.cc index 25fc3eb7..695a7e9 100644 --- a/components/login/secure_module_util_chromeos.cc +++ b/components/login/secure_module_util_chromeos.cc
@@ -38,8 +38,9 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&GetSecureModuleInfoFromFilesAndCacheIt), std::move(callback)); }
diff --git a/components/media_message_center/media_controls_progress_view_unittest.cc b/components/media_message_center/media_controls_progress_view_unittest.cc index 5e233c3b..e562b917 100644 --- a/components/media_message_center/media_controls_progress_view_unittest.cc +++ b/components/media_message_center/media_controls_progress_view_unittest.cc
@@ -33,7 +33,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(300, 300); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); views::View* container = new views::View(); widget_.SetContentsView(container);
diff --git a/components/media_message_center/media_notification_view_unittest.cc b/components/media_message_center/media_notification_view_unittest.cc index e73b7f58..e213c732 100644 --- a/components/media_message_center/media_notification_view_unittest.cc +++ b/components/media_message_center/media_notification_view_unittest.cc
@@ -116,7 +116,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(kWidgetSize); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); CreateViewFromMediaSessionInfo(
diff --git a/components/metrics/cloned_install_detector.cc b/components/metrics/cloned_install_detector.cc index 4287fdb8..b940288 100644 --- a/components/metrics/cloned_install_detector.cc +++ b/components/metrics/cloned_install_detector.cc
@@ -54,9 +54,9 @@ } void ClonedInstallDetector::CheckForClonedInstall(PrefService* local_state) { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::Bind(&MachineIdProvider::GetMachineId), base::Bind(&ClonedInstallDetector::SaveMachineId,
diff --git a/components/metrics/demographic_metrics_provider.cc b/components/metrics/demographic_metrics_provider.cc index 66b3af2..7971117 100644 --- a/components/metrics/demographic_metrics_provider.cc +++ b/components/metrics/demographic_metrics_provider.cc
@@ -33,21 +33,28 @@ // Skip if not exactly one Profile on disk. Having more than one Profile that // is using the browser can make demographics less relevant. This approach // cannot determine if there is more than 1 distinct user using the Profile. - if (profile_client_->GetNumberOfProfilesOnDisk() != 1) + if (profile_client_->GetNumberOfProfilesOnDisk() != 1) { + syncer::LogUserDemographicsStatus( + syncer::UserDemographicsStatus::kMoreThanOneProfile); return; + } syncer::SyncService* sync_service = profile_client_->GetSyncService(); // Skip if no sync service. - if (!sync_service) + if (!sync_service) { + syncer::LogUserDemographicsStatus( + syncer::UserDemographicsStatus::kNoSyncService); return; + } - // Report demographics if they are available. - base::Optional<syncer::UserDemographics> demographics = + syncer::UserDemographicsResult demographics_result = sync_service->GetUserDemographics(profile_client_->GetNetworkTime()); - if (demographics.has_value()) { + syncer::LogUserDemographicsStatus(demographics_result.status()); + // Report demographics when they can be provided. + if (demographics_result.IsSuccess()) { auto* demographics_proto = uma_proto->mutable_user_demographics(); - demographics_proto->set_birth_year(demographics->birth_year); - demographics_proto->set_gender(demographics->gender); + demographics_proto->set_birth_year(demographics_result.value().birth_year); + demographics_proto->set_gender(demographics_result.value().gender); } }
diff --git a/components/metrics/demographic_metrics_provider_unittest.cc b/components/metrics/demographic_metrics_provider_unittest.cc index ae97434..b42fc76 100644 --- a/components/metrics/demographic_metrics_provider_unittest.cc +++ b/components/metrics/demographic_metrics_provider_unittest.cc
@@ -6,7 +6,7 @@ #include <memory> -#include "base/optional.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "base/time/time.h" @@ -50,22 +50,21 @@ }; // Make arbitrary user demographics to provide. -base::Optional<syncer::UserDemographics> GetDemographics() { - base::Optional<syncer::UserDemographics> user_demographics = - syncer::UserDemographics(); - user_demographics->birth_year = 1983; - user_demographics->gender = UserDemographicsProto::GENDER_FEMALE; - return user_demographics; +syncer::UserDemographicsResult GetDemographics() { + syncer::UserDemographics user_demographics; + user_demographics.birth_year = 1983; + user_demographics.gender = UserDemographicsProto::GENDER_FEMALE; + return syncer::UserDemographicsResult::ForValue(std::move(user_demographics)); } std::unique_ptr<TestProfileClient> MakeTestProfileClient( - const base::Optional<syncer::UserDemographics>& user_demographics, + const syncer::UserDemographicsResult& user_demographics_result, int number_of_profiles, bool has_sync_service) { std::unique_ptr<syncer::TestSyncService> sync_service = nullptr; if (has_sync_service) { sync_service = std::make_unique<syncer::TestSyncService>(); - sync_service->SetUserDemographics(user_demographics); + sync_service->SetUserDemographics(user_demographics_result); } return std::make_unique<TestProfileClient>(std::move(sync_service), number_of_profiles); @@ -77,6 +76,8 @@ local_feature.InitAndEnableFeature( DemographicMetricsProvider::kDemographicMetricsReporting); + base::HistogramTester histogram; + // Run demographics provider. DemographicMetricsProvider provider( MakeTestProfileClient(GetDemographics(), /*number_of_profiles=*/1, @@ -85,17 +86,24 @@ provider.ProvideCurrentSessionData(&uma_proto); // Verify provided demographics. - EXPECT_EQ(GetDemographics()->birth_year, + EXPECT_EQ(GetDemographics().value().birth_year, uma_proto.user_demographics().birth_year()); - EXPECT_EQ(GetDemographics()->gender, uma_proto.user_demographics().gender()); + EXPECT_EQ(GetDemographics().value().gender, + uma_proto.user_demographics().gender()); + + // Verify histograms. + histogram.ExpectUniqueSample("UMA.UserDemographics.Status", + syncer::UserDemographicsStatus::kSuccess, 1); } TEST(DemographicMetricsProviderTest, ProvideCurrentSessionData_NoSyncService) { // Enable demographics reporting feature. base::test::ScopedFeatureList local_feature; - local_feature.InitAndDisableFeature( + local_feature.InitAndEnableFeature( DemographicMetricsProvider::kDemographicMetricsReporting); + base::HistogramTester histogram; + // Run demographics provider. DemographicMetricsProvider provider( MakeTestProfileClient(GetDemographics(), @@ -107,6 +115,11 @@ // Expect the proto fields to be not set and left to default. EXPECT_FALSE(uma_proto.user_demographics().has_birth_year()); EXPECT_FALSE(uma_proto.user_demographics().has_gender()); + + // Verify histograms. + histogram.ExpectUniqueSample("UMA.UserDemographics.Status", + syncer::UserDemographicsStatus::kNoSyncService, + 1); } TEST(DemographicMetricsProviderTest, @@ -116,6 +129,8 @@ local_feature.InitAndDisableFeature( DemographicMetricsProvider::kDemographicMetricsReporting); + base::HistogramTester histogram; + // Run demographics provider. DemographicMetricsProvider provider( MakeTestProfileClient(GetDemographics(), /*number_of_profiles=*/1, @@ -126,6 +141,9 @@ // Expect that the UMA proto is untouched. EXPECT_FALSE(uma_proto.user_demographics().has_birth_year()); EXPECT_FALSE(uma_proto.user_demographics().has_gender()); + + // Verify that there are no histograms for user demographics. + histogram.ExpectTotalCount("UMA.UserDemographics.Status", 0); } TEST(DemographicMetricsProviderTest, @@ -135,6 +153,8 @@ local_feature.InitAndEnableFeature( DemographicMetricsProvider::kDemographicMetricsReporting); + base::HistogramTester histogram; + // Run demographics provider with not exactly one Profile on disk. DemographicMetricsProvider provider( MakeTestProfileClient(GetDemographics(), /*number_of_profiles=*/2, @@ -145,6 +165,11 @@ // Expect that the UMA proto is untouched. EXPECT_FALSE(uma_proto.user_demographics().has_birth_year()); EXPECT_FALSE(uma_proto.user_demographics().has_gender()); + + // Verify histograms. + histogram.ExpectUniqueSample( + "UMA.UserDemographics.Status", + syncer::UserDemographicsStatus::kMoreThanOneProfile, 1); } TEST(DemographicMetricsProviderTest, @@ -154,17 +179,27 @@ local_feature.InitAndEnableFeature( DemographicMetricsProvider::kDemographicMetricsReporting); + base::HistogramTester histogram; + // Run demographics provider with a ProfileClient that does not provide - // demographics. - DemographicMetricsProvider provider( - MakeTestProfileClient(base::nullopt, /*number_of_profiles=*/1, - /*has_sync_service=*/true)); + // demographics because of some error. + DemographicMetricsProvider provider(MakeTestProfileClient( + syncer::UserDemographicsResult::ForStatus( + syncer::UserDemographicsStatus::kIneligibleDemographicsData), + /*number_of_profiles=*/1, + /*has_sync_service=*/true)); ChromeUserMetricsExtension uma_proto; provider.ProvideCurrentSessionData(&uma_proto); // Expect that the UMA proto is untouched. EXPECT_FALSE(uma_proto.user_demographics().has_birth_year()); EXPECT_FALSE(uma_proto.user_demographics().has_gender()); + + // Verify that there are no histograms for user demographics. We expect + // histograms to be logged by the sync libraries. + histogram.ExpectUniqueSample( + "UMA.UserDemographics.Status", + syncer::UserDemographicsStatus::kIneligibleDemographicsData, 1); } } // namespace
diff --git a/components/metrics/drive_metrics_provider.cc b/components/metrics/drive_metrics_provider.cc index 1953bb27..ad9c95a 100644 --- a/components/metrics/drive_metrics_provider.cc +++ b/components/metrics/drive_metrics_provider.cc
@@ -33,9 +33,9 @@ } void DriveMetricsProvider::AsyncInit(const base::Closure& done_callback) { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::Bind(&DriveMetricsProvider::GetDriveMetricsOnBackgroundThread, local_state_path_key_),
diff --git a/components/metrics/file_metrics_provider.cc b/components/metrics/file_metrics_provider.cc index e6d00d5..8217c95f 100644 --- a/components/metrics/file_metrics_provider.cc +++ b/components/metrics/file_metrics_provider.cc
@@ -97,9 +97,9 @@ if (g_task_runner_for_testing) return scoped_refptr<base::TaskRunner>(g_task_runner_for_testing); - return base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + return base::CreateTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); } } // namespace
diff --git a/components/metrics/net/network_metrics_provider.cc b/components/metrics/net/network_metrics_provider.cc index a83e1fc..279bb347 100644 --- a/components/metrics/net/network_metrics_provider.cc +++ b/components/metrics/net/network_metrics_provider.cc
@@ -300,9 +300,9 @@ void NetworkMetricsProvider::ProbeWifiPHYLayerProtocol() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&net::GetWifiPHYLayerProtocol), base::BindOnce(&NetworkMetricsProvider::OnWifiPHYLayerProtocolResult,
diff --git a/components/metrics/persistent_histograms.cc b/components/metrics/persistent_histograms.cc index 29a54f5..20d02f39 100644 --- a/components/metrics/persistent_histograms.cc +++ b/components/metrics/persistent_histograms.cc
@@ -168,9 +168,9 @@ } } // Schedule the creation of a "spare" file for use on the next run. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::LOWEST, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::LOWEST, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(base::IgnoreResult( &base::GlobalHistogramAllocator::CreateSpareFile), @@ -211,9 +211,9 @@ allocator->CreateTrackingHistograms(kBrowserMetricsName); #if defined(OS_WIN) - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::LOWEST, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::LOWEST, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&DeleteOldWindowsTempFiles, std::move(metrics_dir)), kDeleteOldWindowsTempFilesDelay);
diff --git a/components/mirroring/browser/cast_remoting_sender.cc b/components/mirroring/browser/cast_remoting_sender.cc index 75d56be..310f83e 100644 --- a/components/mirroring/browser/cast_remoting_sender.cc +++ b/components/mirroring/browser/cast_remoting_sender.cc
@@ -135,7 +135,7 @@ // CastRemotingSender lives entirely on the IO thread, so trampoline if // necessary. if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &CastRemotingSender::FindAndBind, rtp_stream_id, std::move(pipe),
diff --git a/components/mirroring/service/session.cc b/components/mirroring/service/session.cc index 0e7a514..c9dce67 100644 --- a/components/mirroring/service/session.cc +++ b/components/mirroring/service/session.cc
@@ -667,12 +667,12 @@ const bool initially_starting_session = !audio_encode_thread_ && !video_encode_thread_; if (initially_starting_session) { - audio_encode_thread_ = base::CreateSingleThreadTaskRunnerWithTraits( - {base::TaskPriority::USER_BLOCKING, + audio_encode_thread_ = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::SingleThreadTaskRunnerThreadMode::DEDICATED); - video_encode_thread_ = base::CreateSingleThreadTaskRunnerWithTraits( - {base::TaskPriority::USER_BLOCKING, + video_encode_thread_ = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::SingleThreadTaskRunnerThreadMode::DEDICATED); }
diff --git a/components/nacl/browser/nacl_browser.cc b/components/nacl/browser/nacl_browser.cc index 7eb8339..5aeacfba 100644 --- a/components/nacl/browser/nacl_browser.cc +++ b/components/nacl/browser/nacl_browser.cc
@@ -105,8 +105,7 @@ void RemoveCache(const base::FilePath& filename, base::OnceClosure callback) { base::DeleteFile(filename, false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - std::move(callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, std::move(callback)); } void LogCacheQuery(nacl::NaClBrowser::ValidationCacheStatus status) { @@ -284,8 +283,8 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (IsOk() && irt_state_ == NaClResourceUninitialized) { irt_state_ = NaClResourceRequested; - auto task_runner = base::CreateTaskRunnerWithTraits( - {base::MayBlock(), kUserBlocking, + auto task_runner = base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), kUserBlocking, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); std::unique_ptr<base::FileProxy> file_proxy( new base::FileProxy(task_runner.get())); @@ -321,8 +320,8 @@ gdb_debug_stub_port_map_[process_id] = port; if (port != kGdbDebugStubPortUnknown && !debug_stub_port_listener_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(debug_stub_port_listener_, port)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(debug_stub_port_listener_, port)); } } @@ -378,8 +377,10 @@ // We can get away not giving this a sequence ID because this is the first // task and further file access will not occur until after we get a // response. - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock(), kUserBlocking}, + base::PostTaskAndReply( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, base::BindOnce(ReadCache, validation_cache_file_path_, data), base::BindOnce(&NaClBrowser::OnValidationCacheLoaded, base::Unretained(this), base::Owned(data))); @@ -530,8 +531,8 @@ if (validation_cache_file_path_.empty()) { // Can't figure out what file to remove, but don't drop the callback. - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO}, - std::move(callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + std::move(callback)); } else { // Delegate the removal of the cache from the filesystem to another thread // to avoid blocking the IO thread.
diff --git a/components/nacl/browser/nacl_browser.h b/components/nacl/browser/nacl_browser.h index 85500b0..4cb7112 100644 --- a/components/nacl/browser/nacl_browser.h +++ b/components/nacl/browser/nacl_browser.h
@@ -206,8 +206,8 @@ base::circular_deque<base::Time> crash_times_; scoped_refptr<base::SequencedTaskRunner> file_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); DISALLOW_COPY_AND_ASSIGN(NaClBrowser); };
diff --git a/components/nacl/browser/nacl_file_host.cc b/components/nacl/browser/nacl_file_host.cc index 6d76b7e..c76d5a9 100644 --- a/components/nacl/browser/nacl_file_host.cc +++ b/components/nacl/browser/nacl_file_host.cc
@@ -102,7 +102,7 @@ // Not all PNaCl files are executable. Only register those that are // executable in the NaCl file_path cache. if (is_executable) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&DoRegisterOpenedNaClExecutableFile, nacl_host_message_filter, std::move(file_to_open), @@ -148,7 +148,7 @@ if (enable_validation_caching) { // This function is running on the blocking pool, but the path needs to be // registered in a structure owned by the IO thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &DoRegisterOpenedNaClExecutableFile, nacl_host_message_filter, @@ -178,10 +178,9 @@ const std::string& filename, bool is_executable, IPC::Message* reply_msg) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&DoOpenPnaclFile, nacl_host_message_filter, filename, - is_executable, reply_msg)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&DoOpenPnaclFile, nacl_host_message_filter, + filename, is_executable, reply_msg)); } // This function is security sensitive. Be sure to check with a security @@ -224,11 +223,10 @@ bool enable_validation_caching, IPC::Message* reply_msg) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OpenNaClExecutable, nacl_host_message_filter, - render_view_id, file_url, enable_validation_caching, - reply_msg)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OpenNaClExecutable, nacl_host_message_filter, + render_view_id, file_url, + enable_validation_caching, reply_msg)); return; } @@ -253,11 +251,10 @@ // The URL is part of the current app. Now query the extension system for the // file path and convert that to a file descriptor. This should be done on a // blocking pool thread. - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&DoOpenNaClExecutableOnThreadPool, - nacl_host_message_filter, file_url, - enable_validation_caching, reply_msg)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&DoOpenNaClExecutableOnThreadPool, + nacl_host_message_filter, file_url, + enable_validation_caching, reply_msg)); } } // namespace nacl_file_host
diff --git a/components/nacl/browser/nacl_host_message_filter.cc b/components/nacl/browser/nacl_host_message_filter.cc index 05dee81..fd6f887 100644 --- a/components/nacl/browser/nacl_host_message_filter.cc +++ b/components/nacl/browser/nacl_host_message_filter.cc
@@ -134,10 +134,9 @@ ppapi::PpapiPermissions(perms)); return; } - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&NaClHostMessageFilter::LaunchNaClContinuation, this, - launch_params, reply_msg)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&NaClHostMessageFilter::LaunchNaClContinuation, + this, launch_params, reply_msg)); } void NaClHostMessageFilter::LaunchNaClContinuation( @@ -181,9 +180,9 @@ // Process a list of resource file URLs in // |launch_params.resource_files_to_prefetch|. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_BLOCKING, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&NaClHostMessageFilter::BatchOpenResourceFiles, this, safe_launch_params, reply_msg, permissions)); @@ -219,7 +218,7 @@ break; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NaClHostMessageFilter::LaunchNaClContinuationOnIOThread, this, launch_params, reply_msg, prefetched_resource_files,
diff --git a/components/nacl/browser/nacl_process_host.cc b/components/nacl/browser/nacl_process_host.cc index 6169ba9a..3a124c5 100644 --- a/components/nacl/browser/nacl_process_host.cc +++ b/components/nacl/browser/nacl_process_host.cc
@@ -272,15 +272,17 @@ // handles. base::File file(IPC::PlatformFileForTransitToFile( prefetched_resource_files_[i].file)); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CloseFile, std::move(file))); } #endif // Open files need to be closed on the blocking pool. if (nexe_file_.IsValid()) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CloseFile, std::move(nexe_file_))); } @@ -809,11 +811,12 @@ // We have to reopen the file in the browser process; we don't want a // compromised renderer to pass an arbitrary fd that could get loaded // into the plugin process. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, // USER_BLOCKING because it is on the critical path of displaying the // official virtual keyboard on Chrome OS. https://crbug.com/976542 - {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_BLOCKING}, base::BindOnce(OpenNaClReadExecImpl, file_path, true /* is_executable */), base::BindOnce(&NaClProcessHost::StartNaClFileResolved, @@ -834,8 +837,9 @@ if (checked_nexe_file.IsValid()) { // Release the file received from the renderer. This has to be done on a // thread where IO is permitted, though. - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&CloseFile, std::move(nexe_file_))); params.nexe_file_path_metadata = file_path; params.nexe_file = @@ -1045,11 +1049,11 @@ } // Open the file. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, // USER_BLOCKING because it is on the critical path of displaying the // official virtual keyboard on Chrome OS. https://crbug.com/976542 - {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::Bind(OpenNaClReadExecImpl, file_path, true /* is_executable */), base::Bind(&NaClProcessHost::FileResolved, weak_factory_.GetWeakPtr(), file_token_lo, file_token_hi, file_path));
diff --git a/components/nacl/browser/pnacl_host.cc b/components/nacl/browser/pnacl_host.cc index 2b48a1e..79f3615 100644 --- a/components/nacl/browser/pnacl_host.cc +++ b/components/nacl/browser/pnacl_host.cc
@@ -32,9 +32,9 @@ static const int kTranslationCacheInitializationDelayMs = 20; void CloseBaseFile(base::File file) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(base::DoNothing::Once<base::File>(), std::move(file))); } @@ -200,8 +200,8 @@ if (!file.IsValid()) PLOG(ERROR) << "Temp file open failed: " << file.error_details(); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(cb, std::move(file))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(cb, std::move(file))); } void PnaclHost::CreateTemporaryFile(TempFileCallback cb) { @@ -228,7 +228,7 @@ } if (cache_state_ != CacheReady) { // If the backend hasn't yet initialized, try the request again later. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PnaclHost::GetNexeFd, base::Unretained(this), render_process_id, render_view_id, pp_instance, @@ -372,8 +372,9 @@ pt->got_nexe_fd = false; FileProxy* proxy(new FileProxy(std::move(file), this)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&FileProxy::Write, base::Unretained(proxy), pt->nexe_read_buffer), base::Bind(&FileProxy::WriteDone, base::Owned(proxy), entry->first)); @@ -446,8 +447,9 @@ entry->second.nexe_fd = NULL; entry->second.got_nexe_fd = false; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&PnaclHost::CopyFileToBuffer, Passed(&file)), base::Bind(&PnaclHost::StoreTranslatedNexe, base::Unretained(this), id)); @@ -575,7 +577,7 @@ RequeryMatchingTranslations(key); } } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PnaclHost::DeInitIfSafe, base::Unretained(this))); } @@ -591,7 +593,7 @@ } if (cache_state_ == CacheInitializing) { // If the backend hasn't yet initialized, try the request again later. - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PnaclHost::ClearTranslationCacheEntriesBetween, base::Unretained(this), initial_time, end_time, @@ -614,12 +616,12 @@ void PnaclHost::OnEntriesDoomed(base::OnceClosure callback, int net_error) { DCHECK(thread_checker_.CalledOnValidThread()); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, std::move(callback)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, std::move(callback)); pending_backend_operations_--; // When clearing the cache, the UI is blocked on all the cache-clearing // operations, and freeing the backend actually blocks the IO thread. So // instead of calling DeInitIfSafe directly, post it for later. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PnaclHost::DeInitIfSafe, base::Unretained(this))); }
diff --git a/components/nacl/browser/pnacl_host.h b/components/nacl/browser/pnacl_host.h index c64cdf5b..25cf38e 100644 --- a/components/nacl/browser/pnacl_host.h +++ b/components/nacl/browser/pnacl_host.h
@@ -180,8 +180,8 @@ void DeInitIfSafe(); scoped_refptr<base::SequencedTaskRunner> file_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); // Operations which are pending with the cache backend, which we should // wait for before destroying it (see comment on DeInitIfSafe).
diff --git a/components/nacl/browser/pnacl_translation_cache.cc b/components/nacl/browser/pnacl_translation_cache.cc index 6bb26fb2..0e9d333 100644 --- a/components/nacl/browser/pnacl_translation_cache.cc +++ b/components/nacl/browser/pnacl_translation_cache.cc
@@ -153,13 +153,12 @@ // Ensure we have called the user's callback if (step_ != FINISHED) { if (!read_callback_.is_null()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(read_callback_, net::ERR_ABORTED, - scoped_refptr<net::DrainableIOBuffer>())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(read_callback_, net::ERR_ABORTED, + scoped_refptr<net::DrainableIOBuffer>())); } if (!write_callback_.is_null()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(write_callback_), net::ERR_ABORTED)); } @@ -213,8 +212,8 @@ LOG(ERROR) << "Failed to close entry: " << net::ErrorToString(rv); entry_->Doom(); } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&CloseDiskCacheEntry, entry_)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&CloseDiskCacheEntry, entry_)); Finish(rv); } @@ -222,13 +221,13 @@ step_ = FINISHED; if (is_read_) { if (!read_callback_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(read_callback_, rv, io_buf_)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(read_callback_, rv, io_buf_)); } } else { if (!write_callback_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(write_callback_), rv)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(write_callback_), rv)); } } cache_->OpComplete(this); @@ -348,8 +347,8 @@ } // Invoke our client's callback function. if (!init_callback_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(init_callback_), rv)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(init_callback_), rv)); } }
diff --git a/components/net_log/net_export_file_writer.cc b/components/net_log/net_export_file_writer.cc index a64a35e..4f6fbc3 100644 --- a/components/net_log/net_export_file_writer.cc +++ b/components/net_log/net_export_file_writer.cc
@@ -75,8 +75,8 @@ // // These operations can be skipped on shutdown since FileNetLogObserver's API // doesn't require things to have completed until notified of completion. - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); }
diff --git a/components/ntp_snippets/remote/remote_suggestions_database.cc b/components/ntp_snippets/remote/remote_suggestions_database.cc index 6c76b42..b61121a0 100644 --- a/components/ntp_snippets/remote/remote_suggestions_database.cc +++ b/components/ntp_snippets/remote/remote_suggestions_database.cc
@@ -31,8 +31,9 @@ : RemoteSuggestionsDatabase( proto_database_provider, database_dir, - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})) {} RemoteSuggestionsDatabase::RemoteSuggestionsDatabase(
diff --git a/components/ntp_tiles/BUILD.gn b/components/ntp_tiles/BUILD.gn index 244ad33..d077115f 100644 --- a/components/ntp_tiles/BUILD.gn +++ b/components/ntp_tiles/BUILD.gn
@@ -55,7 +55,7 @@ deps = [ "//components/favicon/core", "//components/favicon_base", - "//components/google/core/browser", + "//components/google/core/common", "//components/image_fetcher/core", "//components/pref_registry", "//components/prefs",
diff --git a/components/offline_pages/content/renovations/test/page_renovator_browsertest.cc b/components/offline_pages/content/renovations/test/page_renovator_browsertest.cc index f1c5512..b3f88cd7 100644 --- a/components/offline_pages/content/renovations/test/page_renovator_browsertest.cc +++ b/components/offline_pages/content/renovations/test/page_renovator_browsertest.cc
@@ -194,7 +194,7 @@ void PageRenovatorBrowserTest::QuitRunLoop() { base::Closure quit_task = content::GetDeferredQuitTaskForRunLoop(run_loop_.get()); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, quit_task); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_task); } #if defined(OS_WIN)
diff --git a/components/omnibox/browser/autocomplete_controller.cc b/components/omnibox/browser/autocomplete_controller.cc index 304f3c82..994382d 100644 --- a/components/omnibox/browser/autocomplete_controller.cc +++ b/components/omnibox/browser/autocomplete_controller.cc
@@ -21,6 +21,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/memory_usage_estimator.h"
diff --git a/components/omnibox/browser/base_search_provider_unittest.cc b/components/omnibox/browser/base_search_provider_unittest.cc index 2ff2df2b..6f43cb0f 100644 --- a/components/omnibox/browser/base_search_provider_unittest.cc +++ b/components/omnibox/browser/base_search_provider_unittest.cc
@@ -78,7 +78,7 @@ new TemplateURLService( nullptr, std::unique_ptr<SearchTermsData>(new SearchTermsData), nullptr, std::unique_ptr<TemplateURLServiceClient>(), nullptr, - nullptr, base::Closure())); + base::Closure())); client_.reset(new MockAutocompleteProviderClient()); client_->set_template_url_service(std::move(template_url_service)); provider_ = new NiceMock<TestBaseSearchProvider>(
diff --git a/components/omnibox/browser/in_memory_url_index.cc b/components/omnibox/browser/in_memory_url_index.cc index e99dc70..8c87294 100644 --- a/components/omnibox/browser/in_memory_url_index.cc +++ b/components/omnibox/browser/in_memory_url_index.cc
@@ -94,8 +94,9 @@ private_data_(new URLIndexPrivateData), restore_cache_observer_(nullptr), save_cache_observer_(nullptr), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT})), + task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT})), shutdown_(false), restored_(false), needs_to_be_cached_(false),
diff --git a/components/omnibox/browser/on_device_head_provider.cc b/components/omnibox/browser/on_device_head_provider.cc index 25fd51c..18a24e0c 100644 --- a/components/omnibox/browser/on_device_head_provider.cc +++ b/components/omnibox/browser/on_device_head_provider.cc
@@ -14,6 +14,7 @@ #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "components/omnibox/browser/autocomplete_provider_listener.h" #include "components/omnibox/browser/base_search_provider.h"
diff --git a/components/omnibox/browser/on_device_model_update_listener.cc b/components/omnibox/browser/on_device_model_update_listener.cc index e8a5b58..4db4b72 100644 --- a/components/omnibox/browser/on_device_model_update_listener.cc +++ b/components/omnibox/browser/on_device_model_update_listener.cc
@@ -41,8 +41,8 @@ } OnDeviceModelUpdateListener::OnDeviceModelUpdateListener() - : task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, + : task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::MayBlock()})) {} OnDeviceModelUpdateListener::~OnDeviceModelUpdateListener() = default;
diff --git a/components/omnibox/browser/shortcuts_backend.cc b/components/omnibox/browser/shortcuts_backend.cc index 5201ae5..a81e7e3b 100644 --- a/components/omnibox/browser/shortcuts_backend.cc +++ b/components/omnibox/browser/shortcuts_backend.cc
@@ -77,8 +77,9 @@ current_state_(NOT_INITIALIZED), history_service_observer_(this), main_runner_(base::ThreadTaskRunnerHandle::Get()), - db_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + db_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), no_db_access_(suppress_db) { if (!suppress_db)
diff --git a/components/omnibox/browser/test_omnibox_client.cc b/components/omnibox/browser/test_omnibox_client.cc index a19ba11..aa76bd56 100644 --- a/components/omnibox/browser/test_omnibox_client.cc +++ b/components/omnibox/browser/test_omnibox_client.cc
@@ -47,7 +47,7 @@ new TemplateURLService( nullptr, std::unique_ptr<SearchTermsData>(new SearchTermsData), nullptr, std::unique_ptr<TemplateURLServiceClient>(), nullptr, - nullptr, base::Closure())); + base::Closure())); // Save a reference to the created TemplateURLService for test use. template_url_service_ = template_url_service.get();
diff --git a/components/optimization_guide/BUILD.gn b/components/optimization_guide/BUILD.gn index c7d4589b..a8b92a6d1 100644 --- a/components/optimization_guide/BUILD.gn +++ b/components/optimization_guide/BUILD.gn
@@ -2,6 +2,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +assert(!is_ios, "Optimization Guide is not available on iOS.") + static_library("optimization_guide") { sources = [ "bloom_filter.cc", @@ -42,6 +44,7 @@ "//components/leveldb_proto", "//components/optimization_guide/proto:optimization_guide_proto", "//components/prefs", + "//content/public/browser", "//google_apis", "//net:net", "//services/network/public/cpp",
diff --git a/components/optimization_guide/DEPS b/components/optimization_guide/DEPS index f2c9a00..5f16a15 100644 --- a/components/optimization_guide/DEPS +++ b/components/optimization_guide/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/leveldb_proto", "+components/prefs", + "+content/public/browser", "+google_apis", "+net", "+services/network",
diff --git a/components/optimization_guide/hints_fetcher.cc b/components/optimization_guide/hints_fetcher.cc index 66f626b..d890e1e82 100644 --- a/components/optimization_guide/hints_fetcher.cc +++ b/components/optimization_guide/hints_fetcher.cc
@@ -12,6 +12,7 @@ #include "base/metrics/histogram_macros.h" #include "components/optimization_guide/optimization_guide_features.h" #include "components/optimization_guide/proto/hints.pb.h" +#include "content/public/browser/network_service_instance.h" #include "net/base/load_flags.h" #include "net/base/url_util.h" #include "net/http/http_request_headers.h" @@ -42,6 +43,11 @@ HintsFetchedCallback hints_fetched_callback) { SEQUENCE_CHECKER(sequence_checker_); + if (content::GetNetworkConnectionTracker()->IsOffline()) { + std::move(hints_fetched_callback).Run(base::nullopt); + return false; + } + if (url_loader_) return false;
diff --git a/components/optimization_guide/hints_fetcher_unittest.cc b/components/optimization_guide/hints_fetcher_unittest.cc index 8e56703..429e563 100644 --- a/components/optimization_guide/hints_fetcher_unittest.cc +++ b/components/optimization_guide/hints_fetcher_unittest.cc
@@ -18,6 +18,7 @@ #include "net/base/url_util.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/test/test_network_connection_tracker.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" @@ -49,6 +50,18 @@ bool hints_fetched() { return hints_fetched_; } + void SetConnectionOffline() { + network_tracker_ = network::TestNetworkConnectionTracker::GetInstance(); + network_tracker_->SetConnectionType( + network::mojom::ConnectionType::CONNECTION_NONE); + } + + void SetConnectionOnline() { + network_tracker_ = network::TestNetworkConnectionTracker::GetInstance(); + network_tracker_->SetConnectionType( + network::mojom::ConnectionType::CONNECTION_4G); + } + protected: bool FetchHints(const std::vector<std::string>& hosts) { bool status = hints_fetcher_->FetchOptimizationGuideServiceHints( @@ -90,6 +103,7 @@ scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_; network::TestURLLoaderFactory test_url_loader_factory_; + network::TestNetworkConnectionTracker* network_tracker_; DISALLOW_COPY_AND_ASSIGN(HintsFetcherTest); }; @@ -135,4 +149,17 @@ EXPECT_FALSE(hints_fetched()); } +TEST_F(HintsFetcherTest, FetchAttemptWhenNetworkOffline) { + SetConnectionOffline(); + std::string response_content; + EXPECT_FALSE(FetchHints(std::vector<std::string>())); + EXPECT_FALSE(hints_fetched()); + + SetConnectionOnline(); + EXPECT_TRUE(FetchHints(std::vector<std::string>())); + VerifyHasPendingFetchRequests(); + EXPECT_TRUE(SimulateResponse(response_content, net::HTTP_OK)); + EXPECT_TRUE(hints_fetched()); +} + } // namespace optimization_guide
diff --git a/components/optimization_guide/optimization_guide_prefs.cc b/components/optimization_guide/optimization_guide_prefs.cc index 5d16393..e759f55 100644 --- a/components/optimization_guide/optimization_guide_prefs.cc +++ b/components/optimization_guide/optimization_guide_prefs.cc
@@ -33,6 +33,13 @@ const char kHintsFetcherTopHostBlacklistState[] = "optimization_guide.hintsfetcher.top_host_blacklist_state"; +// A string pref that stores the version of the Optimization Hints component +// that is currently being processed. This pref is cleared once processing +// completes. It is used for detecting a potential crash loop on processing a +// version of hints. +const char kPendingHintsProcessingVersion[] = + "optimization_guide.pending_hints_processing_version"; + void RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kHintLoadedCounts, PrefRegistry::LOSSY_PREF); registry->RegisterInt64Pref( @@ -45,6 +52,8 @@ kHintsFetcherTopHostBlacklistState, static_cast<int>(HintsFetcherTopHostBlacklistState::kNotInitialized), PrefRegistry::LOSSY_PREF); + registry->RegisterStringPref(kPendingHintsProcessingVersion, "", + PrefRegistry::LOSSY_PREF); } } // namespace prefs
diff --git a/components/optimization_guide/optimization_guide_prefs.h b/components/optimization_guide/optimization_guide_prefs.h index 3c0d998..685efb3a 100644 --- a/components/optimization_guide/optimization_guide_prefs.h +++ b/components/optimization_guide/optimization_guide_prefs.h
@@ -16,6 +16,7 @@ extern const char kHintsFetcherLastFetchAttempt[]; extern const char kHintsFetcherTopHostBlacklist[]; extern const char kHintsFetcherTopHostBlacklistState[]; +extern const char kPendingHintsProcessingVersion[]; // State of |HintsFetcherTopHostsBlacklist|. The blacklist begins in // kNotInitialized and transitions to kInitialized after
diff --git a/components/password_manager/core/browser/credential_manager_impl_unittest.cc b/components/password_manager/core/browser/credential_manager_impl_unittest.cc index c9a99b92..bae6bd4a 100644 --- a/components/password_manager/core/browser/credential_manager_impl_unittest.cc +++ b/components/password_manager/core/browser/credential_manager_impl_unittest.cc
@@ -32,6 +32,7 @@ using testing::_; using testing::ElementsAre; +using testing::Pair; using testing::Pointee; using testing::UnorderedElementsAre; @@ -58,6 +59,11 @@ bool(const std::vector<autofill::PasswordForm*>& local_forms, const GURL& origin, const CredentialsCallback& callback)); + MOCK_METHOD3( + PasswordWasAutofilled, + void(const std::map<base::string16, const autofill::PasswordForm*>&, + const GURL&, + const std::vector<const autofill::PasswordForm*>*)); explicit MockPasswordManagerClient(PasswordStore* store) : store_(store), password_manager_(this) { @@ -964,7 +970,6 @@ std::vector<GURL> federations; EXPECT_CALL(*client_, NotifyUserCouldBeAutoSignedInPtr(_)).Times(0); - ExpectZeroClickSignInFailure(CredentialMediationRequirement::kSilent, false, federations); } @@ -1615,4 +1620,33 @@ EXPECT_TRUE(client_->pending_manager()->IsBlacklisted()); } +TEST_F(CredentialManagerImplTest, + ManagePasswordsUICredentialsUpdatedUnconditionallyInSilentMediation) { + autofill::PasswordForm federated = origin_path_form_; + federated.federation_origin = + url::Origin::Create(GURL("https://google.com/")); + federated.signon_realm = + "federation://" + federated.origin.host() + "/google.com"; + store_->AddLogin(federated); + + form_.username_value = base::ASCIIToUTF16("username_value"); + store_->AddLogin(form_); + + EXPECT_CALL(*client_, + PasswordWasAutofilled( + ElementsAre(Pair(form_.username_value, Pointee(form_))), _, + Pointee(ElementsAre(Pointee(federated))))); + + bool called = false; + CredentialManagerError error; + base::Optional<CredentialInfo> credential; + std::vector<GURL> federations; + federations.push_back(GURL("https://google.com/")); + + CallGet(CredentialMediationRequirement::kSilent, true, federations, + base::BindOnce(&GetCredentialCallback, &called, &error, &credential)); + + RunAllPendingTasks(); +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/credential_manager_pending_request_task.cc b/components/password_manager/core/browser/credential_manager_pending_request_task.cc index 689d126..8c9e654 100644 --- a/components/password_manager/core/browser/credential_manager_pending_request_task.cc +++ b/components/password_manager/core/browser/credential_manager_pending_request_task.cc
@@ -196,6 +196,20 @@ else get_result = metrics_util::CredentialManagerGetResult::kNoneFirstRun; + if (!local_results.empty()) { + std::map<base::string16, const autofill::PasswordForm*> + non_federated_matches; + std::vector<const autofill::PasswordForm*> federated_matches; + for (const auto& result : local_results) { + if (result->IsFederatedCredential()) { + federated_matches.emplace_back(result.get()); + } else { + non_federated_matches.emplace(result->username_value, result.get()); + } + } + delegate_->client()->PasswordWasAutofilled(non_federated_matches, origin_, + &federated_matches); + } if (can_use_autosignin) { // The user had credentials, but either chose not to share them with the // site, or was prevented from doing so by lack of zero-click (or the @@ -204,7 +218,6 @@ delegate_->client()->NotifyUserCouldBeAutoSignedIn( std::move(local_results[0])); } - LogCredentialManagerGetResult(get_result, mediation_); delegate_->SendCredential(send_callback_, CredentialInfo()); return;
diff --git a/components/password_manager/core/browser/import/password_importer.cc b/components/password_manager/core/browser/import/password_importer.cc index 9b45e71..dcf08910 100644 --- a/components/password_manager/core/browser/import/password_importer.cc +++ b/components/password_manager/core/browser/import/password_importer.cc
@@ -49,8 +49,9 @@ const CompletionCallback& completion) { // Posting with USER_VISIBLE priority, because the result of the import is // visible to the user in the password settings page. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::MayBlock()}, base::Bind(&ReadFileToString, path), base::Bind(&ParsePasswords, completion)); }
diff --git a/components/password_manager/core/browser/new_password_form_manager.cc b/components/password_manager/core/browser/new_password_form_manager.cc index 644c3d58..6f1cc59 100644 --- a/components/password_manager/core/browser/new_password_form_manager.cc +++ b/components/password_manager/core/browser/new_password_form_manager.cc
@@ -742,13 +742,10 @@ #endif } - // TODO(https://crbug.com/831123): Implement correct treating of federated - // matches. - std::vector<const PasswordForm*> federated_matches; SendFillInformationToRenderer(client_, driver_.get(), IsBlacklisted(), *observed_password_form.get(), best_matches_, - federated_matches, preferred_match_, - metrics_recorder_.get()); + form_fetcher_->GetFederatedMatches(), + preferred_match_, metrics_recorder_.get()); } void NewPasswordFormManager::FillForm(const FormData& observed_form) {
diff --git a/components/password_manager/core/browser/password_store.cc b/components/password_manager/core/browser/password_store.cc index a4ebcbc..0e4b2758 100644 --- a/components/password_manager/core/browser/password_store.cc +++ b/components/password_manager/core/browser/password_store.cc
@@ -494,8 +494,8 @@ scoped_refptr<base::SequencedTaskRunner> PasswordStore::CreateBackgroundTaskRunner() const { - return base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + return base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}); } bool PasswordStore::InitOnBackgroundSequence(
diff --git a/components/password_manager/core/browser/password_store_factory_util.cc b/components/password_manager/core/browser/password_store_factory_util.cc index 38b009d..870b84d0 100644 --- a/components/password_manager/core/browser/password_store_factory_util.cc +++ b/components/password_manager/core/browser/password_store_factory_util.cc
@@ -40,8 +40,8 @@ // // Task priority is USER_VISIBLE, because AffiliationService-related tasks // block obtaining credentials from PasswordStore, hence password autofill. - static auto backend_task_runner = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + static auto backend_task_runner = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}); // The PasswordStore is so far the only consumer of the AffiliationService, // therefore the service is owned by the AffiliatedMatchHelper, which in turn
diff --git a/components/password_manager/core/common/passwords_directory_util_ios.cc b/components/password_manager/core/common/passwords_directory_util_ios.cc index c27880d..b9e30587 100644 --- a/components/password_manager/core/common/passwords_directory_util_ios.cc +++ b/components/password_manager/core/common/passwords_directory_util_ios.cc
@@ -35,10 +35,11 @@ } void DeletePasswordsDirectory() { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, - base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, - base::BindOnce(&DeletePasswordsDirectorySync)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(&DeletePasswordsDirectorySync)); } } // namespace password_manager
diff --git a/components/payments/content/installable_payment_app_crawler.cc b/components/payments/content/installable_payment_app_crawler.cc index e5a0a6b..76c20508 100644 --- a/components/payments/content/installable_payment_app_crawler.cc +++ b/components/payments/content/installable_payment_app_crawler.cc
@@ -68,7 +68,7 @@ if (manifests_to_download.empty()) { // Post the result back asynchronously. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &InstallablePaymentAppCrawler::FinishCrawlingPaymentAppsIfReady,
diff --git a/components/plugins/renderer/webview_plugin.h b/components/plugins/renderer/webview_plugin.h index ffd59c4..0e1d05d 100644 --- a/components/plugins/renderer/webview_plugin.h +++ b/components/plugins/renderer/webview_plugin.h
@@ -180,13 +180,13 @@ const gfx::Point&) override; void DidChangeCursor(const blink::WebCursorInfo& cursor) override; void ScheduleAnimation() override; - std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() - override; // WebLocalFrameClient methods: void BindToFrame(blink::WebNavigationControl* frame) override; void DidClearWindowObject() override; void FrameDetached(DetachType) override; + std::unique_ptr<blink::WebURLLoaderFactory> CreateURLLoaderFactory() + override; private: WebViewPlugin* plugin_;
diff --git a/components/policy/core/browser/BUILD.gn b/components/policy/core/browser/BUILD.gn index a2fc5fe75..bf4ee73 100644 --- a/components/policy/core/browser/BUILD.gn +++ b/components/policy/core/browser/BUILD.gn
@@ -56,7 +56,7 @@ deps = [ "//base/third_party/dynamic_annotations", "//components/bookmarks/managed", - "//components/google/core/browser", + "//components/google/core/common", "//components/keyed_service/core", "//components/pref_registry", "//components/prefs",
diff --git a/components/policy/core/browser/url_blacklist_manager.cc b/components/policy/core/browser/url_blacklist_manager.cc index a8c0056..12b0f66 100644 --- a/components/policy/core/browser/url_blacklist_manager.cc +++ b/components/policy/core/browser/url_blacklist_manager.cc
@@ -431,8 +431,8 @@ // This class assumes that it is created on the same thread that // |pref_service_| lives on. ui_task_runner_ = base::SequencedTaskRunnerHandle::Get(); - background_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT}); + background_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT}); pref_change_registrar_.Init(pref_service_); base::Closure callback = base::Bind(&URLBlacklistManager::ScheduleUpdate,
diff --git a/components/policy/core/common/cloud/cloud_policy_manager.cc b/components/policy/core/common/cloud/cloud_policy_manager.cc index bc7c924..b7812d57 100644 --- a/components/policy/core/common/cloud/cloud_policy_manager.cc +++ b/components/policy/core/common/cloud/cloud_policy_manager.cc
@@ -146,7 +146,7 @@ // ComponentCloudPolicyService's |backend_task_runner| and |cache| must live // on the same task runner. const auto task_runner = - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}); std::unique_ptr<ResourceCache> resource_cache(new ResourceCache( policy_cache_path, task_runner, /* max_cache_size */ base::nullopt)); component_policy_service_.reset(new ComponentCloudPolicyService(
diff --git a/components/policy/core/common/configuration_policy_provider_test.cc b/components/policy/core/common/configuration_policy_provider_test.cc index 5453ef3..9fbbeb5 100644 --- a/components/policy/core/common/configuration_policy_provider_test.cc +++ b/components/policy/core/common/configuration_policy_provider_test.cc
@@ -205,7 +205,7 @@ provider_.reset(test_harness_->CreateProvider( &schema_registry_, - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}))); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock()}))); provider_->Init(&schema_registry_); // Some providers do a reload on init. Make sure any notifications generated // are fired now.
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index c2909b2..4cce316 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -230,11 +230,9 @@ PolicyListMerger policy_list_merger(std::move(policy_lists_to_merge)); PolicyDictionaryMerger policy_dictionary_merger( std::move(policy_dictionaries_to_merge)); - PolicyGroupMerger policy_group_merger; for (auto it = bundle.begin(); it != bundle.end(); ++it) { - it->second->MergeValues( - {&policy_list_merger, &policy_dictionary_merger, &policy_group_merger}); + it->second->MergeValues({&policy_list_merger, &policy_dictionary_merger}); } // Swap first, so that observers that call GetPolicies() see the current
diff --git a/components/policy/core/common/policy_service_impl_unittest.cc b/components/policy/core/common/policy_service_impl_unittest.cc index a427cb35..8e6ccbf 100644 --- a/components/policy/core/common/policy_service_impl_unittest.cc +++ b/components/policy/core/common/policy_service_impl_unittest.cc
@@ -904,7 +904,6 @@ merged.AddWarning(IDS_POLICY_CONFLICT_DIFF_VALUE); expected_chrome.Set(key::kExtensionInstallForcelist, merged.DeepCopy()); expected_chrome.Set(key::kExtensionInstallBlacklist, std::move(merged)); - entry_list_3.SetIgnoredByPolicyAtomicGroup(); expected_chrome.Set(key::kExtensionInstallWhitelist, std::move(entry_list_3)); provider0_.UpdatePolicy(std::move(policy_bundle1));
diff --git a/components/prefs/json_pref_store.h b/components/prefs/json_pref_store.h index e29e3b5..089ce0b6 100644 --- a/components/prefs/json_pref_store.h +++ b/components/prefs/json_pref_store.h
@@ -67,8 +67,9 @@ JsonPrefStore(const base::FilePath& pref_filename, std::unique_ptr<PrefFilter> pref_filter = nullptr, scoped_refptr<base::SequencedTaskRunner> file_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::BLOCK_SHUTDOWN})); // PrefStore overrides:
diff --git a/components/prefs/pref_member_unittest.cc b/components/prefs/pref_member_unittest.cc index eced7b5..420d24b 100644 --- a/components/prefs/pref_member_unittest.cc +++ b/components/prefs/pref_member_unittest.cc
@@ -36,7 +36,8 @@ : public base::RefCountedThreadSafe<GetPrefValueHelper> { public: GetPrefValueHelper() - : value_(false), task_runner_(base::CreateSequencedTaskRunner({})) {} + : value_(false), + task_runner_(base::CreateSequencedTaskRunner({base::ThreadPool()})) {} void Init(const std::string& pref_name, PrefService* prefs) { pref_.Init(pref_name, prefs);
diff --git a/components/previews/content/previews_decider_impl_unittest.cc b/components/previews/content/previews_decider_impl_unittest.cc index c165150..bdbe9ca 100644 --- a/components/previews/content/previews_decider_impl_unittest.cc +++ b/components/previews/content/previews_decider_impl_unittest.cc
@@ -439,8 +439,9 @@ std::make_unique<TestPreviewsOptimizationGuide>( &optimization_guide_service_, scoped_task_environment_.GetMainThreadTaskRunner(), - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}), + base::CreateSequencedTaskRunner({base::ThreadPool(), + base::MayBlock(), + base::TaskPriority::BEST_EFFORT}), temp_dir_.GetPath(), pref_service_.get(), db_provider_.get(), &optimization_guide_top_host_provider_, url_loader_factory_), base::BindRepeating(&IsPreviewFieldTrialEnabled),
diff --git a/components/proxy_config/ios/proxy_service_factory.cc b/components/proxy_config/ios/proxy_service_factory.cc index c5fc61d1..d1f0ca9 100644 --- a/components/proxy_config/ios/proxy_service_factory.cc +++ b/components/proxy_config/ios/proxy_service_factory.cc
@@ -20,7 +20,7 @@ ProxyServiceFactory::CreateProxyConfigService(PrefProxyConfigTracker* tracker) { std::unique_ptr<net::ProxyConfigService> base_service( net::ProxyResolutionService::CreateSystemProxyConfigService( - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO}))); + base::CreateSingleThreadTaskRunner({web::WebThread::IO}))); return tracker->CreateTrackingProxyConfigService(std::move(base_service)); } @@ -31,7 +31,7 @@ PrefService* local_state_prefs) { return std::make_unique<PrefProxyConfigTrackerImpl>( browser_state_prefs, - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO})); + base::CreateSingleThreadTaskRunner({web::WebThread::IO})); } // static @@ -40,7 +40,7 @@ PrefService* local_state_prefs) { return std::make_unique<PrefProxyConfigTrackerImpl>( local_state_prefs, - base::CreateSingleThreadTaskRunnerWithTraits({web::WebThread::IO})); + base::CreateSingleThreadTaskRunner({web::WebThread::IO})); } // static
diff --git a/components/quirks/quirks_manager.cc b/components/quirks/quirks_manager.cc index 81a1344..624d7ae 100644 --- a/components/quirks/quirks_manager.cc +++ b/components/quirks/quirks_manager.cc
@@ -62,7 +62,8 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : waiting_for_login_(true), delegate_(std::move(delegate)), - task_runner_(base::CreateTaskRunnerWithTraits({base::MayBlock()})), + task_runner_( + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock()})), local_state_(local_state), url_loader_factory_(std::move(url_loader_factory)), weak_ptr_factory_(this) {}
diff --git a/components/rlz/BUILD.gn b/components/rlz/BUILD.gn index c5d7a9d..3676c96 100644 --- a/components/rlz/BUILD.gn +++ b/components/rlz/BUILD.gn
@@ -15,7 +15,7 @@ deps = [ "//base", - "//components/google/core/browser", + "//components/google/core/common", "//net", "//rlz:rlz_lib", "//services/network/public/cpp:cpp",
diff --git a/components/rlz/rlz_tracker.cc b/components/rlz/rlz_tracker.cc index 184cef8..100c292 100644 --- a/components/rlz/rlz_tracker.cc +++ b/components/rlz/rlz_tracker.cc
@@ -223,9 +223,9 @@ homepage_used_(false), app_list_used_(false), min_init_delay_(kMinInitDelay), - background_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::MayBlock(), - base::TaskPriority::BEST_EFFORT})) { + background_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::MayBlock(), base::TaskPriority::BEST_EFFORT})) { DETACH_FROM_SEQUENCE(sequence_checker_); }
diff --git a/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc b/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc index e0c5810..19c2555b 100644 --- a/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc +++ b/components/safe_browsing/android/safe_browsing_api_handler_bridge.cc
@@ -41,9 +41,8 @@ const ThreatMetadata& metadata) { CHECK(callback); // Remove after fixing crbug.com/889972 CHECK(!callback->is_null()); // Remove after fixing crbug.com/889972 - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(*callback), threat_type, metadata)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(*callback), threat_type, metadata)); } void ReportUmaResult(safe_browsing::UmaRemoteCallResult result) { @@ -200,10 +199,9 @@ << " with status=" << result_status << " and metadata=[" << metadata_str << "]"; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&OnUrlCheckDoneOnIOThread, callback_id, result_status, - metadata_str)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&OnUrlCheckDoneOnIOThread, callback_id, + result_status, metadata_str)); } //
diff --git a/components/safe_browsing/browser/browser_url_loader_throttle.cc b/components/safe_browsing/browser/browser_url_loader_throttle.cc index cf40771..fce42c5 100644 --- a/components/safe_browsing/browser/browser_url_loader_throttle.cc +++ b/components/safe_browsing/browser/browser_url_loader_throttle.cc
@@ -30,7 +30,7 @@ return; } - base::PostTaskWithTraits(from_here, {thread_id}, std::move(task)); + base::PostTask(from_here, {thread_id}, std::move(task)); } } // namespace
diff --git a/components/safe_browsing/browser/safe_browsing_url_checker_impl.cc b/components/safe_browsing/browser/safe_browsing_url_checker_impl.cc index 20595fe..fb4a50c4 100644 --- a/components/safe_browsing/browser/safe_browsing_url_checker_impl.cc +++ b/components/safe_browsing/browser/safe_browsing_url_checker_impl.cc
@@ -180,8 +180,8 @@ resource.callback = base::Bind(&SafeBrowsingUrlCheckerImpl::OnBlockingPageComplete, weak_factory_.GetWeakPtr()); - resource.callback_thread = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); + resource.callback_thread = + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}); resource.web_contents_getter = web_contents_getter_; resource.threat_source = database_manager_->GetThreatSource(); @@ -254,7 +254,7 @@ TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "CheckUrl", this, "url", url.spec()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&SafeBrowsingUrlCheckerImpl::OnCheckBrowseUrlResult, weak_factory_.GetWeakPtr(), url, threat_type,
diff --git a/components/safe_browsing/browser/safe_browsing_url_request_context_getter.cc b/components/safe_browsing/browser/safe_browsing_url_request_context_getter.cc index e8f85713..30d22f1 100644 --- a/components/safe_browsing/browser/safe_browsing_url_request_context_getter.cc +++ b/components/safe_browsing/browser/safe_browsing_url_request_context_getter.cc
@@ -27,7 +27,7 @@ user_data_dir_(user_data_dir), system_context_getter_(system_context_getter), network_task_runner_( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})) { + base::CreateSingleThreadTaskRunner({BrowserThread::IO})) { DCHECK(!user_data_dir.empty()); DCHECK(system_context_getter_); } @@ -45,8 +45,9 @@ safe_browsing_request_context_->CopyFrom( system_context_getter_->GetURLRequestContext()); scoped_refptr<base::SequencedTaskRunner> background_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), net::GetCookieStoreBackgroundSequencePriority(), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + net::GetCookieStoreBackgroundSequencePriority(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); // Set up the CookieStore
diff --git a/components/safe_browsing/browser/threat_details.cc b/components/safe_browsing/browser/threat_details.cc index 1c85e99..55925b2a99 100644 --- a/components/safe_browsing/browser/threat_details.cc +++ b/components/safe_browsing/browser/threat_details.cc
@@ -850,7 +850,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&WebUIInfoSingleton::AddToCSBRRsSent, base::Unretained(WebUIInfoSingleton::GetInstance()), @@ -878,7 +878,7 @@ void ThreatDetails::AllDone() { is_all_done_ = true; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(done_callback_, base::Unretained(web_contents()))); }
diff --git a/components/safe_browsing/browser/threat_details_cache.cc b/components/safe_browsing/browser/threat_details_cache.cc index cdd90849..0abc641a 100644 --- a/components/safe_browsing/browser/threat_details_cache.cc +++ b/components/safe_browsing/browser/threat_details_cache.cc
@@ -52,9 +52,8 @@ // Post a task in the message loop, so the callers don't need to // check if we call their callback immediately. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ThreatDetailsCacheCollector::OpenEntry, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ThreatDetailsCacheCollector::OpenEntry, this)); } bool ThreatDetailsCacheCollector::HasStarted() { @@ -228,16 +227,15 @@ current_load_.reset(); // Create a task so we don't take over the UI thread for too long. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ThreatDetailsCacheCollector::OpenEntry, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ThreatDetailsCacheCollector::OpenEntry, this)); } void ThreatDetailsCacheCollector::AllDone(bool success) { DVLOG(1) << "AllDone"; DCHECK_CURRENTLY_ON(BrowserThread::UI); *result_ = success; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, callback_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, callback_); callback_.Reset(); }
diff --git a/components/safe_browsing/browser/threat_details_history.cc b/components/safe_browsing/browser/threat_details_history.cc index 1381c2a..3ea0e17 100644 --- a/components/safe_browsing/browser/threat_details_history.cc +++ b/components/safe_browsing/browser/threat_details_history.cc
@@ -46,7 +46,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ThreatDetailsRedirectsCollector::StartGetRedirects, this, urls)); @@ -112,7 +112,7 @@ void ThreatDetailsRedirectsCollector::AllDone() { DVLOG(1) << "AllDone"; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, callback_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, callback_); callback_.Reset(); }
diff --git a/components/safe_browsing/db/database_manager.cc b/components/safe_browsing/db/database_manager.cc index 966ea6c..a00eb65 100644 --- a/components/safe_browsing/db/database_manager.cc +++ b/components/safe_browsing/db/database_manager.cc
@@ -23,8 +23,7 @@ SafeBrowsingDatabaseManager::SafeBrowsingDatabaseManager() : base::RefCountedDeleteOnSequence<SafeBrowsingDatabaseManager>( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO})), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO})), enabled_(false) {} SafeBrowsingDatabaseManager::~SafeBrowsingDatabaseManager() {
diff --git a/components/safe_browsing/db/v4_local_database_manager.cc b/components/safe_browsing/db/v4_local_database_manager.cc index 2ac1d8d..698e1451 100644 --- a/components/safe_browsing/db/v4_local_database_manager.cc +++ b/components/safe_browsing/db/v4_local_database_manager.cc
@@ -264,8 +264,8 @@ list_infos_(GetListInfos()), task_runner_(task_runner_for_tests ? task_runner_for_tests - : base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), + : base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) { DCHECK(!base_path_.empty()); DCHECK(!list_infos_.empty()); @@ -603,7 +603,7 @@ v4_database_->RecordFileSizeHistograms(); UpdateListClientStates(GetStoreStateMap()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &SafeBrowsingDatabaseManager::NotifyDatabaseUpdateFinished, this)); @@ -808,14 +808,13 @@ full_hash_infos.emplace_back(entry.first, list_id, next); } } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&V4LocalDatabaseManager::OnFullHashResponse, - weak_factory_.GetWeakPtr(), std::move(check), - full_hash_infos)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&V4LocalDatabaseManager::OnFullHashResponse, + weak_factory_.GetWeakPtr(), std::move(check), + full_hash_infos)); } else { // Post on the IO thread to enforce async behavior. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&V4LocalDatabaseManager::PerformFullHashCheck, weak_factory_.GetWeakPtr(), std::move(check)));
diff --git a/components/safe_browsing/password_protection/password_protection_request.cc b/components/safe_browsing/password_protection/password_protection_request.cc index f7236da..c78a9624 100644 --- a/components/safe_browsing/password_protection/password_protection_request.cc +++ b/components/safe_browsing/password_protection/password_protection_request.cc
@@ -126,8 +126,7 @@ // check is required. auto result_callback = base::Bind(&OnWhitelistCheckDoneOnIO, GetWeakPtr()); tracker_.PostTask( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}).get(), - FROM_HERE, + base::CreateSingleThreadTaskRunner({BrowserThread::IO}).get(), FROM_HERE, base::BindOnce(&AllowlistCheckerClient::StartCheckCsdWhitelist, password_protection_service_->database_manager(), main_frame_url_, result_callback)); @@ -138,7 +137,7 @@ base::WeakPtr<PasswordProtectionRequest> weak_request, bool match_whitelist) { // Don't access weak_request on IO thread. Move it back to UI thread first. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PasswordProtectionRequest::OnWhitelistCheckDone, weak_request, match_whitelist)); @@ -324,9 +323,9 @@ void PasswordProtectionRequest::OnScreenshotTaken(const SkBitmap& screenshot) { // Do the feature extraction on a worker thread, to avoid blocking the UI. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&ExtractVisualFeatures, screenshot), base::BindOnce(&PasswordProtectionRequest::OnVisualFeatureCollectionDone, @@ -414,7 +413,7 @@ // The weak pointer used for the timeout will be invalidated (and // hence would prevent the timeout) if the check completes on time and // execution reaches Finish(). - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PasswordProtectionRequest::Cancel, GetWeakPtr(), true), base::TimeDelta::FromMilliseconds(request_timeout_in_ms_));
diff --git a/components/safe_browsing/password_protection/password_protection_service.cc b/components/safe_browsing/password_protection/password_protection_service.cc index 73167a96..d896c68 100644 --- a/components/safe_browsing/password_protection/password_protection_service.cc +++ b/components/safe_browsing/password_protection/password_protection_service.cc
@@ -320,7 +320,7 @@ void PasswordProtectionService::OnURLsDeleted( history::HistoryService* history_service, const history::DeletionInfo& deletion_info) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindRepeating(&PasswordProtectionService:: RemoveUnhandledSyncPasswordReuseOnURLsDeleted,
diff --git a/components/safe_browsing/triggers/ad_popup_trigger.cc b/components/safe_browsing/triggers/ad_popup_trigger.cc index 0aaece8..b4d1f6dc 100644 --- a/components/safe_browsing/triggers/ad_popup_trigger.cc +++ b/components/safe_browsing/triggers/ad_popup_trigger.cc
@@ -66,8 +66,8 @@ prefs_(prefs), url_loader_factory_(url_loader_factory), history_service_(history_service), - task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})) {} + task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})) {} AdPopupTrigger::~AdPopupTrigger() {}
diff --git a/components/safe_browsing/triggers/ad_redirect_trigger.cc b/components/safe_browsing/triggers/ad_redirect_trigger.cc index de3aa4e..a70f466 100644 --- a/components/safe_browsing/triggers/ad_redirect_trigger.cc +++ b/components/safe_browsing/triggers/ad_redirect_trigger.cc
@@ -65,8 +65,8 @@ prefs_(prefs), url_loader_factory_(url_loader_factory), history_service_(history_service), - task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})) {} + task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})) {} AdRedirectTrigger::~AdRedirectTrigger() {}
diff --git a/components/safe_browsing/triggers/ad_sampler_trigger.cc b/components/safe_browsing/triggers/ad_sampler_trigger.cc index 75fa07f..c6c71ff 100644 --- a/components/safe_browsing/triggers/ad_sampler_trigger.cc +++ b/components/safe_browsing/triggers/ad_sampler_trigger.cc
@@ -92,8 +92,8 @@ prefs_(prefs), url_loader_factory_(url_loader_factory), history_service_(history_service), - task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})) {} + task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})) {} AdSamplerTrigger::~AdSamplerTrigger() {}
diff --git a/components/safe_browsing/triggers/suspicious_site_trigger.cc b/components/safe_browsing/triggers/suspicious_site_trigger.cc index ca66d9f..a0fc823 100644 --- a/components/safe_browsing/triggers/suspicious_site_trigger.cc +++ b/components/safe_browsing/triggers/suspicious_site_trigger.cc
@@ -66,8 +66,8 @@ prefs_(prefs), url_loader_factory_(url_loader_factory), history_service_(history_service), - task_runner_(base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI})) {} + task_runner_( + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI})) {} SuspiciousSiteTrigger::~SuspiciousSiteTrigger() {}
diff --git a/components/safe_browsing/verdict_cache_manager.cc b/components/safe_browsing/verdict_cache_manager.cc index c31a5fd..71d15021 100644 --- a/components/safe_browsing/verdict_cache_manager.cc +++ b/components/safe_browsing/verdict_cache_manager.cc
@@ -385,12 +385,11 @@ void VerdictCacheManager::OnURLsDeleted( history::HistoryService* history_service, const history::DeletionInfo& deletion_info) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindRepeating( - &VerdictCacheManager::RemoveContentSettingsOnURLsDeleted, - GetWeakPtr(), deletion_info.IsAllHistory(), - deletion_info.deleted_rows())); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindRepeating( + &VerdictCacheManager::RemoveContentSettingsOnURLsDeleted, + GetWeakPtr(), deletion_info.IsAllHistory(), + deletion_info.deleted_rows())); } // Overridden from history::HistoryServiceObserver.
diff --git a/components/safe_browsing/web_ui/safe_browsing_ui.cc b/components/safe_browsing/web_ui/safe_browsing_ui.cc index f595fdc..333eff8 100644 --- a/components/safe_browsing/web_ui/safe_browsing_ui.cc +++ b/components/safe_browsing/web_ui/safe_browsing_ui.cc
@@ -168,10 +168,9 @@ base::Time timestamp = base::Time::Now(); log_messages_.push_back(std::make_pair(timestamp, message)); - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&WebUIInfoSingleton::NotifyLogMessageListeners, timestamp, - message)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&WebUIInfoSingleton::NotifyLogMessageListeners, + timestamp, message)); } void WebUIInfoSingleton::ClearLogMessages() {
diff --git a/components/search/BUILD.gn b/components/search/BUILD.gn index b3896ba..2baff9f 100644 --- a/components/search/BUILD.gn +++ b/components/search/BUILD.gn
@@ -10,7 +10,7 @@ deps = [ "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/search_engines", "//url", ]
diff --git a/components/search_engines/BUILD.gn b/components/search_engines/BUILD.gn index f0e10cf..caf5ebb 100644 --- a/components/search_engines/BUILD.gn +++ b/components/search_engines/BUILD.gn
@@ -49,7 +49,7 @@ public_deps = [ ":search_engine_type", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/keyed_service/core", "//components/prefs", "//components/sync", @@ -144,7 +144,7 @@ "//base", "//base/test:test_support", "//components/country_codes", - "//components/google/core/browser", + "//components/google/core/common", "//components/pref_registry:pref_registry", "//components/prefs", "//components/sync:test_support",
diff --git a/components/search_engines/search_terms_data.cc b/components/search_engines/search_terms_data.cc index 1bd615e..441fb9e1 100644 --- a/components/search_engines/search_terms_data.cc +++ b/components/search_engines/search_terms_data.cc
@@ -5,7 +5,7 @@ #include "components/search_engines/search_terms_data.h" #include "base/logging.h" -#include "components/google/core/browser/google_url_tracker.h" +#include "components/google/core/common/google_util.h" #include "url/gurl.h" SearchTermsData::SearchTermsData() { @@ -15,7 +15,7 @@ } std::string SearchTermsData::GoogleBaseURLValue() const { - return GoogleURLTracker::kDefaultGoogleHomepage; + return google_util::kGoogleHomepageURL; } std::string SearchTermsData::GoogleBaseSuggestURLValue() const {
diff --git a/components/search_engines/template_url_service.cc b/components/search_engines/template_url_service.cc index 3537b67..60b0948 100644 --- a/components/search_engines/template_url_service.cc +++ b/components/search_engines/template_url_service.cc
@@ -282,14 +282,12 @@ std::unique_ptr<SearchTermsData> search_terms_data, const scoped_refptr<KeywordWebDataService>& web_data_service, std::unique_ptr<TemplateURLServiceClient> client, - GoogleURLTracker* google_url_tracker, rappor::RapporServiceImpl* rappor_service, const base::Closure& dsp_change_callback) : prefs_(prefs), search_terms_data_(std::move(search_terms_data)), web_data_service_(web_data_service), client_(std::move(client)), - google_url_tracker_(google_url_tracker), rappor_service_(rappor_service), dsp_change_callback_(dsp_change_callback), default_search_manager_( @@ -759,7 +757,6 @@ prefs_->SetString(prefs::kSyncedDefaultSearchProviderGUID, fallback_engine->sync_guid()); } - RequestGoogleURLTrackerServerCheckIfNecessary(); } else { // If the default search provider came from a user pref we would have been // notified of the new (fallback-provided) value in @@ -1386,13 +1383,6 @@ if (client_) client_->SetOwner(this); - // GoogleURLTracker is not created in tests. - if (google_url_tracker_) { - google_url_updated_subscription_ = - google_url_tracker_->RegisterCallback(base::Bind( - &TemplateURLService::GoogleBaseURLChanged, base::Unretained(this))); - } - if (prefs_) { pref_change_registrar_.Init(prefs_); pref_change_registrar_.Add( @@ -1434,10 +1424,6 @@ default_search_manager_.SetUserSelectedDefaultSearchEngine(data); } } - - // Request a server check for the correct Google URL if Google is the - // default search engine. - RequestGoogleURLTrackerServerCheckIfNecessary(); } TemplateURL* TemplateURLService::BestEngineForKeyword(TemplateURL* engine1, @@ -1804,71 +1790,6 @@ client_->AddKeywordGeneratedVisit(url); } -void TemplateURLService::RequestGoogleURLTrackerServerCheckIfNecessary() { - if (default_search_provider_ && - default_search_provider_->HasGoogleBaseURLs(search_terms_data()) && - google_url_tracker_) - google_url_tracker_->RequestServerCheck(); -} - -void TemplateURLService::GoogleBaseURLChanged() { - if (!loaded_) { - if (initial_default_search_provider_.get() && - initial_default_search_provider_->HasGoogleBaseURLs( - search_terms_data())) { - initial_default_search_provider_->InvalidateCachedValues(); - initial_default_search_provider_->ResetKeywordIfNecessary( - search_terms_data(), false); - } - return; - } - - // Prepare the queue of TemplateURLs which must be updated. We cannot directly - // iterate through template_urls_ while we're updating because sometimes we - // want to remove TemplateURL. - std::set<TemplateURL*> turls_to_update; - for (const auto& turl : template_urls_) - turls_to_update.insert(turl.get()); - - Scoper scoper(this); - - while (!turls_to_update.empty()) { - auto it = turls_to_update.begin(); - TemplateURL* turl = *it; - turls_to_update.erase(it); - if (turl->HasGoogleBaseURLs(search_terms_data())) { - TemplateURL updated_turl(turl->data()); - updated_turl.ResetKeywordIfNecessary(search_terms_data(), false); - KeywordToTURLAndMeaningfulLength::const_iterator existing_entry = - keyword_to_turl_and_length_.find(updated_turl.keyword()); - if (existing_entry != keyword_to_turl_and_length_.end()) { - TemplateURL* existing_turl = existing_entry->second.first; - if (existing_turl != turl) { - // The new autogenerated keyword conflicts with another TemplateURL. - // Overwrite it if it's replaceable; otherwise, leave |turl| using its - // current keyword. (This will not prevent |turl| from auto-updating - // the keyword in the future if the conflicting TemplateURL - // disappears.) Note that we must still update |turl| in this case, or - // the |provider_map_| will not be updated correctly. - if (CanReplace(existing_turl)) { - Remove(existing_turl); - // Remove |existing_url| from the queue we're iterating through. - // Perhaps there is no |existing_url| in this queue already if this - // cycle processed |existing_url| before |turl|. - turls_to_update.erase(existing_turl); - } else { - updated_turl.data_.SetKeyword(turl->keyword()); - } - } - } - // This will send the keyword change to sync. Note that other clients - // need to reset the keyword to an appropriate local value when this - // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData(). - Update(turl, updated_turl); - } - } -} - void TemplateURLService::ApplyDefaultSearchChange( const TemplateURLData* data, DefaultSearchManager::Source source) { @@ -1986,7 +1907,6 @@ bool changed = default_search_provider_ != previous_default_search_engine; if (changed) { model_mutated_notification_pending_ = true; - RequestGoogleURLTrackerServerCheckIfNecessary(); } return changed;
diff --git a/components/search_engines/template_url_service.h b/components/search_engines/template_url_service.h index 8c03c40f..ffaf93b 100644 --- a/components/search_engines/template_url_service.h +++ b/components/search_engines/template_url_service.h
@@ -21,7 +21,6 @@ #include "base/observer_list.h" #include "base/time/default_clock.h" #include "build/build_config.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/keyed_service/core/keyed_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/search_engines/default_search_manager.h" @@ -113,7 +112,6 @@ std::unique_ptr<SearchTermsData> search_terms_data, const scoped_refptr<KeywordWebDataService>& web_data_service, std::unique_ptr<TemplateURLServiceClient> client, - GoogleURLTracker* google_url_tracker, rappor::RapporServiceImpl* rappor_service, const base::RepeatingClosure& dsp_change_callback); // The following is for testing. @@ -605,14 +603,6 @@ // If necessary, generates a visit for the site http:// + t_url.keyword(). void AddTabToSearchVisit(const TemplateURL& t_url); - // Requests the Google URL tracker to check the server if necessary. - void RequestGoogleURLTrackerServerCheckIfNecessary(); - - // Invoked when the Google base URL has changed. Updates the mapping for all - // TemplateURLs that have a replacement term of {google:baseURL} or - // {google:baseSuggestURL}. - void GoogleBaseURLChanged(); - // Adds a new TemplateURL to this model. // // If |newly_adding| is false, we assume that this TemplateURL was already @@ -742,8 +732,6 @@ std::unique_ptr<TemplateURLServiceClient> client_; - GoogleURLTracker* google_url_tracker_ = nullptr; - // ---------- Metrics related members --------------------------------------- rappor::RapporServiceImpl* rappor_service_ = nullptr; @@ -850,9 +838,6 @@ // Helper class to manage the default search engine. DefaultSearchManager default_search_manager_; - std::unique_ptr<GoogleURLTracker::Subscription> - google_url_updated_subscription_; - // This tracks how many Scoper handles exist. When the number of handles drops // to zero, a notification is made to observers if // |model_mutated_notification_pending_| is true.
diff --git a/components/search_provider_logos/logo_service_impl.cc b/components/search_provider_logos/logo_service_impl.cc index b3daa5e3..2bc599e 100644 --- a/components/search_provider_logos/logo_service_impl.cc +++ b/components/search_provider_logos/logo_service_impl.cc
@@ -192,8 +192,9 @@ image_decoder_(std::move(image_decoder)), is_idle_(true), is_cached_logo_valid_(false), - cache_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + cache_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), logo_cache_(new LogoCache(cache_directory_), base::OnTaskRunnerDeleter(cache_task_runner_)) { @@ -719,9 +720,9 @@ bool from_http_cache = !source->ResponseInfo()->network_accessed; bool* parsing_failed = new bool(false); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(parse_logo_response_func_, std::move(response), response_time, parsing_failed),
diff --git a/components/security_interstitials/core/BUILD.gn b/components/security_interstitials/core/BUILD.gn index 8b0cf36..7b758549 100644 --- a/components/security_interstitials/core/BUILD.gn +++ b/components/security_interstitials/core/BUILD.gn
@@ -38,7 +38,7 @@ deps = [ "//base", "//base:i18n", - "//components/google/core/browser", + "//components/google/core/common", "//components/history/core/browser", "//components/metrics", "//components/prefs",
diff --git a/components/services/filesystem/directory_test_helper.cc b/components/services/filesystem/directory_test_helper.cc index 4427c5f..c04f04af 100644 --- a/components/services/filesystem/directory_test_helper.cc +++ b/components/services/filesystem/directory_test_helper.cc
@@ -44,8 +44,8 @@ }; DirectoryTestHelper::DirectoryTestHelper() - : blocking_state_( - base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})) {} + : blocking_state_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})) {} DirectoryTestHelper::~DirectoryTestHelper() = default;
diff --git a/components/services/font/public/cpp/font_service_thread.cc b/components/services/font/public/cpp/font_service_thread.cc index e93db6e..585ede8 100644 --- a/components/services/font/public/cpp/font_service_thread.cc +++ b/components/services/font/public/cpp/font_service_thread.cc
@@ -17,8 +17,9 @@ FontServiceThread::FontServiceThread(mojom::FontServicePtr font_service) : font_service_info_(font_service.PassInterface()), - task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, base::MayBlock()})) { + task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock()})) { task_runner_->PostTask(FROM_HERE, base::BindOnce(&FontServiceThread::Init, weak_factory_.GetWeakPtr())); }
diff --git a/components/services/heap_profiling/heap_profiling_service.cc b/components/services/heap_profiling/heap_profiling_service.cc index 8d86ba7..c970022 100644 --- a/components/services/heap_profiling/heap_profiling_service.cc +++ b/components/services/heap_profiling/heap_profiling_service.cc
@@ -33,8 +33,8 @@ // because the thread owned by ConnectionManager::Connection is doing // blocking Join during dectruction. scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, + base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::WithBaseSyncPrimitives()}, base::SingleThreadTaskRunnerThreadMode::DEDICATED); task_runner->PostTask(
diff --git a/components/services/heap_profiling/public/cpp/profiling_client.cc b/components/services/heap_profiling/public/cpp/profiling_client.cc index 2f0bf6f..251bb1c 100644 --- a/components/services/heap_profiling/public/cpp/profiling_client.cc +++ b/components/services/heap_profiling/public/cpp/profiling_client.cc
@@ -50,9 +50,9 @@ defined(OFFICIAL_BUILD) // On Android the unwinder initialization requires file reading before // initializing shim. So, post task on background thread. - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce([]() { bool can_unwind =
diff --git a/components/services/leveldb/env_mojo.cc b/components/services/leveldb/env_mojo.cc index 86bbf05..01561482 100644 --- a/components/services/leveldb/env_mojo.cc +++ b/components/services/leveldb/env_mojo.cc
@@ -517,10 +517,11 @@ } void MojoEnv::Schedule(void (*function)(void* arg), void* arg) { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::WithBaseSyncPrimitives(), - base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, - base::BindOnce(function, arg)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + base::BindOnce(function, arg)); } void MojoEnv::StartThread(void (*function)(void* arg), void* arg) {
diff --git a/components/services/leveldb/leveldb_service_unittest.cc b/components/services/leveldb/leveldb_service_unittest.cc index 58d7d7d..3450430c 100644 --- a/components/services/leveldb/leveldb_service_unittest.cc +++ b/components/services/leveldb/leveldb_service_unittest.cc
@@ -161,8 +161,9 @@ class LevelDBServiceTest : public testing::Test { public: LevelDBServiceTest() - : leveldb_service_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), + : leveldb_service_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), leveldb_receiver_(&leveldb_service_, leveldb_remote_.BindNewPipeAndPassReceiver()) {} ~LevelDBServiceTest() override = default;
diff --git a/components/services/leveldb/remote_iterator_unittest.cc b/components/services/leveldb/remote_iterator_unittest.cc index f79d664f..c7f7e1f2 100644 --- a/components/services/leveldb/remote_iterator_unittest.cc +++ b/components/services/leveldb/remote_iterator_unittest.cc
@@ -45,8 +45,9 @@ class RemoteIteratorTest : public testing::Test { public: RemoteIteratorTest() - : leveldb_service_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), + : leveldb_service_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), leveldb_receiver_(&leveldb_service_, leveldb_remote_.BindNewPipeAndPassReceiver()) {} ~RemoteIteratorTest() override = default;
diff --git a/components/services/patch/in_process_file_patcher.cc b/components/services/patch/in_process_file_patcher.cc index 38e8190..ea9c5c7 100644 --- a/components/services/patch/in_process_file_patcher.cc +++ b/components/services/patch/in_process_file_patcher.cc
@@ -25,8 +25,8 @@ mojo::PendingRemote<mojom::FilePatcher> LaunchInProcessFilePatcher() { mojo::PendingRemote<mojom::FilePatcher> remote; - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::WithBaseSyncPrimitives()}) + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives()}) ->PostTask(FROM_HERE, base::BindOnce(&BindInProcessFilePatcher, remote.InitWithNewPipeAndPassReceiver()));
diff --git a/components/services/quarantine/quarantine_impl.cc b/components/services/quarantine/quarantine_impl.cc index ffe9c2f..89ef64999 100644 --- a/components/services/quarantine/quarantine_impl.cc +++ b/components/services/quarantine/quarantine_impl.cc
@@ -28,13 +28,13 @@ #if defined(OS_WIN) scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner() { - return base::CreateCOMSTATaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + return base::CreateCOMSTATaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}); } #else // OS_WIN scoped_refptr<base::TaskRunner> GetTaskRunner() { - return base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + return base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}); } #endif // OS_WIN
diff --git a/components/services/unzip/in_process_unzipper.cc b/components/services/unzip/in_process_unzipper.cc index 88784b4..0ca9b5b 100644 --- a/components/services/unzip/in_process_unzipper.cc +++ b/components/services/unzip/in_process_unzipper.cc
@@ -24,8 +24,8 @@ mojo::PendingRemote<mojom::Unzipper> LaunchInProcessUnzipper() { mojo::PendingRemote<mojom::Unzipper> remote; - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::WithBaseSyncPrimitives()}) + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives()}) ->PostTask(FROM_HERE, base::BindOnce(&BindInProcessUnzipper, remote.InitWithNewPipeAndPassReceiver()));
diff --git a/components/services/unzip/public/cpp/unzip.cc b/components/services/unzip/public/cpp/unzip.cc index 70884df..5e8ffb3 100644 --- a/components/services/unzip/public/cpp/unzip.cc +++ b/components/services/unzip/public/cpp/unzip.cc
@@ -160,9 +160,9 @@ DCHECK(!result_callback.is_null()); scoped_refptr<base::SequencedTaskRunner> background_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, + base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); background_task_runner->PostTask( FROM_HERE, base::BindOnce(&DoUnzipWithFilter, std::move(unzipper), zip_path,
diff --git a/components/sessions/core/base_session_service.cc b/components/sessions/core/base_session_service.cc index 9c03e60..bbf50c6 100644 --- a/components/sessions/core/base_session_service.cc +++ b/components/sessions/core/base_session_service.cc
@@ -55,8 +55,9 @@ : pending_reset_(false), commands_since_reset_(0), delegate_(delegate), - backend_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) { + backend_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) { backend_ = new SessionBackend(type, path); DCHECK(backend_); }
diff --git a/components/signin/core/browser/BUILD.gn b/components/signin/core/browser/BUILD.gn index 4221020a..df01214e 100644 --- a/components/signin/core/browser/BUILD.gn +++ b/components/signin/core/browser/BUILD.gn
@@ -69,7 +69,7 @@ ] deps = [ "//base:i18n", - "//components/google/core/browser", + "//components/google/core/common", "//components/metrics", "//components/os_crypt", "//components/signin/public/identity_manager",
diff --git a/components/signin/internal/identity_manager/account_tracker_service.cc b/components/signin/internal/identity_manager/account_tracker_service.cc index 710345b7..fa319f9 100644 --- a/components/signin/internal/identity_manager/account_tracker_service.cc +++ b/components/signin/internal/identity_manager/account_tracker_service.cc
@@ -124,8 +124,8 @@ if (!user_data_dir_.empty()) { // |image_storage_task_runner_| is a sequenced runner because we want to // avoid read and write operations to the same file at the same time. - image_storage_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + image_storage_task_runner_ = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); LoadAccountImagesFromDisk(); }
diff --git a/components/signin/ios/browser/BUILD.gn b/components/signin/ios/browser/BUILD.gn index 7a6fc1a..095aa04f 100644 --- a/components/signin/ios/browser/BUILD.gn +++ b/components/signin/ios/browser/BUILD.gn
@@ -14,7 +14,7 @@ deps = [ "//components/content_settings/core/browser", - "//components/google/core/browser", + "//components/google/core/common", "//components/prefs", "//components/signin/core/browser", "//components/signin/public/base",
diff --git a/components/spellcheck/browser/spellcheck_platform_win.cc b/components/spellcheck/browser/spellcheck_platform_win.cc index 49cdd6d..6562be7 100644 --- a/components/spellcheck/browser/spellcheck_platform_win.cc +++ b/components/spellcheck/browser/spellcheck_platform_win.cc
@@ -451,7 +451,8 @@ static base::NoDestructor<std::unique_ptr<WindowsSpellChecker>> win_spell_checker(std::make_unique<WindowsSpellChecker>( base::ThreadTaskRunnerHandle::Get(), - base::CreateCOMSTATaskRunnerWithTraits({base::MayBlock()}))); + base::CreateCOMSTATaskRunner( + {base::ThreadPool(), base::MayBlock()}))); return *win_spell_checker; } } // anonymous namespace
diff --git a/components/storage_monitor/image_capture_device.mm b/components/storage_monitor/image_capture_device.mm index d0fea027..3b2b0207e 100644 --- a/components/storage_monitor/image_capture_device.mm +++ b/components/storage_monitor/image_capture_device.mm
@@ -220,9 +220,9 @@ // Shared result value from file-copy closure to tell-listener closure. // This is worth blocking shutdown, as otherwise a file that has been // downloaded will be incorrectly named. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::Bind(&storage_monitor::RenameFile, savedPath, saveAsPath), base::Bind(&storage_monitor::ReturnRenameResultToListener, listener_,
diff --git a/components/storage_monitor/media_storage_util.cc b/components/storage_monitor/media_storage_util.cc index ee054d8..7b3f5b1 100644 --- a/components/storage_monitor/media_storage_util.cc +++ b/components/storage_monitor/media_storage_util.cc
@@ -101,9 +101,9 @@ void MediaStorageUtil::FilterAttachedDevices(DeviceIdSet* devices, const base::Closure& done) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, - {base::TaskPriority::BEST_EFFORT, base::MayBlock(), + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&FilterAttachedDevicesOnBackgroundSequence, devices), done);
diff --git a/components/storage_monitor/media_storage_util_unittest.cc b/components/storage_monitor/media_storage_util_unittest.cc index 142c54c7..981d03a1 100644 --- a/components/storage_monitor/media_storage_util_unittest.cc +++ b/components/storage_monitor/media_storage_util_unittest.cc
@@ -81,8 +81,9 @@ // Create a dummy mount point with DCIM Directory. base::FilePath mount_point(CreateMountPoint(true)); ASSERT_FALSE(mount_point.empty()); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&MediaStorageUtilTest::CheckDCIMDeviceType, base::Unretained(this), mount_point)); RunUntilIdle(); @@ -94,8 +95,9 @@ // Create a dummy mount point without DCIM Directory. base::FilePath mount_point(CreateMountPoint(false)); ASSERT_FALSE(mount_point.empty()); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&MediaStorageUtilTest::CheckNonDCIMDeviceType, base::Unretained(this), mount_point)); RunUntilIdle();
diff --git a/components/storage_monitor/portable_device_watcher_win.cc b/components/storage_monitor/portable_device_watcher_win.cc index 2d3b9b0..9936f41 100644 --- a/components/storage_monitor/portable_device_watcher_win.cc +++ b/components/storage_monitor/portable_device_watcher_win.cc
@@ -507,8 +507,8 @@ void PortableDeviceWatcherWin::Init(HWND hwnd) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); notifications_ = RegisterPortableDeviceNotification(hwnd); - media_task_runner_ = base::CreateCOMSTATaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + media_task_runner_ = base::CreateCOMSTATaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); EnumerateAttachedDevices(); }
diff --git a/components/storage_monitor/storage_monitor_chromeos.cc b/components/storage_monitor/storage_monitor_chromeos.cc index a7705cb..f2d6922 100644 --- a/components/storage_monitor/storage_monitor_chromeos.cc +++ b/components/storage_monitor/storage_monitor_chromeos.cc
@@ -141,8 +141,8 @@ } scoped_refptr<base::SequencedTaskRunner> blocking_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}); for (const auto& it : DiskMountManager::GetInstance()->mount_points()) { base::PostTaskAndReplyWithResult( @@ -215,8 +215,10 @@ return; } - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}, base::Bind(&MediaStorageUtil::HasDcim, base::FilePath(mount_info.mount_path)), base::Bind(&StorageMonitorCros::AddMountedPath,
diff --git a/components/storage_monitor/storage_monitor_linux.cc b/components/storage_monitor/storage_monitor_linux.cc index 3a0155c..f2b288e 100644 --- a/components/storage_monitor/storage_monitor_linux.cc +++ b/components/storage_monitor/storage_monitor_linux.cc
@@ -245,8 +245,9 @@ StorageMonitorLinux::StorageMonitorLinux(const base::FilePath& path) : mtab_path_(path), get_device_info_callback_(base::Bind(&GetDeviceInfo)), - mtab_watcher_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT})) {} + mtab_watcher_task_runner_( + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT})) {} StorageMonitorLinux::~StorageMonitorLinux() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -326,8 +327,9 @@ receiver()->ProcessDetach(device_id); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::Bind(&EjectPathOnBlockingTaskRunner, path, device), callback); } @@ -399,8 +401,8 @@ // Check new mtab entries against existing ones. scoped_refptr<base::SequencedTaskRunner> mounting_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}); for (auto new_iter = new_mtab.begin(); new_iter != new_mtab.end(); ++new_iter) { const base::FilePath& mount_point = new_iter->first;
diff --git a/components/storage_monitor/storage_monitor_mac.mm b/components/storage_monitor/storage_monitor_mac.mm index a57b212..1f1745a2 100644 --- a/components/storage_monitor/storage_monitor_mac.mm +++ b/components/storage_monitor/storage_monitor_mac.mm
@@ -306,8 +306,8 @@ options->bsd_name = bsd_name; options->callback = callback; options->disk = std::move(disk); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(EjectDisk, options)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(EjectDisk, options)); } // static @@ -339,8 +339,9 @@ base::ScopedCFTypeRef<CFDictionaryRef> dict(DADiskCopyDescription(disk)); std::string* bsd_name = new std::string; - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&BuildStorageInfo, dict, bsd_name), base::BindOnce(&StorageMonitorMac::UpdateDisk, AsWeakPtr(), update_type, base::Owned(bsd_name)));
diff --git a/components/storage_monitor/storage_monitor_mac_unittest.mm b/components/storage_monitor/storage_monitor_mac_unittest.mm index eb6e340..f78976d 100644 --- a/components/storage_monitor/storage_monitor_mac_unittest.mm +++ b/components/storage_monitor/storage_monitor_mac_unittest.mm
@@ -60,7 +60,7 @@ } void UpdateDisk(StorageInfo info, StorageMonitorMac::UpdateType update_type) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&StorageMonitorMac::UpdateDisk, base::Unretained(monitor_.get()), update_type,
diff --git a/components/storage_monitor/volume_mount_watcher_win.cc b/components/storage_monitor/volume_mount_watcher_win.cc index 50919ff5..1e4915cd 100644 --- a/components/storage_monitor/volume_mount_watcher_win.cc +++ b/components/storage_monitor/volume_mount_watcher_win.cc
@@ -225,9 +225,8 @@ // at not-just-drive-letter paths. if (drive_letter < L'A' || drive_letter > L'Z' || device != device.DirName()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); return; } base::SStringPrintf(&volume_name, L"\\\\.\\%lc:", drive_letter); @@ -237,9 +236,8 @@ nullptr, OPEN_EXISTING, 0, nullptr)); if (!volume_handle.IsValid()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); return; } @@ -267,9 +265,8 @@ return; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_IN_USE)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_IN_USE)); return; } @@ -285,9 +282,8 @@ if (!dismounted) { DeviceIoControl(volume_handle.Get(), FSCTL_UNLOCK_VOLUME, nullptr, 0, nullptr, 0, &bytes_returned, nullptr); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_OK)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_OK)); return; } @@ -297,30 +293,29 @@ if (!DeviceIoControl(volume_handle.Get(), IOCTL_STORAGE_MEDIA_REMOVAL, &pmr_buffer, sizeof(PREVENT_MEDIA_REMOVAL), nullptr, 0, &bytes_returned, nullptr)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); return; } // Physically eject or soft-eject the device. if (!DeviceIoControl(volume_handle.Get(), IOCTL_STORAGE_EJECT_MEDIA, nullptr, 0, nullptr, 0, &bytes_returned, nullptr)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_FAILURE)); return; } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, StorageMonitor::EJECT_OK)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, StorageMonitor::EJECT_OK)); } } // namespace VolumeMountWatcherWin::VolumeMountWatcherWin() - : device_info_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT, + : device_info_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), notifications_(nullptr), weak_factory_(this) {} @@ -376,14 +371,13 @@ base::WeakPtr<VolumeMountWatcherWin> volume_watcher) { StorageInfo info; if (!get_device_details_callback.Run(device_path, &info)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&VolumeMountWatcherWin::DeviceCheckComplete, - volume_watcher, device_path)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&VolumeMountWatcherWin::DeviceCheckComplete, + volume_watcher, device_path)); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&VolumeMountWatcherWin::HandleDeviceAttachEventOnUIThread, volume_watcher, device_path, info));
diff --git a/components/subresource_filter/content/browser/fake_safe_browsing_database_manager.cc b/components/subresource_filter/content/browser/fake_safe_browsing_database_manager.cc index 3a24304..f37e2ff 100644 --- a/components/subresource_filter/content/browser/fake_safe_browsing_database_manager.cc +++ b/components/subresource_filter/content/browser/fake_safe_browsing_database_manager.cc
@@ -57,12 +57,11 @@ checks_.insert(client); if (simulate_timeout_) return false; - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&FakeSafeBrowsingDatabaseManager:: - OnCheckUrlForSubresourceFilterComplete, - weak_factory_.GetWeakPtr(), base::Unretained(client), - url)); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&FakeSafeBrowsingDatabaseManager:: + OnCheckUrlForSubresourceFilterComplete, + weak_factory_.GetWeakPtr(), + base::Unretained(client), url)); return false; }
diff --git a/components/subresource_filter/content/browser/ruleset_publisher_impl.cc b/components/subresource_filter/content/browser/ruleset_publisher_impl.cc index b158be8a..dafdb86 100644 --- a/components/subresource_filter/content/browser/ruleset_publisher_impl.cc +++ b/components/subresource_filter/content/browser/ruleset_publisher_impl.cc
@@ -46,9 +46,10 @@ void CloseFileOnFileThread(base::File* file) { if (!file->IsValid()) return; - base::PostTaskWithTraits(FROM_HERE, - {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, - base::BindOnce(&CloseFile, std::move(*file))); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::BindOnce(&CloseFile, std::move(*file))); } } // namespace @@ -59,7 +60,7 @@ : ruleset_service_(ruleset_service), ruleset_dealer_(std::make_unique<VerifiedRulesetDealer::Handle>( std::move(blocking_task_runner))) { - best_effort_task_runner_ = base::CreateSingleThreadTaskRunnerWithTraits( + best_effort_task_runner_ = base::CreateSingleThreadTaskRunner( {content::BrowserThread::UI, base::TaskPriority::BEST_EFFORT}); DCHECK(best_effort_task_runner_->BelongsToCurrentThread()); // Must rely on notifications as RenderProcessHostObserver::RenderProcessReady
diff --git a/components/suggestions/BUILD.gn b/components/suggestions/BUILD.gn index fd86688c..fcb9c81 100644 --- a/components/suggestions/BUILD.gn +++ b/components/suggestions/BUILD.gn
@@ -27,7 +27,7 @@ "//url", ] deps = [ - "//components/google/core/browser", + "//components/google/core/common", "//components/keyed_service/core", "//components/pref_registry", "//components/signin/public/identity_manager",
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 7d4538d..70b835d 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -563,6 +563,7 @@ "base/sync_prefs_unittest.cc", "base/system_encryptor_unittest.cc", "base/unique_position_unittest.cc", + "base/user_demographics_unittest.cc", "base/weak_handle_unittest.cc", "driver/about_sync_util_unittest.cc", "driver/async_directory_type_controller_unittest.cc",
diff --git a/components/sync/base/BUILD.gn b/components/sync/base/BUILD.gn index 8c55712..cd73fed 100644 --- a/components/sync/base/BUILD.gn +++ b/components/sync/base/BUILD.gn
@@ -61,6 +61,7 @@ "unrecoverable_error_handler.h", "unrecoverable_error_info.cc", "unrecoverable_error_info.h", + "user_demographics.cc", "user_demographics.h", "user_selectable_type.cc", "user_selectable_type.h",
diff --git a/components/sync/base/sync_prefs.cc b/components/sync/base/sync_prefs.cc index 5ba3d8c..0ad1c39 100644 --- a/components/sync/base/sync_prefs.cc +++ b/components/sync/base/sync_prefs.cc
@@ -4,6 +4,7 @@ #include "components/sync/base/sync_prefs.h" +#include <utility> #include <vector> #include "base/base64.h" @@ -604,12 +605,18 @@ return local_sync_enabled_; } -base::Optional<UserDemographics> SyncPrefs::GetUserDemographics( - base::Time now) { +UserDemographicsResult SyncPrefs::GetUserDemographics(base::Time now) { // Verify that the now time is available. There are situations where the now // time cannot be provided. - if (now.is_null()) - return base::nullopt; + if (now.is_null()) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kCannotGetTime); + } + + // Get user demographics. Only one error status code should be used to + // represent the case where demographics are invalid, see doc of + // UserDemographicsStatus in components/sync/base/user_demographics.h for more + // details. // Get the pref that contains the demographic info. const base::DictionaryValue* demographics = @@ -618,26 +625,32 @@ // Get the user's birth year. base::Optional<int> birth_year = GetUserBirthYear(demographics); - if (!birth_year.has_value()) - return base::nullopt; + if (!birth_year.has_value()) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kIneligibleDemographicsData); + } // Get the user's gender. base::Optional<metrics::UserDemographicsProto_Gender> gender = GetUserGender(demographics); - if (!gender.has_value()) - return base::nullopt; + if (!gender.has_value()) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kIneligibleDemographicsData); + } // Get the offset and do one last check that demographics are allowed. int offset = GetBirthYearOffset(pref_service_); - if (!CanProvideDemographics(now, *birth_year, offset)) - return base::nullopt; + if (!CanProvideDemographics(now, *birth_year, offset)) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kIneligibleDemographicsData); + } // Set gender and offset birth year in demographics. UserDemographics user_demographics; user_demographics.gender = *gender; user_demographics.birth_year = *birth_year + offset; - return user_demographics; + return UserDemographicsResult::ForValue(std::move(user_demographics)); } void MigrateSessionsToProxyTabsPrefs(PrefService* pref_service) {
diff --git a/components/sync/base/sync_prefs.h b/components/sync/base/sync_prefs.h index 20ba54d..1712e94 100644 --- a/components/sync/base/sync_prefs.h +++ b/components/sync/base/sync_prefs.h
@@ -15,7 +15,6 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" -#include "base/optional.h" #include "base/sequence_checker.h" #include "base/time/time.h" #include "build/build_config.h" @@ -174,9 +173,9 @@ // Gets the local sync backend enabled state. bool IsLocalSyncEnabled() const; - // Gets user demographics. Returns an empty optional if not all demographics - // are available. - base::Optional<UserDemographics> GetUserDemographics(base::Time now); + // Gets user demographics. Returns an error status with an empty value when + // demographics cannot be provided. + UserDemographicsResult GetUserDemographics(base::Time now); private: static void RegisterTypeSelectedPref(user_prefs::PrefRegistrySyncable* prefs,
diff --git a/components/sync/base/sync_prefs_unittest.cc b/components/sync/base/sync_prefs_unittest.cc index 427be733..e704bf9 100644 --- a/components/sync/base/sync_prefs_unittest.cc +++ b/components/sync/base/sync_prefs_unittest.cc
@@ -7,7 +7,7 @@ #include <memory> #include "base/command_line.h" -#include "base/optional.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "components/prefs/pref_notifier_impl.h" @@ -164,12 +164,12 @@ int provided_birth_year; { - base::Optional<UserDemographics> demographics = + UserDemographicsResult demographics_result = sync_prefs_->GetUserDemographics(GetNowTime()); - ASSERT_TRUE(demographics.has_value()); - EXPECT_EQ(user_demographics_gender, demographics->gender); + ASSERT_TRUE(demographics_result.IsSuccess()); + EXPECT_EQ(user_demographics_gender, demographics_result.value().gender); // Verify that the provided birth year is within the range. - provided_birth_year = demographics->birth_year; + provided_birth_year = demographics_result.value().birth_year; int delta = provided_birth_year - user_demographics_birth_year; EXPECT_LE(delta, kUserDemographicsBirthYearNoiseOffsetRange); EXPECT_GE(delta, -kUserDemographicsBirthYearNoiseOffsetRange); @@ -180,16 +180,16 @@ { ASSERT_TRUE( pref_service_.HasPrefPath(prefs::kSyncDemographicsBirthYearOffset)); - base::Optional<UserDemographics> demographics = + UserDemographicsResult demographics_result = sync_prefs_->GetUserDemographics(GetNowTime()); - ASSERT_TRUE(demographics.has_value()); - EXPECT_EQ(provided_birth_year, demographics->birth_year); + ASSERT_TRUE(demographics_result.IsSuccess()); + EXPECT_EQ(provided_birth_year, demographics_result.value().birth_year); } } TEST_F(SyncPrefsTest, ReadAndClearUserDemographicPreferences) { // Verify demographic prefs are not available when there is nothing set. - ASSERT_FALSE(sync_prefs_->GetUserDemographics(GetNowTime()).has_value()); + ASSERT_FALSE(sync_prefs_->GetUserDemographics(GetNowTime()).IsSuccess()); // Set demographic prefs directly from the pref service interface because // demographic prefs will only be set on the server-side. The SyncPrefs @@ -201,9 +201,9 @@ // Verify that demographics are provided. { - base::Optional<UserDemographics> demographics = + UserDemographicsResult demographics_result = sync_prefs_->GetUserDemographics(GetNowTime()); - ASSERT_TRUE(demographics.has_value()); + ASSERT_TRUE(demographics_result.IsSuccess()); } sync_prefs_->ClearPreferences(); @@ -213,7 +213,7 @@ // syncing, causing these prefs to be recreated, we don't want them to start // reporting a different randomized birth year as this could narrow down or // even reveal their true birth year. - EXPECT_FALSE(sync_prefs_->GetUserDemographics(GetNowTime()).has_value()); + EXPECT_FALSE(sync_prefs_->GetUserDemographics(GetNowTime()).IsSuccess()); EXPECT_FALSE(pref_service_.HasPrefPath(prefs::kSyncDemographics)); EXPECT_TRUE( pref_service_.HasPrefPath(prefs::kSyncDemographicsBirthYearOffset)); @@ -487,9 +487,8 @@ metrics::UserDemographicsProto_Gender gender = kUserDemographicGenderDefaultEnumValue; - // Whether SyncPrefs::GetUserDemographics should return non-empty - // UserDemographics. - bool should_return_demographics = false; + // Status of the retrieval of demographics. + UserDemographicsStatus status = UserDemographicsStatus::kMaxValue; }; // Extend SyncPrefsTest fixture for parameterized tests on demographics. @@ -508,15 +507,16 @@ param.birth_year_offset); // Verify provided demographics for the different parameterized test cases. - base::Optional<UserDemographics> demographics = + UserDemographicsResult demographics_result = sync_prefs_->GetUserDemographics(GetNowTime()); - if (param.should_return_demographics) { - ASSERT_TRUE(demographics.has_value()); + if (param.status == UserDemographicsStatus::kSuccess) { + ASSERT_TRUE(demographics_result.IsSuccess()); EXPECT_EQ(param.birth_year + param.birth_year_offset, - demographics->birth_year); - EXPECT_EQ(param.gender, demographics->gender); + demographics_result.value().birth_year); + EXPECT_EQ(param.gender, demographics_result.value().gender); } else { - EXPECT_FALSE(demographics.has_value()); + ASSERT_FALSE(demographics_result.IsSuccess()); + EXPECT_EQ(param.status, demographics_result.status()); } } @@ -534,21 +534,21 @@ /*birth_year=*/1997, /*birth_year_offset=*/2, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/false}, + /*status=*/UserDemographicsStatus::kIneligibleDemographicsData}, // Test where birth year should not be provided because |birth_year| - 2 // > 1998. DemographicsTestParam{ /*birth_year=*/2001, /*birth_year_offset=*/-2, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/false}, + /*status=*/UserDemographicsStatus::kIneligibleDemographicsData}, // Test where birth year should not be provided because age of user is // |kUserDemographicsMaxAge| + 1, which is over the max age. DemographicsTestParam{ /*birth_year=*/1933, /*birth_year_offset=*/0, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/false}, + /*status=*/UserDemographicsStatus::kIneligibleDemographicsData}, // Test where gender should not be provided because it has a low // population that can have their privacy compromised because of high // entropy. @@ -556,49 +556,49 @@ /*birth_year=*/1986, /*birth_year_offset=*/0, /*gender=*/metrics::UserDemographicsProto::GENDER_UNKNOWN_OR_OTHER, - /*should_return_demographics=*/false}, + /*status=*/UserDemographicsStatus::kIneligibleDemographicsData}, // Test where birth year can be provided because |birth_year| + 2 == // 1998. DemographicsTestParam{ /*birth_year=*/1996, /*birth_year_offset=*/2, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/true}, + /*status=*/UserDemographicsStatus::kSuccess}, // Test where birth year can be provided because |birth_year| - 2 == // 1998. DemographicsTestParam{ /*birth_year=*/2000, /*birth_year_offset=*/-2, /*gender=*/metrics::UserDemographicsProto::GENDER_MALE, - /*should_return_demographics=*/true}, + /*status=*/UserDemographicsStatus::kSuccess}, // Test where birth year can be provided because |birth_year| + 2 < // 1998. DemographicsTestParam{ /*birth_year=*/1995, /*birth_year_offset=*/2, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/true}, + /*status=*/UserDemographicsStatus::kSuccess}, // Test where birth year can be provided because |birth_year| - 2 < // 1998. DemographicsTestParam{ /*birth_year=*/1999, /*birth_year_offset=*/-2, /*gender=*/metrics::UserDemographicsProto::GENDER_MALE, - /*should_return_demographics=*/true}, + /*status=*/UserDemographicsStatus::kSuccess}, // Test where gender can be provided because it is part of a large // population with a low entropy. DemographicsTestParam{ /*birth_year=*/1986, /*birth_year_offset=*/0, /*gender=*/metrics::UserDemographicsProto::GENDER_FEMALE, - /*should_return_demographics=*/true}, + /*status=*/UserDemographicsStatus::kSuccess}, // Test where gender can be provided because it is part of a large // population with a low entropy. DemographicsTestParam{ /*birth_year=*/1986, /*birth_year_offset=*/0, /*gender=*/metrics::UserDemographicsProto::GENDER_MALE, - /*should_return_demographics=*/true})); + /*status=*/UserDemographicsStatus::kSuccess})); } // namespace
diff --git a/components/sync/base/user_demographics.cc b/components/sync/base/user_demographics.cc new file mode 100644 index 0000000..080f817 --- /dev/null +++ b/components/sync/base/user_demographics.cc
@@ -0,0 +1,47 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/sync/base/user_demographics.h" + +#include <utility> + +#include "base/metrics/histogram_macros.h" + +namespace syncer { + +void LogUserDemographicsStatus(UserDemographicsStatus status) { + UMA_HISTOGRAM_ENUMERATION("UMA.UserDemographics.Status", status); +} + +// static +UserDemographicsResult UserDemographicsResult::ForValue( + UserDemographics value) { + return UserDemographicsResult(std::move(value), + UserDemographicsStatus::kSuccess); +} + +// static +UserDemographicsResult UserDemographicsResult::ForStatus( + UserDemographicsStatus status) { + DCHECK(status != UserDemographicsStatus::kSuccess); + return UserDemographicsResult(UserDemographics(), status); +} + +bool UserDemographicsResult::IsSuccess() const { + return status_ == UserDemographicsStatus::kSuccess; +} + +UserDemographicsStatus UserDemographicsResult::status() const { + return status_; +} + +const UserDemographics& UserDemographicsResult::value() const { + return value_; +} + +UserDemographicsResult::UserDemographicsResult(UserDemographics value, + UserDemographicsStatus status) + : value_(std::move(value)), status_(status) {} + +} // namespace syncer
diff --git a/components/sync/base/user_demographics.h b/components/sync/base/user_demographics.h index 73ef0b7e..496247b8 100644 --- a/components/sync/base/user_demographics.h +++ b/components/sync/base/user_demographics.h
@@ -43,6 +43,67 @@ metrics::UserDemographicsProto::Gender_MIN; }; +// Represents the status of providing user demographics that is logged to UMA. +// Entries of the enum should not be renumbered and numeric values should never +// be reused. Please keep in sync with "UserDemographicsStatus" in +// src/tools/metrics/histograms/enums.xml. There should only be one entry +// representing demographic data that is ineligible to be provided. A finer +// grained division of kIneligibleDemographicsData (e.g., INVALID_BIRTH_YEAR) +// might help inferring categories of demographics that should not be exposed to +// protect privacy. +enum class UserDemographicsStatus { + // Could get user demographics. + kSuccess = 0, + // Sync is not enabled. + kSyncNotEnabled = 1, + // Demographics are ineligible to be provided either because some of them + // don't + // exist (missing data) or some of them are not eligible to be provided. + kIneligibleDemographicsData = 2, + // Could not get the time needed to compute the user's age. + kCannotGetTime = 3, + // There is more than one Profile for the Chrome browser. This entry is used + // by the metrics::DemographicMetricsProvider client. + kMoreThanOneProfile = 4, + // There is no sync service available for the loaded Profile. This entry is + // used by the metrics::DemographicMetricsProvider client. + kNoSyncService = 5, + // Upper boundary of the enum that is needed for the histogram. + kMaxValue = kNoSyncService +}; + +// Container and handler for data related to the retrieval of user demographics. +class UserDemographicsResult { + public: + // Builds a UserDemographicsResult that contains user demographics and has a + // UserDemographicsStatus::kSuccess status. + static UserDemographicsResult ForValue(UserDemographics value); + + // Build a UserDemographicsResult that does not have user demographics (only + // default values) and has a status other than + // UserDemographicsStatus::kSuccess. + static UserDemographicsResult ForStatus(UserDemographicsStatus status); + + // Determines whether demographics could be successfully retrieved. + bool IsSuccess() const; + + // Gets the status of the result. + UserDemographicsStatus status() const; + + // Gets the value of the result which will contain data when status() is + // UserDemographicsStatus::kSuccess. + const UserDemographics& value() const; + + private: + UserDemographicsResult(UserDemographics value, UserDemographicsStatus status); + + UserDemographics value_; + UserDemographicsStatus status_ = UserDemographicsStatus::kMaxValue; +}; + +// Log user demographic status in the histogram. +void LogUserDemographicsStatus(UserDemographicsStatus status); + } // namespace syncer #endif // COMPONENTS_SYNC_BASE_USER_DEMOGRAPHICS_H_
diff --git a/components/sync/base/user_demographics_unittest.cc b/components/sync/base/user_demographics_unittest.cc new file mode 100644 index 0000000..e8f665e --- /dev/null +++ b/components/sync/base/user_demographics_unittest.cc
@@ -0,0 +1,42 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/sync/base/user_demographics.h" + +#include <utility> + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/metrics_proto/user_demographics.pb.h" + +namespace syncer { + +TEST(UserDemographicsTest, UserDemographicsResult_ForValue) { + int user_birth_year = 1982; + metrics::UserDemographicsProto_Gender user_gender = + metrics::UserDemographicsProto::GENDER_MALE; + + UserDemographics user_demographics; + user_demographics.birth_year = user_birth_year; + user_demographics.gender = user_gender; + UserDemographicsResult user_demographics_result = + UserDemographicsResult::ForValue(std::move(user_demographics)); + + EXPECT_TRUE(user_demographics_result.IsSuccess()); + EXPECT_EQ(UserDemographicsStatus::kSuccess, + user_demographics_result.status()); + EXPECT_EQ(user_birth_year, user_demographics_result.value().birth_year); + EXPECT_EQ(user_gender, user_demographics_result.value().gender); +} + +TEST(UserDemographicsTest, UserDemographicsResult_ForStatus) { + UserDemographicsStatus error_status = + UserDemographicsStatus::kIneligibleDemographicsData; + UserDemographicsResult user_demographics_result = + UserDemographicsResult::ForStatus(error_status); + + EXPECT_FALSE(user_demographics_result.IsSuccess()); + EXPECT_EQ(error_status, user_demographics_result.status()); +} + +} // namespace syncer
diff --git a/components/sync/driver/fake_sync_service.cc b/components/sync/driver/fake_sync_service.cc index ec5bcf53..b34929a 100644 --- a/components/sync/driver/fake_sync_service.cc +++ b/components/sync/driver/fake_sync_service.cc
@@ -156,9 +156,9 @@ void FakeSyncService::SetInvalidationsForSessionsEnabled(bool enabled) {} -base::Optional<UserDemographics> FakeSyncService::GetUserDemographics( - base::Time now) { - return base::nullopt; +UserDemographicsResult FakeSyncService::GetUserDemographics(base::Time now) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kIneligibleDemographicsData); } void FakeSyncService::Shutdown() {}
diff --git a/components/sync/driver/fake_sync_service.h b/components/sync/driver/fake_sync_service.h index 036c4f6..92821c2 100644 --- a/components/sync/driver/fake_sync_service.h +++ b/components/sync/driver/fake_sync_service.h
@@ -65,7 +65,7 @@ const base::Callback<void(std::unique_ptr<base::ListValue>)>& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; - base::Optional<UserDemographics> GetUserDemographics(base::Time now) override; + UserDemographicsResult GetUserDemographics(base::Time now) override; // KeyedService implementation. void Shutdown() override;
diff --git a/components/sync/driver/mock_sync_service.h b/components/sync/driver/mock_sync_service.h index f22a32b..2c278525 100644 --- a/components/sync/driver/mock_sync_service.h +++ b/components/sync/driver/mock_sync_service.h
@@ -54,8 +54,7 @@ MOCK_METHOD1(TriggerRefresh, void(const ModelTypeSet& types)); MOCK_METHOD1(ReadyForStartChanged, void(syncer::ModelType type)); MOCK_METHOD1(SetInvalidationsForSessionsEnabled, void(bool enabled)); - MOCK_METHOD1(GetUserDemographics, - base::Optional<UserDemographics>(base::Time now)); + MOCK_METHOD1(GetUserDemographics, UserDemographicsResult(base::Time now)); MOCK_METHOD1(AddObserver, void(SyncServiceObserver* observer)); MOCK_METHOD1(RemoveObserver, void(SyncServiceObserver* observer));
diff --git a/components/sync/driver/profile_sync_service.cc b/components/sync/driver/profile_sync_service.cc index 9226002..6d071c3 100644 --- a/components/sync/driver/profile_sync_service.cc +++ b/components/sync/driver/profile_sync_service.cc
@@ -221,13 +221,6 @@ sync_prefs_.AddSyncPrefObserver(this); - // If sync is disallowed by policy, clean up. - if (HasDisableReason(DISABLE_REASON_ENTERPRISE_POLICY)) { - // Note that this won't actually clear data, since neither |engine_| nor - // |sync_thread_| exist at this point. Bug or feature? - StopImpl(CLEAR_DATA); - } - if (!IsLocalSyncEnabled()) { auth_manager_->RegisterForAuthNotifications(); for (auto* provider : invalidations_identity_providers_) { @@ -235,11 +228,13 @@ provider->SetActiveAccountId(GetAuthenticatedAccountInfo().account_id); } } + } - if (!IsSignedIn()) { - // Clean up in case of previous crash during signout. - StopImpl(CLEAR_DATA); - } + // If sync is disabled permanently, clean up old data that may be around (e.g. + // crash during signout). + if (HasDisableReason(DISABLE_REASON_ENTERPRISE_POLICY) || + HasDisableReason(DISABLE_REASON_NOT_SIGNED_IN)) { + StopImpl(CLEAR_DATA); } // Note: We need to record the initial state *after* calling @@ -423,6 +418,19 @@ startup_controller_->OnDataTypeRequestsSyncStartup(type); } +void ProfileSyncService::StartSyncThreadIfNeeded() { + if (sync_thread_) { + // Already started. + return; + } + + sync_thread_ = std::make_unique<base::Thread>("Chrome_SyncThread"); + base::Thread::Options options; + options.timer_slack = base::TIMER_SLACK_MAXIMUM; + bool success = sync_thread_->StartWithOptions(options); + DCHECK(success); +} + void ProfileSyncService::StartUpSlowEngineComponents() { DCHECK(IsEngineAllowedToStart()); @@ -435,13 +443,7 @@ last_actionable_error_ = SyncProtocolError(); } - if (!sync_thread_) { - sync_thread_ = std::make_unique<base::Thread>("Chrome_SyncThread"); - base::Thread::Options options; - options.timer_slack = base::TIMER_SLACK_MAXIMUM; - bool success = sync_thread_->StartWithOptions(options); - DCHECK(success); - } + StartSyncThreadIfNeeded(); SyncEngine::InitParams params; params.sync_task_runner = sync_thread_->task_runner(); @@ -467,18 +469,6 @@ } params.sync_manager_factory = std::make_unique<SyncManagerFactory>(network_connection_tracker_); - // The first time we start up the engine we want to ensure we have a clean - // directory, so delete any old one that might be there. - params.delete_sync_data_folder = !user_settings_->IsFirstSetupComplete(); - if (params.delete_sync_data_folder) { - // This looks questionable here but it mimics the old behavior of deleting - // the directory via Directory::DeleteDirectoryFiles(). One consecuence is - // that, for sync the transport users (without sync-the-feature enabled), - // the cache GUID and other fields are reset on every restart. - // TODO(crbug.com/923285): Reconsider the lifetime of the cache GUID and - // its persistence depending on StorageOption. - sync_prefs_.ClearDirectoryConsistencyPreferences(); - } params.enable_local_sync_backend = sync_prefs_.IsLocalSyncEnabled(); params.local_sync_backend_folder = sync_client_->GetLocalSyncBackendFolder(); params.restored_key_for_bootstrapping = @@ -533,12 +523,24 @@ void ProfileSyncService::ShutdownImpl(ShutdownReason reason) { if (!engine_) { - if (reason == ShutdownReason::DISABLE_SYNC && sync_thread_) { - // If the engine is already shut down when a DISABLE_SYNC happens, - // the data directory needs to be cleaned up here. - sync_thread_->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&syncable::Directory::DeleteDirectoryFiles, - sync_client_->GetSyncDataPath())); + // If the engine hasn't started or is already shut down when a DISABLE_SYNC + // happens, the data directory needs to be cleaned up here. + if (reason == ShutdownReason::DISABLE_SYNC) { + // Clearing the Directory via Directory::DeleteDirectoryFiles() requires + // the |sync_thread_| initialized. It also means there's IO involved which + // may we considerable overhead if triggered consistently upon browser + // startup (which is the case for certain codepaths such as the user being + // signed out). To avoid that, SyncPrefs is used to determine whether it's + // worth. + if (!sync_prefs_.GetCacheGuid().empty()) { + StartSyncThreadIfNeeded(); + } + if (sync_thread_) { + sync_thread_->task_runner()->PostTask( + FROM_HERE, + base::BindOnce(&syncable::Directory::DeleteDirectoryFiles, + sync_client_->GetSyncDataPath())); + } } return; } @@ -1670,13 +1672,14 @@ } } -base::Optional<UserDemographics> ProfileSyncService::GetUserDemographics( - base::Time now) { +UserDemographicsResult ProfileSyncService::GetUserDemographics(base::Time now) { // Do not provide demographics when sync is disabled or paused because user // demographics should only be provided when the other sync data can be // uploaded to the sync server. - if (!IsSyncFeatureEnabled() || auth_manager_->IsSyncPaused()) - return base::nullopt; + if (!IsSyncFeatureEnabled() || auth_manager_->IsSyncPaused()) { + return UserDemographicsResult::ForStatus( + UserDemographicsStatus::kSyncNotEnabled); + } return sync_prefs_.GetUserDemographics(now); }
diff --git a/components/sync/driver/profile_sync_service.h b/components/sync/driver/profile_sync_service.h index 8a0f5106..2e17895 100644 --- a/components/sync/driver/profile_sync_service.h +++ b/components/sync/driver/profile_sync_service.h
@@ -134,7 +134,7 @@ void TriggerRefresh(const ModelTypeSet& types) override; void ReadyForStartChanged(ModelType type) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; - base::Optional<UserDemographics> GetUserDemographics(base::Time now) override; + UserDemographicsResult GetUserDemographics(base::Time now) override; void AddObserver(SyncServiceObserver* observer) override; void RemoveObserver(SyncServiceObserver* observer) override; bool HasObserver(const SyncServiceObserver* observer) const override; @@ -331,6 +331,9 @@ void ClearUnrecoverableError(); + // Initializes and starts |sync_thread_|. + void StartSyncThreadIfNeeded(); + // Kicks off asynchronous initialization of the SyncEngine. void StartUpSlowEngineComponents();
diff --git a/components/sync/driver/profile_sync_service_unittest.cc b/components/sync/driver/profile_sync_service_unittest.cc index ac88c565..8ff4aa4 100644 --- a/components/sync/driver/profile_sync_service_unittest.cc +++ b/components/sync/driver/profile_sync_service_unittest.cc
@@ -11,7 +11,6 @@ #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" -#include "base/optional.h" #include "base/run_loop.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_feature_list.h" @@ -1288,12 +1287,12 @@ prefs()->SetInteger(prefs::kSyncDemographicsBirthYearOffset, birth_year_offset); - base::Optional<UserDemographics> user_demographics = + UserDemographicsResult user_demographics_result = service()->GetUserDemographics(GetNowTime()); - ASSERT_TRUE(user_demographics.has_value()); + ASSERT_TRUE(user_demographics_result.IsSuccess()); EXPECT_EQ(user_demographics_birth_year + birth_year_offset, - user_demographics->birth_year); - EXPECT_EQ(user_demographics_gender, user_demographics->gender); + user_demographics_result.value().birth_year); + EXPECT_EQ(user_demographics_gender, user_demographics_result.value().gender); } // Test whether sync service does not provide user demographics when sync is @@ -1317,7 +1316,7 @@ ASSERT_TRUE(HasGenderDemographic(prefs())); // Verify that we don't get demographics when sync is off. - EXPECT_FALSE(service()->GetUserDemographics(GetNowTime()).has_value()); + EXPECT_FALSE(service()->GetUserDemographics(GetNowTime()).IsSuccess()); } // Test whether sync service does not provide user demographics and does not @@ -1357,9 +1356,9 @@ // Verify that sync service does not provide demographics when it is // temporarily disabled. - base::Optional<UserDemographics> user_demographics = + UserDemographicsResult user_demographics_result = service()->GetUserDemographics(GetNowTime()); - EXPECT_FALSE(user_demographics.has_value()); + EXPECT_FALSE(user_demographics_result.IsSuccess()); // Verify that demographic prefs are not cleared. EXPECT_TRUE(HasBirthYearDemographic(prefs())); @@ -1404,9 +1403,9 @@ ASSERT_EQ(SyncService::DISABLE_REASON_NONE, service()->GetDisableReasons()); // Verify that sync service does not provide demographics when sync is paused. - base::Optional<UserDemographics> user_demographics = + UserDemographicsResult user_demographics_result = service()->GetUserDemographics(GetNowTime()); - EXPECT_FALSE(user_demographics.has_value()); + EXPECT_FALSE(user_demographics_result.IsSuccess()); // Verify that demographic prefs are not cleared. EXPECT_TRUE(HasBirthYearDemographic(prefs())); @@ -1451,9 +1450,9 @@ ASSERT_EQ(SyncService::DISABLE_REASON_PAUSED, service()->GetDisableReasons()); // Verify that sync service does not provide demographics when sync is paused. - base::Optional<UserDemographics> user_demographics = + UserDemographicsResult user_demographics_result = service()->GetUserDemographics(GetNowTime()); - EXPECT_FALSE(user_demographics.has_value()); + EXPECT_FALSE(user_demographics_result.IsSuccess()); // Verify that demographic prefs are not cleared. EXPECT_TRUE(HasBirthYearDemographic(prefs()));
diff --git a/components/sync/driver/sync_service.h b/components/sync/driver/sync_service.h index ec85f95..4cce95b 100644 --- a/components/sync/driver/sync_service.h +++ b/components/sync/driver/sync_service.h
@@ -12,7 +12,6 @@ #include "base/location.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" -#include "base/optional.h" #include "base/time/time.h" #include "components/keyed_service/core/keyed_service.h" #include "components/sync/base/model_type.h" @@ -351,11 +350,10 @@ // USER DEMOGRAPHICS ////////////////////////////////////////////////////////////////////////////// - // Gets user synced demographics. See documentation of function - // SyncPrefs::GetUserDemographicss for more details. You need to provide an - // accurate |now| time that represents the user's current time. - virtual base::Optional<UserDemographics> GetUserDemographics( - base::Time now) = 0; + // Gets user synced demographics. Returns an error status with an empty value + // when demographics cannot be provided. You need to provide an accurate |now| + // time that represents the user's current time. + virtual UserDemographicsResult GetUserDemographics(base::Time now) = 0; ////////////////////////////////////////////////////////////////////////////// // OBSERVERS
diff --git a/components/sync/driver/test_sync_service.cc b/components/sync/driver/test_sync_service.cc index b4b8db544..ea40f6f 100644 --- a/components/sync/driver/test_sync_service.cc +++ b/components/sync/driver/test_sync_service.cc
@@ -38,7 +38,9 @@ : user_settings_(this), preferred_data_types_(ModelTypeSet::All()), active_data_types_(ModelTypeSet::All()), - last_cycle_snapshot_(MakeDefaultCycleSnapshot()) {} + last_cycle_snapshot_(MakeDefaultCycleSnapshot()), + user_demographics_result_(UserDemographicsResult::ForStatus( + UserDemographicsStatus::kIneligibleDemographicsData)) {} TestSyncService::~TestSyncService() = default; @@ -88,8 +90,8 @@ } void TestSyncService::SetUserDemographics( - const base::Optional<UserDemographics>& demographics) { - user_demographics_ = demographics; + const UserDemographicsResult& user_demographics_result) { + user_demographics_result_ = user_demographics_result; } void TestSyncService::SetEmptyLastCycleSnapshot() { @@ -273,9 +275,8 @@ void TestSyncService::SetInvalidationsForSessionsEnabled(bool enabled) {} -base::Optional<UserDemographics> TestSyncService::GetUserDemographics( - base::Time now) { - return user_demographics_; +UserDemographicsResult TestSyncService::GetUserDemographics(base::Time now) { + return user_demographics_result_; } void TestSyncService::Shutdown() {}
diff --git a/components/sync/driver/test_sync_service.h b/components/sync/driver/test_sync_service.h index 6a6870c35..227ef86 100644 --- a/components/sync/driver/test_sync_service.h +++ b/components/sync/driver/test_sync_service.h
@@ -39,7 +39,7 @@ void SetActiveDataTypes(const ModelTypeSet& types); void SetLastCycleSnapshot(const SyncCycleSnapshot& snapshot); void SetUserDemographics( - const base::Optional<UserDemographics>& demographics); + const UserDemographicsResult& user_demographics_result); // Convenience versions of the above, for when the caller doesn't care about // the particular values in the snapshot, just whether there is one. @@ -100,7 +100,7 @@ const base::Callback<void(std::unique_ptr<base::ListValue>)>& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; - base::Optional<UserDemographics> GetUserDemographics(base::Time now) override; + UserDemographicsResult GetUserDemographics(base::Time now) override; // KeyedService implementation. void Shutdown() override; @@ -128,7 +128,7 @@ GURL sync_service_url_; - base::Optional<UserDemographics> user_demographics_; + UserDemographicsResult user_demographics_result_; DISALLOW_COPY_AND_ASSIGN(TestSyncService); };
diff --git a/components/sync/engine/net/http_bridge.cc b/components/sync/engine/net/http_bridge.cc index 5e50d43..22e4655 100644 --- a/components/sync/engine/net/http_bridge.cc +++ b/components/sync/engine/net/http_bridge.cc
@@ -123,10 +123,10 @@ http_post_completed_(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED), url_loader_factory_info_(std::move(url_loader_factory_info)), - network_task_runner_( - g_io_capable_task_runner_for_tests.Get() - ? g_io_capable_task_runner_for_tests.Get() - : base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()})), + network_task_runner_(g_io_capable_task_runner_for_tests.Get() + ? g_io_capable_task_runner_for_tests.Get() + : base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock()})), network_time_update_callback_(network_time_update_callback) {} HttpBridge::~HttpBridge() {}
diff --git a/components/sync/engine/sequenced_model_worker_unittest.cc b/components/sync/engine/sequenced_model_worker_unittest.cc index 815e5109..fb1946a 100644 --- a/components/sync/engine/sequenced_model_worker_unittest.cc +++ b/components/sync/engine/sequenced_model_worker_unittest.cc
@@ -59,8 +59,9 @@ protected: void SetUp() override { - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); + task_runner_ = + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::BEST_EFFORT}); worker_ = new SequencedModelWorker(task_runner_, GROUP_DB); }
diff --git a/components/sync/engine/sync_engine.h b/components/sync/engine/sync_engine.h index 5dd622e..7e42f06 100644 --- a/components/sync/engine/sync_engine.h +++ b/components/sync/engine/sync_engine.h
@@ -65,6 +65,7 @@ CoreAccountId authenticated_account_id; std::string invalidator_client_id; std::unique_ptr<SyncManagerFactory> sync_manager_factory; + // TODO(crbug.com/955989): Remove since it's unused. bool delete_sync_data_folder = false; bool enable_local_sync_backend = false; base::FilePath local_sync_backend_folder;
diff --git a/components/sync/model_impl/model_type_store_service_impl.cc b/components/sync/model_impl/model_type_store_service_impl.cc index da1c8fad..c0039537 100644 --- a/components/sync/model_impl/model_type_store_service_impl.cc +++ b/components/sync/model_impl/model_type_store_service_impl.cc
@@ -94,8 +94,9 @@ const base::FilePath& base_path) : sync_path_(base_path.Append(base::FilePath(kSyncDataFolderName))), leveldb_path_(sync_path_.Append(base::FilePath(kLevelDBFolderName))), - backend_task_runner_(base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + backend_task_runner_(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), store_backend_(ModelTypeStoreBackend::CreateUninitialized()) { DCHECK(backend_task_runner_); backend_task_runner_->PostTask(
diff --git a/components/test/android/OWNERS b/components/test/android/OWNERS index e822ec4..709192b 100644 --- a/components/test/android/OWNERS +++ b/components/test/android/OWNERS
@@ -1,2 +1,3 @@ jaekyun@chromium.org tedchoc@chromium.org +# COMPONENT: Tests
diff --git a/components/ui_devtools/views/dom_agent_unittest.cc b/components/ui_devtools/views/dom_agent_unittest.cc index a702a40..a6905a4 100644 --- a/components/ui_devtools/views/dom_agent_unittest.cc +++ b/components/ui_devtools/views/dom_agent_unittest.cc
@@ -78,7 +78,7 @@ #if defined(USE_AURA) params.parent = GetContext(); #endif - widget->Init(params); + widget->Init(std::move(params)); return widget->native_widget_private(); } @@ -95,7 +95,7 @@ #endif if (name) params.name = *name; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/components/ui_devtools/views/overlay_agent_unittest.cc b/components/ui_devtools/views/overlay_agent_unittest.cc index 20520e2..bfd40f3 100644 --- a/components/ui_devtools/views/overlay_agent_unittest.cc +++ b/components/ui_devtools/views/overlay_agent_unittest.cc
@@ -122,7 +122,7 @@ #if defined(USE_AURA) params.parent = GetContext(); #endif - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); }
diff --git a/components/ui_devtools/views/view_element_unittest.cc b/components/ui_devtools/views/view_element_unittest.cc index 41a6a7c5..ca21a9b 100644 --- a/components/ui_devtools/views/view_element_unittest.cc +++ b/components/ui_devtools/views/view_element_unittest.cc
@@ -232,7 +232,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->GetContentsView()->AddChildView(view());
diff --git a/components/ui_devtools/views/widget_element_unittest.cc b/components/ui_devtools/views/widget_element_unittest.cc index 4fef1df..dc3ede06 100644 --- a/components/ui_devtools/views/widget_element_unittest.cc +++ b/components/ui_devtools/views/widget_element_unittest.cc
@@ -29,7 +29,7 @@ views::Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_WINDOW); params.name = kWidgetName; - widget_->Init(params); + widget_->Init(std::move(params)); delegate_.reset(new testing::NiceMock<MockUIElementDelegate>); element_.reset(new WidgetElement(widget_, delegate_.get(), nullptr));
diff --git a/components/update_client/action_runner.cc b/components/update_client/action_runner.cc index c1f8297..e738bdc 100644 --- a/components/update_client/action_runner.cc +++ b/components/update_client/action_runner.cc
@@ -40,7 +40,7 @@ run_complete_ = std::move(run_complete); - base::CreateSequencedTaskRunnerWithTraits(kTaskTraits) + base::CreateSequencedTaskRunner(kTaskTraits) ->PostTask( FROM_HERE, base::BindOnce(&ActionRunner::RunOnTaskRunner, base::Unretained(this),
diff --git a/components/update_client/action_runner_win.cc b/components/update_client/action_runner_win.cc index 6985ee6..dca30597 100644 --- a/components/update_client/action_runner_win.cc +++ b/components/update_client/action_runner_win.cc
@@ -34,10 +34,9 @@ options.start_hidden = true; base::Process process = base::LaunchProcess(cmdline, options); - base::PostTaskWithTraits( - FROM_HERE, kTaskTraitsRunCommand, - base::BindOnce(&ActionRunner::WaitForCommand, base::Unretained(this), - std::move(process))); + base::PostTask(FROM_HERE, kTaskTraitsRunCommand, + base::BindOnce(&ActionRunner::WaitForCommand, + base::Unretained(this), std::move(process))); } void ActionRunner::WaitForCommand(base::Process process) { @@ -67,7 +66,7 @@ } void ActionRunner::RunRecoveryCRXElevated(const base::FilePath& crx_path) { - base::CreateCOMSTATaskRunnerWithTraits( + base::CreateCOMSTATaskRunner( kTaskTraitsRunCommand, base::SingleThreadTaskRunnerThreadMode::DEDICATED) ->PostTask(FROM_HERE, base::BindOnce(&ActionRunner::RunRecoveryCRXElevatedInSTA,
diff --git a/components/update_client/background_downloader_win.cc b/components/update_client/background_downloader_win.cc index 4d6e28e..5e165799 100644 --- a/components/update_client/background_downloader_win.cc +++ b/components/update_client/background_downloader_win.cc
@@ -399,8 +399,8 @@ BackgroundDownloader::BackgroundDownloader( std::unique_ptr<CrxDownloader> successor) : CrxDownloader(std::move(successor)), - com_task_runner_(base::CreateCOMSTATaskRunnerWithTraits( - kTaskTraitsBackgroundDownloader)), + com_task_runner_( + base::CreateCOMSTATaskRunner(kTaskTraitsBackgroundDownloader)), git_cookie_bits_manager_(0), git_cookie_job_(0) {}
diff --git a/components/update_client/component.cc b/components/update_client/component.cc index 73fc259..7f5ecb5 100644 --- a/components/update_client/component.cc +++ b/components/update_client/component.cc
@@ -75,8 +75,9 @@ InstallOnBlockingTaskRunnerCompleteCallback callback, const base::FilePath& unpack_path, const CrxInstaller::Result& result) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce( [](scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, InstallOnBlockingTaskRunnerCompleteCallback callback, @@ -141,11 +142,10 @@ return; } - base::PostTaskWithTraits( - FROM_HERE, kTaskTraits, - base::BindOnce(&InstallOnBlockingTaskRunner, main_task_runner, - result.unpack_path, result.public_key, fingerprint, - installer, std::move(callback))); + base::PostTask(FROM_HERE, kTaskTraits, + base::BindOnce(&InstallOnBlockingTaskRunner, main_task_runner, + result.unpack_path, result.public_key, + fingerprint, installer, std::move(callback))); } void StartInstallOnBlockingTaskRunner( @@ -756,7 +756,7 @@ component.NotifyObservers(Events::COMPONENT_UPDATE_READY); - base::CreateSequencedTaskRunnerWithTraits(kTaskTraits) + base::CreateSequencedTaskRunner(kTaskTraits) ->PostTask( FROM_HERE, base::BindOnce( @@ -818,7 +818,7 @@ component.NotifyObservers(Events::COMPONENT_UPDATE_READY); - base::CreateSequencedTaskRunnerWithTraits(kTaskTraits) + base::CreateSequencedTaskRunner(kTaskTraits) ->PostTask(FROM_HERE, base::BindOnce( &update_client::StartInstallOnBlockingTaskRunner,
diff --git a/components/update_client/crx_downloader.cc b/components/update_client/crx_downloader.cc index a881c865..cf45d4c 100644 --- a/components/update_client/crx_downloader.cc +++ b/components/update_client/crx_downloader.cc
@@ -120,7 +120,7 @@ DCHECK(thread_checker_.CalledOnValidThread()); if (!result.error) - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kTaskTraits, base::BindOnce(&CrxDownloader::VerifyResponse, base::Unretained(this), is_handled, result, download_metrics));
diff --git a/components/update_client/task_traits.h b/components/update_client/task_traits.h index d14bbea..1f675e7 100644 --- a/components/update_client/task_traits.h +++ b/components/update_client/task_traits.h
@@ -10,16 +10,16 @@ namespace update_client { constexpr base::TaskTraits kTaskTraits = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; constexpr base::TaskTraits kTaskTraitsBackgroundDownloader = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}; // This task joins a process, hence .WithBaseSyncPrimitives(). constexpr base::TaskTraits kTaskTraitsRunCommand = { - base::MayBlock(), base::WithBaseSyncPrimitives(), + base::ThreadPool(), base::MayBlock(), base::WithBaseSyncPrimitives(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN};
diff --git a/components/update_client/test_installer.cc b/components/update_client/test_installer.cc index c6e5b8aa..0285af0f 100644 --- a/components/update_client/test_installer.cc +++ b/components/update_client/test_installer.cc
@@ -44,8 +44,8 @@ void TestInstaller::InstallComplete(Callback callback, const Result& result) const { - base::PostTaskWithTraits(FROM_HERE, {base::MayBlock()}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(std::move(callback), result)); } bool TestInstaller::GetInstalledFile(const std::string& file,
diff --git a/components/update_client/update_checker.cc b/components/update_client/update_checker.cc index b9d83ba..cfc2578 100644 --- a/components/update_client/update_checker.cc +++ b/components/update_client/update_checker.cc
@@ -130,7 +130,7 @@ ids_checked_ = ids_checked; update_check_callback_ = std::move(update_check_callback); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, kTaskTraits, base::BindOnce(&UpdateCheckerImpl::ReadUpdaterStateAttributes, base::Unretained(this)),
diff --git a/components/update_client/update_client_unittest.cc b/components/update_client/update_client_unittest.cc index d580470e..cf5f69c 100644 --- a/components/update_client/update_client_unittest.cc +++ b/components/update_client/update_client_unittest.cc
@@ -1633,8 +1633,8 @@ unpack_path_ = unpack_path; EXPECT_TRUE(base::DirectoryExists(unpack_path_)); - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(std::move(callback), CrxInstaller::Result(InstallError::GENERIC_ERROR))); }
diff --git a/components/update_client/url_fetcher_downloader.cc b/components/update_client/url_fetcher_downloader.cc index 7a550feb..eaf78ad 100644 --- a/components/update_client/url_fetcher_downloader.cc +++ b/components/update_client/url_fetcher_downloader.cc
@@ -21,7 +21,7 @@ namespace { constexpr base::TaskTraits kTaskTraits = { - base::MayBlock(), base::TaskPriority::BEST_EFFORT, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; } // namespace @@ -40,7 +40,7 @@ void UrlFetcherDownloader::DoStartDownload(const GURL& url) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, kTaskTraits, base::BindOnce(&UrlFetcherDownloader::CreateDownloadDir, base::Unretained(this)), @@ -136,7 +136,7 @@ // Delete the download directory in the error cases. if (error && !download_dir_.empty()) - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kTaskTraits, base::BindOnce(IgnoreResult(&base::DeleteFile), download_dir_, true));
diff --git a/components/upload_list/upload_list.cc b/components/upload_list/upload_list.cc index 18e49bc..78e6735 100644 --- a/components/upload_list/upload_list.cc +++ b/components/upload_list/upload_list.cc
@@ -17,7 +17,7 @@ // USER_VISIBLE because loading uploads blocks chrome://crashes, // chrome://webrtc-logs and the feedback UI. See https://crbug.com/972526. constexpr base::TaskTraits kLoadingTaskTraits = { - base::MayBlock(), base::TaskPriority::USER_BLOCKING, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}; } // namespace @@ -63,7 +63,7 @@ void UploadList::Load(base::OnceClosure callback) { DCHECK(sequence_checker_.CalledOnValidSequence()); load_callback_ = std::move(callback); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, kLoadingTaskTraits, base::Bind(&UploadList::LoadUploadList, this), base::Bind(&UploadList::OnLoadComplete, this)); @@ -74,7 +74,7 @@ base::OnceClosure callback) { DCHECK(sequence_checker_.CalledOnValidSequence()); clear_callback_ = std::move(callback); - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, kLoadingTaskTraits, base::BindOnce(&UploadList::ClearUploadList, this, begin, end), base::BindOnce(&UploadList::OnClearComplete, this)); @@ -86,7 +86,7 @@ void UploadList::RequestSingleUploadAsync(const std::string& local_id) { DCHECK(sequence_checker_.CalledOnValidSequence()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kLoadingTaskTraits, base::BindOnce(&UploadList::RequestSingleUpload, this, local_id)); }
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker.cc b/components/url_formatter/spoof_checks/idn_spoof_checker.cc index 36c90c9..97711146 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker.cc +++ b/components/url_formatter/spoof_checks/idn_spoof_checker.cc
@@ -35,35 +35,38 @@ if (!reader->Next(&is_same_skeleton)) return false; - std::string top_domain; + TopDomainEntry top_domain; + if (!reader->Next(&top_domain.is_top_500)) + return false; + if (is_same_skeleton) { - top_domain = search; + top_domain.domain = search; } else { bool has_com_suffix = false; if (!reader->Next(&has_com_suffix)) return false; - for (char c;; top_domain += c) { + for (char c;; top_domain.domain += c) { huffman_decoder().Decode(reader, &c); if (c == net::extras::PreloadDecoder::kEndOfTable) break; } if (has_com_suffix) - top_domain += ".com"; + top_domain.domain += ".com"; } if (current_search_offset == 0) { *out_found = true; - DCHECK(!top_domain.empty()); + DCHECK(!top_domain.domain.empty()); result_ = top_domain; } return true; } - std::string matching_top_domain() const { return result_; } + TopDomainEntry matching_top_domain() const { return result_; } private: - std::string result_; + TopDomainEntry result_; }; void OnThreadTermination(void* regex_matcher) { @@ -383,16 +386,17 @@ return !dangerous_pattern->find(); } -std::string IDNSpoofChecker::GetSimilarTopDomain(base::StringPiece16 hostname) { +TopDomainEntry IDNSpoofChecker::GetSimilarTopDomain( + base::StringPiece16 hostname) { DCHECK(!hostname.empty()); for (const std::string& skeleton : GetSkeletons(hostname)) { DCHECK(!skeleton.empty()); - std::string matching_top_domain = LookupSkeletonInTopDomains(skeleton); - if (!matching_top_domain.empty()) { + TopDomainEntry matching_top_domain = LookupSkeletonInTopDomains(skeleton); + if (!matching_top_domain.domain.empty()) { return matching_top_domain; } } - return std::string(); + return TopDomainEntry(); } Skeletons IDNSpoofChecker::GetSkeletons(base::StringPiece16 hostname) { @@ -439,7 +443,7 @@ return skeletons; } -std::string IDNSpoofChecker::LookupSkeletonInTopDomains( +TopDomainEntry IDNSpoofChecker::LookupSkeletonInTopDomains( const std::string& skeleton) { DCHECK(!skeleton.empty()); // There are no other guarantees about a skeleton string such as not including @@ -462,14 +466,14 @@ bool decoded = preload_decoder.Decode(partial_skeleton, &match); DCHECK(decoded); if (!decoded) - return std::string(); + return TopDomainEntry(); if (match) return preload_decoder.matching_top_domain(); labels.erase(labels.begin()); } - return std::string(); + return TopDomainEntry(); } void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker.h b/components/url_formatter/spoof_checks/idn_spoof_checker.h index 1a30355..ae156843 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker.h +++ b/components/url_formatter/spoof_checks/idn_spoof_checker.h
@@ -33,11 +33,18 @@ using Skeletons = base::flat_set<std::string>; +// Represents a top domain entry in the trie. +struct TopDomainEntry { + // The domain name. + std::string domain; + // True if the domain is in the top 500. + bool is_top_500 = false; +}; + // A helper class for IDN Spoof checking, used to ensure that no IDN input is // spoofable per Chromium's standard of spoofability. For a more thorough // explanation of how spoof checking works in Chromium, see // http://dev.chromium.org/developers/design-documents/idn-in-google-chrome . - class IDNSpoofChecker { public: struct HuffmanTrieParams { @@ -65,14 +72,18 @@ // top domains. // 2. Look up the diacritic-free version of |hostname| in the list of // top domains. Note that non-IDN hostnames will not get here. - std::string GetSimilarTopDomain(base::StringPiece16 hostname); + TopDomainEntry GetSimilarTopDomain(base::StringPiece16 hostname); // Returns skeleton strings computed from |hostname|. This function can apply // extra mappings to some characters to produce multiple skeletons. Skeletons GetSkeletons(base::StringPiece16 hostname); // Returns a top domain from the top 10K list matching the given |skeleton|. - std::string LookupSkeletonInTopDomains(const std::string& skeleton); + TopDomainEntry LookupSkeletonInTopDomains(const std::string& skeleton); + + // Used for unit tests. + static void SetTrieParamsForTesting(const HuffmanTrieParams& trie_params); + static void RestoreTrieParamsForTesting(); private: // Sets allowed characters in IDN labels and turns on USPOOF_CHAR_LIMIT. @@ -82,10 +93,6 @@ // Cyrillic letters that look like ASCII Latin letters. bool IsMadeOfLatinAlikeCyrillic(const icu::UnicodeString& label); - // Used for unit tests. - static void SetTrieParamsForTesting(const HuffmanTrieParams& trie_params); - static void RestoreTrieParamsForTesting(); - USpoofChecker* checker_; icu::UnicodeSet deviation_characters_; icu::UnicodeSet non_ascii_latin_letters_; @@ -97,7 +104,6 @@ std::unique_ptr<icu::Transliterator> diacritic_remover_; std::unique_ptr<icu::Transliterator> extra_confusable_mapper_; - FRIEND_TEST_ALL_PREFIXES(IDNSpoofCheckerTest, IDNToUnicode); IDNSpoofChecker(const IDNSpoofChecker&) = delete; void operator=(const IDNSpoofChecker&) = delete; };
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc b/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc index 2afa440..bce7aa80 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc +++ b/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc
@@ -1074,13 +1074,20 @@ } // namespace -TEST(IDNSpoofCheckerTest, IDNToUnicode) { - IDNSpoofChecker::HuffmanTrieParams trie_params{ - test::kTopDomainsHuffmanTree, sizeof(test::kTopDomainsHuffmanTree), - test::kTopDomainsTrie, test::kTopDomainsTrieBits, - test::kTopDomainsRootPosition}; - IDNSpoofChecker::SetTrieParamsForTesting(trie_params); +class IDNSpoofCheckerTest : public ::testing::Test { + protected: + void SetUp() override { + IDNSpoofChecker::HuffmanTrieParams trie_params{ + test::kTopDomainsHuffmanTree, sizeof(test::kTopDomainsHuffmanTree), + test::kTopDomainsTrie, test::kTopDomainsTrieBits, + test::kTopDomainsRootPosition}; + IDNSpoofChecker::SetTrieParamsForTesting(trie_params); + } + void TearDown() override { IDNSpoofChecker::RestoreTrieParamsForTesting(); } +}; + +TEST_F(IDNSpoofCheckerTest, IDNToUnicode) { for (size_t i = 0; i < base::size(kIdnCases); i++) { base::string16 output(IDNToUnicode(kIdnCases[i].input)); base::string16 expected(kIdnCases[i].unicode_allowed @@ -1089,12 +1096,44 @@ EXPECT_EQ(expected, output) << "input # " << i << ": \"" << kIdnCases[i].input << "\""; } - IDNSpoofChecker::RestoreTrieParamsForTesting(); +} + +TEST_F(IDNSpoofCheckerTest, LookupSkeletonInTopDomains) { + { + TopDomainEntry entry = + IDNSpoofChecker().LookupSkeletonInTopDomains("d4OOO.corn"); + EXPECT_EQ("d4000.com", entry.domain); + EXPECT_TRUE(entry.is_top_500); + } + { + TopDomainEntry entry = + IDNSpoofChecker().LookupSkeletonInTopDomains("digklrno68.corn"); + EXPECT_EQ("digklmo68.com", entry.domain); + EXPECT_FALSE(entry.is_top_500); + } +} + +// Same test as LookupSkeletonInTopDomains but using the real top domain list. +TEST(IDNSpoofCheckerNoFixtureTest, LookupSkeletonInTopDomains) { + { + TopDomainEntry entry = + IDNSpoofChecker().LookupSkeletonInTopDomains("google.corn"); + EXPECT_EQ("google.com", entry.domain); + EXPECT_TRUE(entry.is_top_500); + } + { + // This is data dependent, must be updated when the top domain list + // is updated. + TopDomainEntry entry = + IDNSpoofChecker().LookupSkeletonInTopDomains("google.sk"); + EXPECT_EQ("google.sk", entry.domain); + EXPECT_FALSE(entry.is_top_500); + } } // Check the unsafe version of IDNToUnicode. Even though the input domain // matches a top domain, it should still be converted to unicode. -TEST(IDNSpoofCheckerTest, UnsafeIDNToUnicodeWithDetails) { +TEST(IDNSpoofCheckerNoFixtureTest, UnsafeIDNToUnicodeWithDetails) { const struct TestCase { // The IDNA/Punycode version of the domain (plain ASCII). const char* const punycode; @@ -1104,25 +1143,30 @@ const bool expected_has_idn; // The top domain that |punycode| matched to, if any. const char* const expected_matching_domain; + // If true, the matching top domain is expected to be in top 500. + const bool expected_is_top_500; } kTestCases[] = { {// An ASCII, top domain. "google.com", L"google.com", false, // Since it's not unicode, we won't attempt to match it to a top domain. - ""}, + "", + // ...And since we don't match it to a top domain, we don't know if it's + // a top 500 domain. + false}, {// An ASCII domain that's not a top domain. - "not-top-domain.com", L"not-top-domain.com", false, ""}, + "not-top-domain.com", L"not-top-domain.com", false, "", false}, {// A unicode domain that's valid according to all of the rules in IDN // spoof checker except that it matches a top domain. Should be // converted to punycode. - "xn--googl-fsa.com", L"googlé.com", true, "google.com"}, + "xn--googl-fsa.com", L"googlé.com", true, "google.com", true}, {// A unicode domain that's not valid according to the rules in IDN spoof // checker (mixed script) and it matches a top domain. Should be // converted to punycode. - "xn--80ak6aa92e.com", L"аррӏе.com", true, "apple.com"}, + "xn--80ak6aa92e.com", L"аррӏе.com", true, "apple.com", true}, {// A unicode domain that's not valid according to the rules in IDN spoof // checker (mixed script) but it doesn't match a top domain. - "xn--o-o-oai-26a223aia177a7ab7649d.com", L"ɴoτ-τoρ-ďoᛖaiɴ.com", true, - ""}, + "xn--o-o-oai-26a223aia177a7ab7649d.com", L"ɴoτ-τoρ-ďoᛖaiɴ.com", true, "", + false}, }; for (const TestCase& test_case : kTestCases) { @@ -1130,13 +1174,16 @@ UnsafeIDNToUnicodeWithDetails(test_case.punycode); EXPECT_EQ(base::WideToUTF16(test_case.expected_unicode), result.result); EXPECT_EQ(test_case.expected_has_idn, result.has_idn_component); - EXPECT_EQ(test_case.expected_matching_domain, result.matching_top_domain); + EXPECT_EQ(test_case.expected_matching_domain, + result.matching_top_domain.domain); + EXPECT_EQ(test_case.expected_is_top_500, + result.matching_top_domain.is_top_500); } } // Checks that skeletons are properly generated for domains with blocked // characters after using UnsafeIDNToUnicodeWithDetails. -TEST(IDNSpoofCheckerTest, Skeletons) { +TEST(IDNSpoofCheckerNoFixtureTest, Skeletons) { // All of these should produce the same skeleton. Not all of these are // explicitly mapped in idn_spoof_checker.cc, ICU already handles some. const GURL kTestCases[] = {
diff --git a/components/url_formatter/spoof_checks/top_domains/BUILD.gn b/components/url_formatter/spoof_checks/top_domains/BUILD.gn index 73a5e11..5a77d0f1 100644 --- a/components/url_formatter/spoof_checks/top_domains/BUILD.gn +++ b/components/url_formatter/spoof_checks/top_domains/BUILD.gn
@@ -63,8 +63,10 @@ outputs = [ "$target_gen_dir/test_domains-trie-inc.cc", ] - args = - rebase_path(inputs, root_build_dir) + rebase_path(outputs, root_build_dir) + + # Passing --for_testing flag marks only the first site with is_top_500. + args = rebase_path(inputs, root_build_dir) + + rebase_path(outputs, root_build_dir) + [ "--for_testing" ] } executable("make_top_domain_list_for_edit_distance") {
diff --git a/components/url_formatter/spoof_checks/top_domains/make_top_domain_skeletons.cc b/components/url_formatter/spoof_checks/top_domains/make_top_domain_skeletons.cc index 7d1e78d..978b207 100644 --- a/components/url_formatter/spoof_checks/top_domains/make_top_domain_skeletons.cc +++ b/components/url_formatter/spoof_checks/top_domains/make_top_domain_skeletons.cc
@@ -112,7 +112,7 @@ int main(int argc, const char** argv) { if (argc != 1) { std::cerr << "Generates the list of top domain skeletons to use as input to" - "\nbase/dafsa/make_dafsa.py.\nUsage: " + " top_domain_generator.\nUsage: " << argv[0] << '\n'; return 1; }
diff --git a/components/url_formatter/spoof_checks/top_domains/top_domain_generator.cc b/components/url_formatter/spoof_checks/top_domains/top_domain_generator.cc index ffbf6fb..a018f6f 100644 --- a/components/url_formatter/spoof_checks/top_domains/top_domain_generator.cc +++ b/components/url_formatter/spoof_checks/top_domains/top_domain_generator.cc
@@ -19,6 +19,7 @@ #include "base/files/file_util.h" #include "base/logging.h" #include "base/path_service.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -35,7 +36,8 @@ // Print the command line help. void PrintHelp() { std::cout << "top_domain_generator <input-file>" - << " <template-file> <output-file> [--v=1]" << std::endl; + << " <template-file> <output-file> [--for_testing] [--v=1]" + << std::endl; } void CheckName(const std::string& name) { @@ -73,7 +75,7 @@ } base::FilePath input_path = - base::MakeAbsoluteFilePath(base::FilePath::FromUTF8Unsafe(argv[1])); + base::MakeAbsoluteFilePath(base::FilePath::FromUTF8Unsafe(args[0])); if (!base::PathExists(input_path)) { LOG(ERROR) << "Input path doesn't exist: " << input_path; return 1; @@ -85,6 +87,8 @@ return 1; } + const bool for_testing = command_line.HasSwitch("for_testing"); + std::vector<std::string> lines = base::SplitString( input_text, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); @@ -114,13 +118,20 @@ entry->skeleton = skeleton; entry->top_domain = tokens[1]; + // If testing, only mark the first 5 sites as "top 500". + if (for_testing) { + entry->is_top_500 = entries.size() < 1; + } else { + entry->is_top_500 = entries.size() < 500; + } + CheckName(entry->skeleton); CheckName(entry->top_domain); entries.push_back(std::move(entry)); } - base::FilePath template_path = base::FilePath::FromUTF8Unsafe(argv[2]); + base::FilePath template_path = base::FilePath::FromUTF8Unsafe(args[1]); if (!base::PathExists(template_path)) { LOG(ERROR) << "Template file doesn't exist: " << template_path; return 1; @@ -140,7 +151,7 @@ return 1; } - base::FilePath output_path = base::FilePath::FromUTF8Unsafe(argv[3]); + base::FilePath output_path = base::FilePath::FromUTF8Unsafe(args[2]); if (base::WriteFile(output_path, output.c_str(), static_cast<uint32_t>(output.size())) <= 0) { LOG(ERROR) << "Failed to write output: " << output_path;
diff --git a/components/url_formatter/spoof_checks/top_domains/trie_entry.cc b/components/url_formatter/spoof_checks/top_domains/trie_entry.cc index 00fd52d..13ebcd0 100644 --- a/components/url_formatter/spoof_checks/top_domains/trie_entry.cc +++ b/components/url_formatter/spoof_checks/top_domains/trie_entry.cc
@@ -29,9 +29,11 @@ net::huffman_trie::TrieBitBuffer* writer) const { if (entry_->skeleton == entry_->top_domain) { writer->WriteBit(1); + writer->WriteBit(entry_->is_top_500 ? 1 : 0); return true; } writer->WriteBit(0); + writer->WriteBit(entry_->is_top_500 ? 1 : 0); std::string top_domain = entry_->top_domain; // With the current top 10,000 domains, this optimization reduces the
diff --git a/components/url_formatter/spoof_checks/top_domains/trie_entry.h b/components/url_formatter/spoof_checks/top_domains/trie_entry.h index bb47809..20b7c1aa 100644 --- a/components/url_formatter/spoof_checks/top_domains/trie_entry.h +++ b/components/url_formatter/spoof_checks/top_domains/trie_entry.h
@@ -18,6 +18,7 @@ struct TopDomainEntry { std::string skeleton; std::string top_domain; + bool is_top_500; }; class TopDomainTrieEntry : public net::huffman_trie::TrieEntry {
diff --git a/components/url_formatter/url_formatter.cc b/components/url_formatter/url_formatter.cc index 8fae05d..e2478a5c 100644 --- a/components/url_formatter/url_formatter.cc +++ b/components/url_formatter/url_formatter.cc
@@ -17,7 +17,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_local_storage.h" #include "build/build_config.h" -#include "components/url_formatter/spoof_checks/idn_spoof_checker.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "third_party/icu/source/common/unicode/uidna.h" #include "third_party/icu/source/common/unicode/utypes.h" @@ -286,7 +285,7 @@ if (result.has_idn_component) { result.matching_top_domain = g_idn_spoof_checker.Get().GetSimilarTopDomain(out16); - if (enable_spoof_checks && !result.matching_top_domain.empty()) { + if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) { if (adjustments) adjustments->clear(); result.result = input16; @@ -705,7 +704,7 @@ return g_idn_spoof_checker.Get().GetSkeletons(host); } -std::string LookupSkeletonInTopDomains(const std::string& skeleton) { +TopDomainEntry LookupSkeletonInTopDomains(const std::string& skeleton) { return g_idn_spoof_checker.Get().LookupSkeletonInTopDomains(skeleton); }
diff --git a/components/url_formatter/url_formatter.h b/components/url_formatter/url_formatter.h index 18cc2781..4803b557 100644 --- a/components/url_formatter/url_formatter.h +++ b/components/url_formatter/url_formatter.h
@@ -25,6 +25,7 @@ #include "base/strings/string16.h" #include "base/strings/string_piece.h" #include "base/strings/utf_offset_string_conversions.h" +#include "components/url_formatter/spoof_checks/idn_spoof_checker.h" #include "net/base/escape.h" class GURL; @@ -53,8 +54,8 @@ // The top domain that the hostname of the input is visually similar to. Is // empty if the input didn't match any top domain. // E.g. IDNToUnicodeWithDetails("googlé.com") will fill |result| with - // "xn--googl-fsa.com" and |matching_top_domain| with "google.com". - std::string matching_top_domain; + // "xn--googl-fsa.com" and |matching_top_domain.domain| with "google.com". + TopDomainEntry matching_top_domain; }; // Nothing is omitted. @@ -192,7 +193,7 @@ // Returns a domain from the top 10K list matching the given skeleton. Used for // spoof checking. -std::string LookupSkeletonInTopDomains(const std::string& skeleton); +TopDomainEntry LookupSkeletonInTopDomains(const std::string& skeleton); } // namespace url_formatter
diff --git a/components/variations/net/BUILD.gn b/components/variations/net/BUILD.gn index 7d103d4..23bad7c 100644 --- a/components/variations/net/BUILD.gn +++ b/components/variations/net/BUILD.gn
@@ -19,7 +19,7 @@ ] deps = [ "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/metrics", "//components/variations/field_trial_config", "//components/variations/proto",
diff --git a/components/variations/service/variations_service.cc b/components/variations/service/variations_service.cc index fe42449..90e687b4 100644 --- a/components/variations/service/variations_service.cc +++ b/components/variations/service/variations_service.cc
@@ -608,8 +608,9 @@ // activated by this seed. To do this, first get the Chrome version to do a // simulation with, which must be done on a background thread, and then do the // actual simulation on the UI thread. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, client_->GetVersionForSimulationCallback(), base::Bind(&VariationsService::PerformSimulationWithVersion, weak_ptr_factory_.GetWeakPtr(), base::Passed(&seed)));
diff --git a/components/visitedlink/browser/visitedlink_master.cc b/components/visitedlink/browser/visitedlink_master.cc index 19265ce..1918a684 100644 --- a/components/visitedlink/browser/visitedlink_master.cc +++ b/components/visitedlink/browser/visitedlink_master.cc
@@ -617,9 +617,8 @@ scoped_refptr<LoadFromFileResult> load_from_file_result; bool success = LoadApartFromFile(filename, &load_from_file_result); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, success, load_from_file_result)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, success, load_from_file_result)); } // static @@ -1141,9 +1140,8 @@ // Marshal to the main thread to notify the VisitedLinkMaster that the // rebuild is complete. - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&TableBuilder::OnCompleteMainThread, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&TableBuilder::OnCompleteMainThread, this)); } void VisitedLinkMaster::TableBuilder::OnCompleteMainThread() {
diff --git a/components/visitedlink/browser/visitedlink_master.h b/components/visitedlink/browser/visitedlink_master.h index 6f8bb3d..08be8c7d 100644 --- a/components/visitedlink/browser/visitedlink_master.h +++ b/components/visitedlink/browser/visitedlink_master.h
@@ -405,8 +405,9 @@ // Task runner for posting file tasks. scoped_refptr<base::SequencedTaskRunner> file_task_runner_ = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); // When non-NULL, indicates we are in database rebuild mode and points to
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index abab7162..112a813 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -14,9 +14,6 @@ namespace features { -const base::Feature kEnableSurfaceSynchronization{ - "SurfaceSynchronization", base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables running the display compositor as part of the viz service in the GPU // process. This is also referred to as out-of-process display compositor // (OOP-D). @@ -46,8 +43,8 @@ base::FEATURE_DISABLED_BY_DEFAULT}; bool IsSurfaceSynchronizationEnabled() { - return IsVizDisplayCompositorEnabled() || - base::FeatureList::IsEnabled(kEnableSurfaceSynchronization); + // TODO(crbug.com/985009): Delete function after all callers are removed. + return true; } bool IsVizDisplayCompositorEnabled() {
diff --git a/components/viz/common/features.h b/components/viz/common/features.h index 1b14d5d..0bd8394 100644 --- a/components/viz/common/features.h +++ b/components/viz/common/features.h
@@ -11,7 +11,6 @@ namespace features { -VIZ_COMMON_EXPORT extern const base::Feature kEnableSurfaceSynchronization; VIZ_COMMON_EXPORT extern const base::Feature kEnableVizHitTestSurfaceLayer; VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaForGLReadback; VIZ_COMMON_EXPORT extern const base::Feature kUseSkiaRenderer;
diff --git a/components/viz/service/gl/gpu_service_impl.cc b/components/viz/service/gl/gpu_service_impl.cc index 78f0cca..d9c58ac 100644 --- a/components/viz/service/gl/gpu_service_impl.cc +++ b/components/viz/service/gl/gpu_service_impl.cc
@@ -589,8 +589,8 @@ // We can continue on shutdown here because we're not writing any critical // state in this task. base::PostTaskAndReplyWithResult( - base::CreateCOMSTATaskRunnerWithTraits( - {base::TaskPriority::USER_VISIBLE, + base::CreateCOMSTATaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}) .get(), FROM_HERE, base::BindOnce([]() {
diff --git a/components/web_resource/BUILD.gn b/components/web_resource/BUILD.gn index ac70b7e..26ecee2 100644 --- a/components/web_resource/BUILD.gn +++ b/components/web_resource/BUILD.gn
@@ -16,7 +16,7 @@ deps = [ "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/pref_registry", "//components/prefs", "//components/version_info",
diff --git a/components/webdata_services/web_data_service_wrapper.cc b/components/webdata_services/web_data_service_wrapper.cc index baf03a4a..8eb831c 100644 --- a/components/webdata_services/web_data_service_wrapper.cc +++ b/components/webdata_services/web_data_service_wrapper.cc
@@ -101,8 +101,8 @@ // TODO(pkasting): http://crbug.com/740773 This should likely be sequenced, // not single-threaded; it's also possible the various uses of this below // should each use their own sequences instead of sharing this one. - auto db_task_runner = base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + auto db_task_runner = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); profile_database_ = new WebDatabaseService(path, ui_task_runner, db_task_runner);
diff --git a/content/DEPS b/content/DEPS index 6b12bcdf..7e891035 100644 --- a/content/DEPS +++ b/content/DEPS
@@ -124,19 +124,9 @@ # content -> content/shell dependency is disallowed, except browser tests. "+content/shell/browser", "+content/shell/common", - - # components/variations/variations_params_manager.h is allowed from tests - # (it is part of //components/variations:test_support target). - "+components/variations/variations_params_manager.h", ], - "test_utils\.cc": [ - # components/variations/variations_params_manager.h is allowed from tests - # (it is part of //components/variations:test_support target). - "+components/variations/variations_params_manager.h", - ], - - # Dependencies specific for fuzz targets and other fuzzing-related code. + # Dependencies specific for fuzz targets and other fuzzing-related code. ".*fuzz.*": [ "+third_party/libFuzzer/src/utils", # This contains FuzzedDataProvider. ]
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 0d86acd..93d2088c 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -72,8 +72,6 @@ "//components/tracing/common:interfaces", "//components/ui_devtools", "//components/url_formatter", - "//components/variations", - "//components/variations/net", "//components/viz/client", "//components/viz/common", "//components/viz/host",
diff --git a/content/browser/DEPS b/content/browser/DEPS index 2103991..e37025d 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -1,6 +1,9 @@ include_rules = [ # Allow inclusion of specific components that we depend on. # See comment in content/DEPS for which components are allowed. + # *********************************** NOTE *********************************** + # If adding a new component dependency, email content/OWNERS first. + # **************************************************************************** "+components/discardable_memory/common", "+components/discardable_memory/public", "+components/discardable_memory/service", @@ -20,7 +23,6 @@ "+components/offline_pages/buildflags/buildflags.h", "+components/offline_pages/core/request_header", "+components/payments", - "+components/profile_service", "+components/rappor/public", "+components/services/heap_profiling/public", "+components/tracing", @@ -30,6 +32,9 @@ "+components/viz", "+components/cbor", "+components/os_crypt/os_crypt_switches.h", + # *********************************** NOTE *********************************** + # If adding a new component dependency, email content/OWNERS first. + # **************************************************************************** "+content/public/app", "+content/public/browser",
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index eab7111..8be9e28 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -918,7 +918,8 @@ DevToolsBackgroundService::kPeriodicBackgroundSync, /* event_name= */ "Got next event delay", /* instance_id= */ registration.options()->tag, - {{"Next Attempt Delay (ms)", GetDelayAsString(delay)}}); + {{"Next Attempt Delay (ms)", + GetDelayAsString(registration.delay_until() - clock_->Now())}}); } AddOrUpdateActiveRegistration( @@ -1980,7 +1981,8 @@ std::string event_name = GetSyncEventName(registration->sync_type()) + (succeeded ? " event completed" : " event failed"); std::map<std::string, std::string> event_metadata = { - {"Next Attempt Delay (ms)", GetDelayAsString(delay)}}; + {"Next Attempt Delay (ms)", + GetDelayAsString(registration->delay_until() - clock_->Now())}}; if (!succeeded) { event_metadata.emplace("Failure Reason", GetEventStatusString(status_code));
diff --git a/content/browser/background_sync/background_sync_manager_unittest.cc b/content/browser/background_sync/background_sync_manager_unittest.cc index 4419b8b..acec7a2 100644 --- a/content/browser/background_sync/background_sync_manager_unittest.cc +++ b/content/browser/background_sync/background_sync_manager_unittest.cc
@@ -1221,20 +1221,28 @@ TEST_F(BackgroundSyncManagerTest, PeriodicSyncFiresWhenExpected) { InitPeriodicSyncEventTest(); - int thirteen_hours_ms = 13 * 60 * 60 * 1000; - sync_options_2_.min_interval = thirteen_hours_ms; + base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13); + sync_options_2_.min_interval = thirteen_hours.InMilliseconds(); EXPECT_TRUE(Register(sync_options_2_)); EXPECT_EQ(0, periodic_sync_events_called_); EXPECT_TRUE(GetRegistration(sync_options_2_)); // Advance clock. - test_clock_.Advance(base::TimeDelta::FromMilliseconds(thirteen_hours_ms)); + test_clock_.Advance(thirteen_hours); FireReadyEvents(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, periodic_sync_events_called_); EXPECT_TRUE(GetRegistration(sync_options_2_)); + + // Advance clock again. + test_clock_.Advance(thirteen_hours); + FireReadyEvents(); + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(2, periodic_sync_events_called_); + EXPECT_TRUE(GetRegistration(sync_options_2_)); } TEST_F(BackgroundSyncManagerTest, TestSupensionAndRevival) { @@ -1855,6 +1863,53 @@ EXPECT_FALSE(GetRegistration(sync_options_1_)); } +TEST_F(BackgroundSyncManagerTest, TwoFailedAttemptsForPeriodicSync) { + SetMaxSyncAttemptsAndRestartManager(2); + InitFailedPeriodicSyncEventTest(); + + base::TimeDelta thirteen_hours = base::TimeDelta::FromHours(13); + sync_options_2_.min_interval = thirteen_hours.InMilliseconds(); + + EXPECT_TRUE(Register(sync_options_2_)); + EXPECT_TRUE(GetRegistration(sync_options_2_)); + EXPECT_EQ(0, periodic_sync_events_called_); + + // Advance clock. + test_clock_.Advance(thirteen_hours); + FireReadyEvents(); + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(1, periodic_sync_events_called_); + EXPECT_TRUE(GetRegistration(sync_options_2_)); + + // Since this one failed, a wakeup/delayed task will be scheduled for retries + // after five minutes. + EXPECT_EQ(base::TimeDelta::FromMinutes(5), + test_background_sync_manager()->delayed_periodic_sync_task_delta()); + test_clock_.Advance(base::TimeDelta::FromMinutes(5)); + FireReadyEvents(); + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(2, periodic_sync_events_called_); + EXPECT_TRUE(GetRegistration(sync_options_2_)); + + // Second attempt would also fail, resetting to next thirteen_hours. + // Expect nothing after just another hour. + test_clock_.Advance(base::TimeDelta::FromHours(1)); + FireReadyEvents(); + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(2, periodic_sync_events_called_); + + // Expect the next event after another twelve hours. + test_clock_.Advance(base::TimeDelta::FromHours(12)); + FireReadyEvents(); + base::RunLoop().RunUntilIdle(); + + EXPECT_EQ(3, periodic_sync_events_called_); + EXPECT_TRUE(GetRegistration(sync_options_2_)); +} + TEST_F(BackgroundSyncManagerTest, TwoAttempts) { SetMaxSyncAttemptsAndRestartManager(2); InitFailedSyncEventTest();
diff --git a/content/browser/devtools/protocol/DEPS b/content/browser/devtools/protocol/DEPS index 4d8e52aa..8577b7ccb 100644 --- a/content/browser/devtools/protocol/DEPS +++ b/content/browser/devtools/protocol/DEPS
@@ -1,6 +1,7 @@ include_rules = [ # For parsing and validating fido enums in protocol/webauthn_handler.cc. "+device/fido/fido_constants.h", + "+device/fido/fido_parsing_utils.h", "+device/fido/fido_transport_protocol.h", # For VirtualFidoDevice::RegistrationData used in protocol/webauthn_handler.cc. "+device/fido/virtual_fido_device.h",
diff --git a/content/browser/devtools/protocol/webauthn_handler.cc b/content/browser/devtools/protocol/webauthn_handler.cc index 70e469b..3cdc6eaa 100644 --- a/content/browser/devtools/protocol/webauthn_handler.cc +++ b/content/browser/devtools/protocol/webauthn_handler.cc
@@ -5,6 +5,8 @@ #include "content/browser/devtools/protocol/webauthn_handler.h" #include <map> +#include <string> +#include <utility> #include <vector> #include "base/strings/string_number_conversions.h" @@ -14,6 +16,7 @@ #include "content/browser/webauth/virtual_authenticator.h" #include "content/browser/webauth/virtual_fido_discovery_factory.h" #include "device/fido/fido_constants.h" +#include "device/fido/fido_parsing_utils.h" #include "device/fido/fido_transport_protocol.h" #include "device/fido/virtual_fido_device.h" #include "device/fido/virtual_u2f_device.h" @@ -32,10 +35,16 @@ "The DevTools session is not attached to a frame"; static constexpr char kErrorCreatingAuthenticator[] = "An error occurred when trying to create the authenticator"; +static constexpr char kHandleRequiredForResidentCredential[] = + "The User Handle is required for Resident Credentials"; static constexpr char kInvalidProtocol[] = "The protocol is not valid"; -static constexpr char kInvalidRpIdHash[] = - "The Relying Party ID hash must have a size of "; static constexpr char kInvalidTransport[] = "The transport is not valid"; +static constexpr char kInvalidUserHandle[] = + "The User Handle must have a maximum size of "; +static constexpr char kResidentCredentialNotSupported[] = + "The Authenticator does not support Resident Credentials."; +static constexpr char kRpIdRequired[] = + "The Relying Party ID is a required parameter"; static constexpr char kVirtualEnvironmentNotEnabled[] = "The Virtual Authenticator Environment has not been enabled for this " "session"; @@ -147,19 +156,42 @@ if (!response.isSuccess()) return response; - if (credential->GetRpIdHash().size() != device::kRpIdHashLength) { + Binary user_handle = credential->GetUserHandle(Binary()); + if (credential->HasUserHandle() && + user_handle.size() > device::kUserHandleMaxLength) { return Response::InvalidParams( - kInvalidRpIdHash + base::NumberToString(device::kRpIdHashLength)); + kInvalidUserHandle + + base::NumberToString(device::kUserHandleMaxLength)); } - if (!authenticator->AddRegistration( - CopyBinaryToVector(credential->GetCredentialId()), - CopyBinaryToVector(credential->GetRpIdHash()), - CopyBinaryToVector(credential->GetPrivateKey()), - credential->GetSignCount())) { - return Response::Error(kCouldNotCreateCredential); + if (!credential->HasRpId()) + return Response::InvalidParams(kRpIdRequired); + std::string rp_id = credential->GetRpId(""); + + bool credential_created; + if (credential->GetIsResidentCredential()) { + if (!authenticator->has_resident_key()) + return Response::InvalidParams(kResidentCredentialNotSupported); + + if (!credential->HasUserHandle()) + return Response::InvalidParams(kHandleRequiredForResidentCredential); + + credential_created = authenticator->AddResidentRegistration( + CopyBinaryToVector(credential->GetCredentialId()), rp_id, + CopyBinaryToVector(credential->GetPrivateKey()), + credential->GetSignCount(), CopyBinaryToVector(user_handle)); + } else { + credential_created = authenticator->AddRegistration( + CopyBinaryToVector(credential->GetCredentialId()), + base::make_span<uint8_t, device::kRpIdHashLength>( + device::fido_parsing_utils::CreateSHA256Hash(rp_id)), + CopyBinaryToVector(credential->GetPrivateKey()), + credential->GetSignCount()); } + if (!credential_created) + return Response::Error(kCouldNotCreateCredential); + return Response::OK(); } @@ -172,19 +204,25 @@ return response; *out_credentials = std::make_unique<Array<WebAuthn::Credential>>(); - for (const auto& credential : authenticator->registrations()) { - const auto& rp_id_hash = credential.second.application_parameter; + for (const auto& registration : authenticator->registrations()) { std::vector<uint8_t> private_key; - credential.second.private_key->ExportPrivateKey(&private_key); - (*out_credentials) - ->emplace_back( - WebAuthn::Credential::Create() - .SetCredentialId(Binary::fromVector(credential.first)) - .SetRpIdHash( - Binary::fromSpan(rp_id_hash.data(), rp_id_hash.size())) - .SetPrivateKey(Binary::fromVector(std::move(private_key))) - .SetSignCount(credential.second.counter) - .Build()); + registration.second.private_key->ExportPrivateKey(&private_key); + + auto credential = + WebAuthn::Credential::Create() + .SetCredentialId(Binary::fromVector(registration.first)) + .SetPrivateKey(Binary::fromVector(std::move(private_key))) + .SetSignCount(registration.second.counter) + .SetIsResidentCredential(registration.second.is_resident) + .Build(); + + if (registration.second.rp) + credential->SetRpId(registration.second.rp->id); + if (registration.second.user) { + credential->SetUserHandle( + Binary::fromVector(registration.second.user->id)); + } + (*out_credentials)->emplace_back(std::move(credential)); } return Response::OK(); }
diff --git a/content/browser/frame_host/OWNERS b/content/browser/frame_host/OWNERS index 66f5ba1..c8f9887 100644 --- a/content/browser/frame_host/OWNERS +++ b/content/browser/frame_host/OWNERS
@@ -1,4 +1,6 @@ # COMPONENT: Internals>Sandbox>SiteIsolation +# TEAM: site-isolation-dev@chromium.org + arthursonzogni@chromium.org # For surface ID propagation and synchronization
diff --git a/content/browser/frame_host/cross_process_frame_connector.cc b/content/browser/frame_host/cross_process_frame_connector.cc index 1d1c93bc..f6e49231 100644 --- a/content/browser/frame_host/cross_process_frame_connector.cc +++ b/content/browser/frame_host/cross_process_frame_connector.cc
@@ -181,14 +181,6 @@ parent_view->host()->delegate()->SubframeCrashed(visibility_); } -void CrossProcessFrameConnector::FirstSurfaceActivation( - const viz::SurfaceInfo& surface_info) { - if (!features::IsSurfaceSynchronizationEnabled()) { - frame_proxy_in_parent_renderer_->Send(new FrameMsg_FirstSurfaceActivation( - frame_proxy_in_parent_renderer_->GetRoutingID(), surface_info)); - } -} - void CrossProcessFrameConnector::SendIntrinsicSizingInfoToParent( const blink::WebIntrinsicSizingInfo& sizing_info) { frame_proxy_in_parent_renderer_->Send(
diff --git a/content/browser/frame_host/cross_process_frame_connector.h b/content/browser/frame_host/cross_process_frame_connector.h index 0334178..c57a578 100644 --- a/content/browser/frame_host/cross_process_frame_connector.h +++ b/content/browser/frame_host/cross_process_frame_connector.h
@@ -78,7 +78,6 @@ RenderWidgetHostViewBase* GetParentRenderWidgetHostView() override; RenderWidgetHostViewBase* GetRootRenderWidgetHostView() override; void RenderProcessGone() override; - void FirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override; void SendIntrinsicSizingInfoToParent( const blink::WebIntrinsicSizingInfo&) override;
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 151819d..40f74d8 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -4298,8 +4298,8 @@ static_cast<StoragePartitionImpl*>( frame->GetProcess()->GetStoragePartition()), NativeFileSystemManagerImpl::BindingContext( - frame->GetLastCommittedOrigin(), frame->GetProcess()->GetID(), - frame->GetRoutingID()), + frame->GetLastCommittedOrigin(), frame->GetLastCommittedURL(), + frame->GetProcess()->GetID(), frame->GetRoutingID()), std::move(request)); }, base::Unretained(this)));
diff --git a/content/browser/frame_host/render_widget_host_view_guest.cc b/content/browser/frame_host/render_widget_host_view_guest.cc index b978972..e0b025e 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest.cc
@@ -148,13 +148,9 @@ // The two sizes may fall out of sync if we switch RenderWidgetHostViews, // resize, and then switch page, as is the case with interstitial pages. // NOTE: |guest_| is NULL in unit tests. - if (guest_) { + if (guest_) SetSize(guest_->web_contents()->GetViewBounds().size()); - // Since we were last shown, our renderer may have had a different surface - // set (e.g. showing an interstitial), so we resend our current surface to - // the renderer. - SendSurfaceInfoToEmbedder(); - } + host()->WasShown(base::nullopt /* record_tab_switch_time_request */); } @@ -329,7 +325,6 @@ void RenderWidgetHostViewGuest::OnAttached() { RegisterFrameSinkId(); - SendSurfaceInfoToEmbedder(); } RenderWidgetHostViewBase* RenderWidgetHostViewGuest::GetRootView() {
diff --git a/content/browser/media/session/media_session_impl.cc b/content/browser/media/session/media_session_impl.cc index 67a25c2f..35a7705 100644 --- a/content/browser/media/session/media_session_impl.cc +++ b/content/browser/media/session/media_session_impl.cc
@@ -29,7 +29,6 @@ #include "media/base/media_content_type.h" #include "services/media_session/public/cpp/media_image_manager.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" -#include "third_party/blink/public/mojom/mediasession/media_session.mojom.h" #include "ui/gfx/favicon_size.h" #if defined(OS_ANDROID) @@ -913,6 +912,20 @@ DidReceiveAction(media_session::mojom::MediaSessionAction::kSkipAd); } +void MediaSessionImpl::SeekTo(base::TimeDelta seek_time) { + DidReceiveAction( + media_session::mojom::MediaSessionAction::kSeekTo, + blink::mojom::MediaSessionActionDetails::NewSeekTo( + blink::mojom::MediaSessionSeekToDetails::New(seek_time, false))); +} + +void MediaSessionImpl::ScrubTo(base::TimeDelta seek_time) { + DidReceiveAction( + media_session::mojom::MediaSessionAction::kSeekTo, + blink::mojom::MediaSessionActionDetails::NewSeekTo( + blink::mojom::MediaSessionSeekToDetails::New(seek_time, true))); +} + void MediaSessionImpl::GetMediaImageBitmap( const media_session::MediaImage& image, int minimum_size_px, @@ -1070,6 +1083,12 @@ void MediaSessionImpl::DidReceiveAction( media_session::mojom::MediaSessionAction action) { + DidReceiveAction(action, nullptr /* details */); +} + +void MediaSessionImpl::DidReceiveAction( + media_session::mojom::MediaSessionAction action, + blink::mojom::MediaSessionActionDetailsPtr details) { MediaSessionUmaHelper::RecordMediaSessionUserAction( MediaSessionActionToUserAction(action), focused_); @@ -1108,7 +1127,7 @@ if (!routed_service_) return; - routed_service_->GetClient()->DidReceiveAction(action, nullptr /* details */); + routed_service_->GetClient()->DidReceiveAction(action, std::move(details)); } bool MediaSessionImpl::IsServiceActiveForRenderFrameHost(RenderFrameHost* rfh) { @@ -1195,6 +1214,12 @@ actions.insert(media_session::mojom::MediaSessionAction::kStop); } + // If we support kSeekTo then we support kScrubTo as well. + if (base::Contains(actions, + media_session::mojom::MediaSessionAction::kSeekTo)) { + actions.insert(media_session::mojom::MediaSessionAction::kScrubTo); + } + if (actions_ == actions) return;
diff --git a/content/browser/media/session/media_session_impl.h b/content/browser/media/session/media_session_impl.h index a8cd550..e35ff20 100644 --- a/content/browser/media/session/media_session_impl.h +++ b/content/browser/media/session/media_session_impl.h
@@ -28,6 +28,7 @@ #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote_set.h" #include "services/media_session/public/mojom/audio_focus.mojom.h" +#include "third_party/blink/public/mojom/mediasession/media_session.mojom.h" #if defined(OS_ANDROID) #include "base/android/scoped_java_ref.h" @@ -238,6 +239,12 @@ // Skip ad. CONTENT_EXPORT void SkipAd() override; + // Seek the media session to a specific time. + void SeekTo(base::TimeDelta seek_time) override; + + // Scrub ("fast seek") the media session to a specific time. + void ScrubTo(base::TimeDelta seek_time) override; + // Downloads the bitmap version of a MediaImage at least |minimum_size_px| // and closest to |desired_size_px|. If the download failed, was too small or // the image did not come from the media session then returns a null image. @@ -254,12 +261,6 @@ // Returns whether the action should be routed to |routed_service_|. bool ShouldRouteAction(media_session::mojom::MediaSessionAction action) const; - // Seek the media session to a specific time. - void SeekTo(base::TimeDelta seek_time) override {} - - // Scrub ("fast seek") the media session to a specific time. - void ScrubTo(base::TimeDelta seek_time) override {} - private: friend class content::WebContentsUserData<MediaSessionImpl>; friend class ::MediaSessionImplBrowserTest; @@ -365,6 +366,11 @@ // changed. void RebuildAndNotifyMetadataChanged(); + // Called when a MediaSessionAction is received. The action will be forwarded + // to blink::MediaSession corresponding to the current routed service. + void DidReceiveAction(media_session::mojom::MediaSessionAction action, + blink::mojom::MediaSessionActionDetailsPtr details); + // A set of actions supported by |routed_service_| and the current media // session. std::set<media_session::mojom::MediaSessionAction> actions_;
diff --git a/content/browser/media/session/media_session_impl_service_routing_unittest.cc b/content/browser/media/session/media_session_impl_service_routing_unittest.cc index 31504f5a..3a0169b2 100644 --- a/content/browser/media/session/media_session_impl_service_routing_unittest.cc +++ b/content/browser/media/session/media_session_impl_service_routing_unittest.cc
@@ -582,6 +582,75 @@ } TEST_F(MediaSessionImplServiceRoutingTest, + TestSeekToBehaviorWhenMainFrameIsRouted) { + base::RunLoop run_loop; + + StartPlayerForFrame(main_frame_); + StartPlayerForFrame(sub_frame_); + + CreateServiceForFrame(main_frame_); + + base::TimeDelta seek_time = base::TimeDelta::FromSeconds(10); + + EXPECT_CALL(*GetClientForFrame(main_frame_), + DidReceiveAction(MediaSessionAction::kSeekTo, _)) + .WillOnce([&run_loop, &seek_time](auto a, auto details) { + EXPECT_EQ(seek_time, details->get_seek_to()->seek_time); + EXPECT_FALSE(details->get_seek_to()->fast_seek); + run_loop.Quit(); + }); + + services_[main_frame_]->EnableAction(MediaSessionAction::kSeekTo); + + MediaSessionImpl::Get(contents())->SeekTo(seek_time); + run_loop.Run(); +} + +TEST_F(MediaSessionImplServiceRoutingTest, + TestScrubToBehaviorWhenMainFrameIsRouted) { + base::RunLoop run_loop; + + StartPlayerForFrame(main_frame_); + StartPlayerForFrame(sub_frame_); + + CreateServiceForFrame(main_frame_); + + base::TimeDelta seek_time = base::TimeDelta::FromSeconds(10); + + EXPECT_CALL(*GetClientForFrame(main_frame_), + DidReceiveAction(MediaSessionAction::kSeekTo, _)) + .WillOnce([&run_loop, &seek_time](auto a, auto details) { + EXPECT_EQ(seek_time, details->get_seek_to()->seek_time); + EXPECT_TRUE(details->get_seek_to()->fast_seek); + run_loop.Quit(); + }); + + services_[main_frame_]->EnableAction(MediaSessionAction::kSeekTo); + + MediaSessionImpl::Get(contents())->ScrubTo(seek_time); + run_loop.Run(); +} + +TEST_F(MediaSessionImplServiceRoutingTest, SeekToActionEnablesScrubTo) { + CreateServiceForFrame(main_frame_); + StartPlayerForFrame(main_frame_); + + std::set<MediaSessionAction> expected_actions(default_actions().begin(), + default_actions().end()); + expected_actions.insert(MediaSessionAction::kSeekTo); + expected_actions.insert(MediaSessionAction::kScrubTo); + + services_[main_frame_]->EnableAction(MediaSessionAction::kSeekTo); + + media_session::test::MockMediaSessionMojoObserver observer( + *GetMediaSession()); + observer.WaitForExpectedActions(expected_actions); + + services_[main_frame_]->DisableAction(MediaSessionAction::kSeekTo); + observer.WaitForExpectedActions(default_actions()); +} + +TEST_F(MediaSessionImplServiceRoutingTest, NotifyObserverMetadataWhenControllable) { media_session::MediaMetadata expected_metadata; expected_metadata.title = base::ASCIIToUTF16("title");
diff --git a/content/browser/native_file_system/native_file_system_file_handle_impl_unittest.cc b/content/browser/native_file_system/native_file_system_file_handle_impl_unittest.cc index fbc471e..8930983 100644 --- a/content/browser/native_file_system/native_file_system_file_handle_impl_unittest.cc +++ b/content/browser/native_file_system/native_file_system_file_handle_impl_unittest.cc
@@ -43,15 +43,17 @@ void SetUp() override { ASSERT_TRUE(dir_.CreateUniqueTempDir()); + file_system_context_ = CreateFileSystemContextForTesting( /*quota_manager_proxy=*/nullptr, dir_.GetPath()); - test_url_ = file_system_context_->CreateCrackedFileSystemURL( - GURL("http://example.com"), storage::kFileSystemTypeTest, + test_file_url_ = file_system_context_->CreateCrackedFileSystemURL( + test_src_origin_.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test")); - ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile( - file_system_context_.get(), test_url_)); + ASSERT_EQ(base::File::FILE_OK, + AsyncFileTestHelper::CreateFile(file_system_context_.get(), + test_file_url_)); chrome_blob_context_ = base::MakeRefCounted<ChromeBlobStorageContext>(); chrome_blob_context_->InitializeOnIOThread(base::FilePath(), nullptr); @@ -63,9 +65,9 @@ handle_ = std::make_unique<NativeFileSystemFileHandleImpl>( manager_.get(), NativeFileSystemManagerImpl::BindingContext( - test_url_.origin(), /*process_id=*/1, + test_src_origin_, test_src_url_, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), - test_url_, + test_file_url_, NativeFileSystemManagerImpl::SharedHandleState( allow_grant_, allow_grant_, /*file_system=*/{})); } @@ -91,6 +93,9 @@ } protected: + const GURL test_src_url_ = GURL("http://example.com/foo"); + const url::Origin test_src_origin_ = url::Origin::Create(test_src_url_); + base::test::ScopedFeatureList scoped_feature_list_; TestBrowserThreadBundle scoped_task_environment_; @@ -99,7 +104,7 @@ scoped_refptr<ChromeBlobStorageContext> chrome_blob_context_; scoped_refptr<NativeFileSystemManagerImpl> manager_; - FileSystemURL test_url_; + FileSystemURL test_file_url_; scoped_refptr<FixedNativeFileSystemPermissionGrant> allow_grant_ = base::MakeRefCounted<FixedNativeFileSystemPermissionGrant>( @@ -113,7 +118,7 @@ const FileSystemURL base_swap_url = file_system_context_->CreateCrackedFileSystemURL( - GURL("http://example.com"), storage::kFileSystemTypeTest, + test_src_origin_.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test.crswap")); std::vector<blink::mojom::NativeFileSystemFileWriterPtr> writers; @@ -123,7 +128,7 @@ swap_url = base_swap_url; } else { swap_url = file_system_context_->CreateCrackedFileSystemURL( - GURL("http://example.com"), storage::kFileSystemTypeTest, + test_src_origin_.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe( base::StringPrintf("test.%d.crswap", i))); }
diff --git a/content/browser/native_file_system/native_file_system_file_writer_impl_unittest.cc b/content/browser/native_file_system/native_file_system_file_writer_impl_unittest.cc index 03d01e6..a5b8254e 100644 --- a/content/browser/native_file_system/native_file_system_file_writer_impl_unittest.cc +++ b/content/browser/native_file_system/native_file_system_file_writer_impl_unittest.cc
@@ -46,16 +46,17 @@ file_system_context_ = CreateFileSystemContextForTesting( /*quota_manager_proxy=*/nullptr, dir_.GetPath()); - test_url_ = file_system_context_->CreateCrackedFileSystemURL( - GURL("http://example.com"), storage::kFileSystemTypeTest, + test_file_url_ = file_system_context_->CreateCrackedFileSystemURL( + kTestOrigin.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test")); test_swap_url_ = file_system_context_->CreateCrackedFileSystemURL( - GURL("http://example.com"), storage::kFileSystemTypeTest, + kTestOrigin.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test.crswap")); - ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile( - file_system_context_.get(), test_url_)); + ASSERT_EQ(base::File::FILE_OK, + AsyncFileTestHelper::CreateFile(file_system_context_.get(), + test_file_url_)); ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile(file_system_context_.get(), @@ -72,9 +73,9 @@ handle_ = std::make_unique<NativeFileSystemFileWriterImpl>( manager_.get(), NativeFileSystemManagerImpl::BindingContext( - test_url_.origin(), /*process_id=*/1, + kTestOrigin, kTestURL, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), - test_url_, test_swap_url_, + test_file_url_, test_swap_url_, NativeFileSystemManagerImpl::SharedHandleState( permission_grant_, permission_grant_, /*file_system=*/{})); } @@ -206,6 +207,8 @@ } protected: + const GURL kTestURL = GURL("https://example.com/test"); + const url::Origin kTestOrigin = url::Origin::Create(kTestURL); base::test::ScopedFeatureList scoped_feature_list_; TestBrowserThreadBundle scoped_task_environment_; @@ -215,7 +218,7 @@ storage::BlobStorageContext* blob_context_; scoped_refptr<NativeFileSystemManagerImpl> manager_; - FileSystemURL test_url_; + FileSystemURL test_file_url_; FileSystemURL test_swap_url_; scoped_refptr<FixedNativeFileSystemPermissionGrant> permission_grant_ = @@ -247,7 +250,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ("", ReadFile(test_url_)); + EXPECT_EQ("", ReadFile(test_file_url_)); } TEST_P(NativeFileSystemFileWriterImplWriteTest, WriteValidEmptyString) { @@ -259,7 +262,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ("", ReadFile(test_url_)); + EXPECT_EQ("", ReadFile(test_file_url_)); } TEST_P(NativeFileSystemFileWriterImplWriteTest, WriteValidNonEmpty) { @@ -272,7 +275,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ(test_data, ReadFile(test_url_)); + EXPECT_EQ(test_data, ReadFile(test_file_url_)); } TEST_P(NativeFileSystemFileWriterImplWriteTest, WriteWithOffsetInFile) { @@ -290,7 +293,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ("1234abc890", ReadFile(test_url_)); + EXPECT_EQ("1234abc890", ReadFile(test_file_url_)); } TEST_P(NativeFileSystemFileWriterImplWriteTest, WriteWithOffsetPastFile) { @@ -302,7 +305,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ("", ReadFile(test_url_)); + EXPECT_EQ("", ReadFile(test_file_url_)); } TEST_F(NativeFileSystemFileWriterImplTest, TruncateShrink) { @@ -319,7 +322,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ("12345", ReadFile(test_url_)); + EXPECT_EQ("12345", ReadFile(test_file_url_)); } TEST_F(NativeFileSystemFileWriterImplTest, TruncateGrow) { @@ -336,7 +339,7 @@ result = CloseSync(); EXPECT_EQ(result, base::File::FILE_OK); - EXPECT_EQ(std::string("abc\0\0", 5), ReadFile(test_url_)); + EXPECT_EQ(std::string("abc\0\0", 5), ReadFile(test_file_url_)); } TEST_F(NativeFileSystemFileWriterImplTest, CloseAfterCloseNotOK) {
diff --git a/content/browser/native_file_system/native_file_system_handle_base_unittest.cc b/content/browser/native_file_system/native_file_system_handle_base_unittest.cc index 48e79d7..7e6e5e02 100644 --- a/content/browser/native_file_system/native_file_system_handle_base_unittest.cc +++ b/content/browser/native_file_system/native_file_system_handle_base_unittest.cc
@@ -64,8 +64,8 @@ } protected: - const url::Origin kTestOrigin = - url::Origin::Create(GURL("https://example.com")); + const GURL kTestURL = GURL("https://example.com/test"); + const url::Origin kTestOrigin = url::Origin::Create(kTestURL); base::test::ScopedFeatureList scoped_feature_list_; TestBrowserThreadBundle scoped_task_environment_; @@ -93,7 +93,7 @@ base::FilePath::FromUTF8Unsafe("/test")); TestNativeFileSystemHandle handle(manager_.get(), NativeFileSystemManagerImpl::BindingContext( - kTestOrigin, /*process_id=*/1, + kTestOrigin, kTestURL, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), url, handle_state_); @@ -113,7 +113,7 @@ base::FilePath::FromUTF8Unsafe("/test")); TestNativeFileSystemHandle handle(manager_.get(), NativeFileSystemManagerImpl::BindingContext( - kTestOrigin, /*process_id=*/1, + kTestOrigin, kTestURL, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), url, handle_state_); @@ -133,7 +133,7 @@ base::FilePath::FromUTF8Unsafe("/test")); TestNativeFileSystemHandle handle(manager_.get(), NativeFileSystemManagerImpl::BindingContext( - kTestOrigin, /*process_id=*/1, + kTestOrigin, kTestURL, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), url, handle_state_); @@ -150,7 +150,7 @@ base::FilePath::FromUTF8Unsafe("/test")); TestNativeFileSystemHandle handle(manager_.get(), NativeFileSystemManagerImpl::BindingContext( - kTestOrigin, /*process_id=*/1, + kTestOrigin, kTestURL, /*process_id=*/1, /*frame_id=*/MSG_ROUTING_NONE), url, handle_state_); @@ -176,10 +176,11 @@ auto url = FileSystemURL::CreateForTest(kTestOrigin, storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("/test")); - TestNativeFileSystemHandle handle(manager_.get(), - NativeFileSystemManagerImpl::BindingContext( - kTestOrigin, kProcessId, kFrameId), - url, handle_state_); + TestNativeFileSystemHandle handle( + manager_.get(), + NativeFileSystemManagerImpl::BindingContext(kTestOrigin, kTestURL, + kProcessId, kFrameId), + url, handle_state_); EXPECT_CALL(*read_grant_, GetStatus()) .WillRepeatedly(testing::Return(PermissionStatus::GRANTED));
diff --git a/content/browser/native_file_system/native_file_system_manager_impl_unittest.cc b/content/browser/native_file_system/native_file_system_manager_impl_unittest.cc index 7f844a3..0a9a7ad 100644 --- a/content/browser/native_file_system/native_file_system_manager_impl_unittest.cc +++ b/content/browser/native_file_system/native_file_system_manager_impl_unittest.cc
@@ -63,12 +63,12 @@ } protected: - const url::Origin kTestOrigin = - url::Origin::Create(GURL("https://example.com")); + const GURL kTestURL = GURL("https://example.com/test"); + const url::Origin kTestOrigin = url::Origin::Create(kTestURL); const int kProcessId = 1; const int kFrameId = 2; const NativeFileSystemManagerImpl::BindingContext kBindingContext = { - kTestOrigin, kProcessId, kFrameId}; + kTestOrigin, kTestURL, kProcessId, kFrameId}; base::test::ScopedFeatureList scoped_feature_list_; TestBrowserThreadBundle scoped_task_environment_; @@ -189,7 +189,7 @@ TEST_F(NativeFileSystemManagerImplTest, FileWriterSwapDeletedOnConnectionClose) { - auto test_url = file_system_context_->CreateCrackedFileSystemURL( + auto test_file_url = file_system_context_->CreateCrackedFileSystemURL( kTestOrigin.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test")); @@ -197,15 +197,16 @@ kTestOrigin.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test.crswap")); - ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile( - file_system_context_.get(), test_url)); + ASSERT_EQ(base::File::FILE_OK, + AsyncFileTestHelper::CreateFile(file_system_context_.get(), + test_file_url)); ASSERT_EQ(base::File::FILE_OK, AsyncFileTestHelper::CreateFile(file_system_context_.get(), test_swap_url)); auto writer_ptr = - manager_->CreateFileWriter(kBindingContext, test_url, test_swap_url, + manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url, NativeFileSystemManagerImpl::SharedHandleState( allow_grant_, allow_grant_, {})); @@ -225,7 +226,7 @@ TEST_F(NativeFileSystemManagerImplTest, FileWriterCloseAllowedToCompleteOnDestruct) { - auto test_url = file_system_context_->CreateCrackedFileSystemURL( + auto test_file_url = file_system_context_->CreateCrackedFileSystemURL( kTestOrigin.GetURL(), storage::kFileSystemTypeTest, base::FilePath::FromUTF8Unsafe("test")); @@ -238,13 +239,13 @@ test_swap_url, "foo", 3)); auto writer_ptr = - manager_->CreateFileWriter(kBindingContext, test_url, test_swap_url, + manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url, NativeFileSystemManagerImpl::SharedHandleState( allow_grant_, allow_grant_, {})); ASSERT_TRUE(writer_ptr.is_bound()); ASSERT_FALSE( - AsyncFileTestHelper::FileExists(file_system_context_.get(), test_url, + AsyncFileTestHelper::FileExists(file_system_context_.get(), test_file_url, AsyncFileTestHelper::kDontCheckSize)); writer_ptr->Close(base::DoNothing()); @@ -255,8 +256,8 @@ ASSERT_FALSE( AsyncFileTestHelper::FileExists(file_system_context_.get(), test_swap_url, AsyncFileTestHelper::kDontCheckSize)); - ASSERT_TRUE( - AsyncFileTestHelper::FileExists(file_system_context_.get(), test_url, 3)); + ASSERT_TRUE(AsyncFileTestHelper::FileExists(file_system_context_.get(), + test_file_url, 3)); } } // namespace content
diff --git a/content/browser/portal/portal.cc b/content/browser/portal/portal.cc index 90ee62a6..fe4c3362 100644 --- a/content/browser/portal/portal.cc +++ b/content/browser/portal/portal.cc
@@ -17,6 +17,7 @@ #include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" #include "content/browser/web_contents/web_contents_impl.h" +#include "content/public/browser/render_widget_host_iterator.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/common/content_switches.h" #include "content/public/common/referrer_type_converters.h" @@ -199,6 +200,16 @@ download_policy, "GET", nullptr, "", nullptr, false); } +namespace { +void FlushTouchEventQueues(RenderWidgetHostImpl* host) { + host->input_router()->FlushTouchEventQueue(); + std::unique_ptr<RenderWidgetHostIterator> child_widgets = + host->GetEmbeddedRenderWidgetHosts(); + while (RenderWidgetHost* child_widget = child_widgets->GetNextHost()) + FlushTouchEventQueues(static_cast<RenderWidgetHostImpl*>(child_widget)); +} +} // namespace + void Portal::Activate(blink::TransferableMessage data, ActivateCallback callback) { WebContentsImpl* outer_contents = static_cast<WebContentsImpl*>( @@ -246,8 +257,8 @@ outer_contents_main_frame_view); outer_contents_main_frame_view->CancelActiveTouches(); - outer_contents->GetInputEventRouter()->IgnoreUnackedTouchEvents( - outer_contents_main_frame_view); + FlushTouchEventQueues(outer_contents_main_frame_view->host()); + outer_contents_main_frame_view->Destroy(); }
diff --git a/content/browser/portal/portal_browsertest.cc b/content/browser/portal/portal_browsertest.cc index a5d66d0..68803d1 100644 --- a/content/browser/portal/portal_browsertest.cc +++ b/content/browser/portal/portal_browsertest.cc
@@ -18,6 +18,7 @@ #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/frame.mojom-test-utils.h" #include "content/public/browser/web_contents_delegate.h" +#include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" @@ -242,6 +243,10 @@ ContentBrowserTest::SetUp(); } + void SetUpCommandLine(base::CommandLine* command_line) override { + command_line->AppendSwitch(switches::kValidateInputEventStream); + } + void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); ContentBrowserTest::SetUpOnMainThread(); @@ -859,15 +864,24 @@ std::unique_ptr<SyntheticTapGesture> gesture = std::make_unique<SyntheticTapGesture>(params); - render_widget_host->QueueSyntheticGesture( - std::move(gesture), base::Bind([](SyntheticGesture::Result) {})); + + Portal* predecessor_portal = nullptr; + { + PortalCreatedObserver adoption_observer(portal_frame); + render_widget_host->QueueSyntheticGesture( + std::move(gesture), base::Bind([](SyntheticGesture::Result) {})); + portal_interceptor->WaitForActivate(); + EXPECT_EQ(portal_contents, shell()->web_contents()); + predecessor_portal = adoption_observer.WaitUntilPortalCreated(); + } + + portal_interceptor = PortalInterceptorForTesting::From(predecessor_portal); portal_interceptor->WaitForActivate(); - EXPECT_EQ(portal_contents, shell()->web_contents()); + // Sanity check to see if the predecessor was reactivated. + EXPECT_EQ(web_contents_impl, shell()->web_contents()); // Wait for a touch ack to be sent from the predecessor. input_event_ack_waiter.Wait(); - // Sanity check to see if the predecessor was reactivated. - EXPECT_EQ(web_contents_impl, shell()->web_contents()); } // TODO(crbug.com/985078): Fix on Mac. @@ -952,6 +966,86 @@ } #endif +// TODO(crbug.com/985078): Fix on Mac. +#if !defined(OS_MACOSX) +IN_PROC_BROWSER_TEST_F(PortalBrowserTest, GestureCleanedUpBeforeActivation) { + EXPECT_TRUE(NavigateToURL( + shell(), embedded_test_server()->GetURL("portal.test", "/title1.html"))); + WebContentsImpl* web_contents_impl = + static_cast<WebContentsImpl*>(shell()->web_contents()); + RenderFrameHostImpl* main_frame = web_contents_impl->GetMainFrame(); + + // Create portal and wait for navigation. + Portal* portal = nullptr; + { + PortalCreatedObserver portal_created_observer(main_frame); + GURL a_url(embedded_test_server()->GetURL("a.com", "/title1.html")); + EXPECT_TRUE( + ExecJs(main_frame, + JsReplace("var portal = document.createElement('portal');" + "portal.src = $1;" + "document.body.appendChild(portal);" + "document.body.addEventListener('touchstart', e => {" + " portal.activate();" + "}, {once: true});", + a_url))); + portal = portal_created_observer.WaitUntilPortalCreated(); + } + WebContentsImpl* portal_contents = portal->GetPortalContents(); + + // The portal should not have navigated yet, wait for the first navigation. + TestNavigationObserver navigation_observer(portal_contents); + navigation_observer.Wait(); + + RenderFrameHostImpl* portal_frame = portal_contents->GetMainFrame(); + EXPECT_TRUE(ExecJs(portal_frame, + "window.addEventListener('portalactivate', e => {" + " var portal = e.adoptPredecessor();" + " document.body.appendChild(portal);" + " portal.activate(); " + "});")); + WaitForHitTestData(portal_frame); + + PortalInterceptorForTesting* portal_interceptor = + PortalInterceptorForTesting::From(portal); + RenderWidgetHostImpl* render_widget_host = main_frame->GetRenderWidgetHost(); + + SyntheticTapGestureParams params; + params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; + params.position = gfx::PointF(20, 20); + params.duration_ms = 1; + + // Simulate a tap and activate the portal. + Portal* adopted_portal = nullptr; + { + PortalCreatedObserver adoption_observer(portal_frame); + std::unique_ptr<SyntheticTapGesture> gesture = + std::make_unique<SyntheticTapGesture>(params); + render_widget_host->QueueSyntheticGesture( + std::move(gesture), base::Bind([](SyntheticGesture::Result) {})); + portal_interceptor->WaitForActivate(); + EXPECT_EQ(portal_contents, shell()->web_contents()); + adopted_portal = adoption_observer.WaitUntilPortalCreated(); + } + + // Wait for predecessor to be reactivated. + PortalInterceptorForTesting* adopted_portal_interceptor = + PortalInterceptorForTesting::From(adopted_portal); + adopted_portal_interceptor->WaitForActivate(); + EXPECT_EQ(web_contents_impl, shell()->web_contents()); + + // Simulate another tap. + InputEventAckWaiter input_event_ack_waiter( + render_widget_host, blink::WebInputEvent::Type::kGestureTap); + auto gesture = std::make_unique<SyntheticTapGesture>(params); + render_widget_host->QueueSyntheticGesture( + std::move(gesture), base::Bind([](SyntheticGesture::Result) {})); + // Wait for the tap gesture ack. If the initial gesture wasn't cleaned up, the + // new gesture created will cause an error in the gesture validator. + input_event_ack_waiter.Wait(); +} +#endif + // Tests that the outer FrameTreeNode is deleted after activation. IN_PROC_BROWSER_TEST_F(PortalBrowserTest, FrameDeletedAfterActivation) { EXPECT_TRUE(NavigateToURL(
diff --git a/content/browser/renderer_host/embedded_frame_sink_impl.cc b/content/browser/renderer_host/embedded_frame_sink_impl.cc index d62399e..85a822a 100644 --- a/content/browser/renderer_host/embedded_frame_sink_impl.cc +++ b/content/browser/renderer_host/embedded_frame_sink_impl.cc
@@ -7,7 +7,6 @@ #include <memory> #include <utility> -#include "components/viz/common/features.h" #include "components/viz/host/host_frame_sink_manager.h" #include "components/viz/service/surfaces/surface_manager.h" #include "content/browser/compositor/surface_utils.h" @@ -26,10 +25,7 @@ frame_sink_id_(frame_sink_id) { client_.set_connection_error_handler(std::move(destroy_callback)); host_frame_sink_manager_->RegisterFrameSinkId( - frame_sink_id_, this, - features::IsSurfaceSynchronizationEnabled() - ? viz::ReportFirstSurfaceActivation::kNo - : viz::ReportFirstSurfaceActivation::kYes); + frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo); host_frame_sink_manager_->SetFrameSinkDebugLabel(frame_sink_id_, "EmbeddedFrameSinkImpl"); } @@ -70,13 +66,7 @@ } void EmbeddedFrameSinkImpl::OnFirstSurfaceActivation( - const viz::SurfaceInfo& surface_info) { - DCHECK_EQ(surface_info.id().frame_sink_id(), frame_sink_id_); - - local_surface_id_ = surface_info.id().local_surface_id(); - if (client_) - client_->OnFirstSurfaceActivation(surface_info); -} + const viz::SurfaceInfo& surface_info) {} void EmbeddedFrameSinkImpl::OnFrameTokenChanged(uint32_t frame_token) { // TODO(yiyix, fsamuel): To complete plumbing of frame tokens for offscreen
diff --git a/content/browser/renderer_host/embedded_frame_sink_provider_impl_unittest.cc b/content/browser/renderer_host/embedded_frame_sink_provider_impl_unittest.cc index 0d1d4e4..7ca46308 100644 --- a/content/browser/renderer_host/embedded_frame_sink_provider_impl_unittest.cc +++ b/content/browser/renderer_host/embedded_frame_sink_provider_impl_unittest.cc
@@ -70,10 +70,6 @@ void Close() { binding_.Close(); } - const viz::SurfaceInfo& last_surface_info() const { - return last_surface_info_; - } - const viz::LocalSurfaceId& last_received_local_surface_id() const { return last_received_local_surface_id_; } @@ -82,9 +78,6 @@ private: // blink::mojom::EmbeddedFrameSinkClient: - void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) override { - last_surface_info_ = surface_info; - } void BindSurfaceEmbedder( blink::mojom::SurfaceEmbedderRequest request) override { surface_embedder_binding_.Bind(std::move(request)); @@ -97,7 +90,6 @@ mojo::Binding<blink::mojom::SurfaceEmbedder> surface_embedder_binding_; mojo::Binding<blink::mojom::EmbeddedFrameSinkClient> binding_; - viz::SurfaceInfo last_surface_info_; viz::LocalSurfaceId last_received_local_surface_id_; bool connection_error_ = false;
diff --git a/content/browser/renderer_host/input/input_router.h b/content/browser/renderer_host/input/input_router.h index ff5c10a..49d1684 100644 --- a/content/browser/renderer_host/input/input_router.h +++ b/content/browser/renderer_host/input/input_router.h
@@ -114,6 +114,10 @@ // OOPIF hit-testing will need to wait until updated CompositorFrames have // been submitted to the browser. virtual void WaitForInputProcessed(base::OnceClosure callback) = 0; + + // Acks any pending touch events that are waiting for acks from the renderer. + // Any future acks for those events from the renderer will be ignored. + virtual void FlushTouchEventQueue() = 0; }; } // namespace content
diff --git a/content/browser/renderer_host/input/input_router_impl.cc b/content/browser/renderer_host/input/input_router_impl.cc index b4757203..dbcedc4d 100644 --- a/content/browser/renderer_host/input/input_router_impl.cc +++ b/content/browser/renderer_host/input/input_router_impl.cc
@@ -684,6 +684,10 @@ client_->GetWidgetInputHandler()->WaitForInputProcessed(std::move(callback)); } +void InputRouterImpl::FlushTouchEventQueue() { + touch_event_queue_.FlushQueue(); +} + void InputRouterImpl::ForceSetTouchActionAuto() { touch_action_filter_.AppendToGestureSequenceForDebugging("F"); touch_action_filter_.OnSetTouchAction(cc::kTouchActionAuto);
diff --git a/content/browser/renderer_host/input/input_router_impl.h b/content/browser/renderer_host/input/input_router_impl.h index 14c45147..d9f4da8b 100644 --- a/content/browser/renderer_host/input/input_router_impl.h +++ b/content/browser/renderer_host/input/input_router_impl.h
@@ -112,6 +112,7 @@ void SetMouseCapture(bool capture) override; void OnHasTouchEventHandlers(bool has_handlers) override; void WaitForInputProcessed(base::OnceClosure callback) override; + void FlushTouchEventQueue() override; // Exposed so that tests can swap out the implementation and intercept calls. mojo::Receiver<mojom::WidgetInputHandlerHost>&
diff --git a/content/browser/renderer_host/input/input_router_impl_unittest.cc b/content/browser/renderer_host/input/input_router_impl_unittest.cc index e2d9be2..f4f8f329c 100644 --- a/content/browser/renderer_host/input/input_router_impl_unittest.cc +++ b/content/browser/renderer_host/input/input_router_impl_unittest.cc
@@ -1290,10 +1290,10 @@ EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount()); EXPECT_EQ(1U, GetAndResetDispatchedMessages().size()); - // The remainder of the touch sequence should be dropped. + // The remainder of the touch sequence should be forwarded. ReleaseTouchPoint(0); SendTouchEvent(); - EXPECT_EQ(1U, disposition_handler_->GetAndResetAckCount()); + EXPECT_EQ(0U, disposition_handler_->GetAndResetAckCount()); PressAndSetTouchActionAuto(); EXPECT_EQ(0U, GetAndResetDispatchedMessages().size()); @@ -2067,7 +2067,7 @@ } // Tests that touch event stream validation passes when events are filtered -// out. See crbug.com/581231 for details. +// out. See https://crbug.com/581231 for details. TEST_P(InputRouterImplTest, TouchValidationPassesWithFilteredInputEvents) { // Touch sequence with touch handler. OnHasTouchEventHandlers(true); @@ -2087,11 +2087,11 @@ dispatched_messages[0]->ToEvent()->CallCallback( INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); - // This event will be filtered out, since no consumer exists. + // This event will not be filtered out even though no consumer exists. ReleaseTouchPoint(1); SendTouchEvent(); dispatched_messages = GetAndResetDispatchedMessages(); - EXPECT_EQ(0U, dispatched_messages.size()); + EXPECT_EQ(1U, dispatched_messages.size()); // If the validator didn't see the filtered out release event, it will crash // now, upon seeing a press for a touch which it believes to be still pressed.
diff --git a/content/browser/renderer_host/input/mock_input_router.h b/content/browser/renderer_host/input/mock_input_router.h index a2a5276..1e09ca7 100644 --- a/content/browser/renderer_host/input/mock_input_router.h +++ b/content/browser/renderer_host/input/mock_input_router.h
@@ -52,6 +52,7 @@ void ForceSetTouchActionAuto() override {} void OnHasTouchEventHandlers(bool has_handlers) override; void WaitForInputProcessed(base::OnceClosure callback) override {} + void FlushTouchEventQueue() override {} bool sent_mouse_event_; bool sent_wheel_event_;
diff --git a/content/browser/renderer_host/input/passthrough_touch_event_queue.h b/content/browser/renderer_host/input/passthrough_touch_event_queue.h index 3399455..eca7684 100644 --- a/content/browser/renderer_host/input/passthrough_touch_event_queue.h +++ b/content/browser/renderer_host/input/passthrough_touch_event_queue.h
@@ -50,6 +50,12 @@ // model of the renderer it is possible that an ack for a touchend can // be sent before the corresponding ack for the touchstart. This class // corrects that state. +// +// This class also performs filtering over the sequence of touch-events to, for +// example, avoid sending events to the renderer that would have no effect. By +// default, we always forward touchstart and touchend but, if there are no +// handlers, touchmoves are filtered out of the sequence. The filtering logic +// is implemented in |FilterBeforeForwarding|. class CONTENT_EXPORT PassthroughTouchEventQueue { public: struct CONTENT_EXPORT Config { @@ -114,14 +120,15 @@ void StopTimeoutMonitor(); + // Empties the queue of touch events. This may result in any number of gesture + // events being sent to the renderer. + void FlushQueue(); + protected: void SendTouchCancelEventForTouchEvent( const TouchEventWithLatencyInfo& event_to_cancel); void UpdateTouchConsumerStates(const blink::WebTouchEvent& event, InputEventAckState ack_result); - // Empties the queue of touch events. This may result in any number of gesture - // events being sent to the renderer. - void FlushQueue(); private: friend class InputRouterImplTestBase; @@ -129,13 +136,13 @@ FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, TouchScrollStartedUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, - TouchStartWithoutPageHandlersFiltered); + TouchStartWithoutPageHandlersUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, TouchStartWithPageHandlersUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, TouchMoveFilteredAfterTimeout); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, - TouchMoveWithoutPageHandlersFiltered); + TouchMoveWithoutPageHandlersUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, StationaryTouchMoveFiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, @@ -145,7 +152,7 @@ FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, TouchMoveWithNonTouchMoveUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, - TouchMoveWithoutSequenceHandlerFiltered); + TouchMoveWithoutSequenceHandlerUnfiltered); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, TouchMoveWithoutPageHandlersUnfilteredWithSkipFlag); FRIEND_TEST_ALL_PREFIXES(PassthroughTouchEventQueueTest, @@ -219,7 +226,7 @@ // this is a stricter condition than an empty |touch_consumer_states_|, as it // also prevents forwarding of touchstart events for new pointers in the // current sequence. This is only used when the event is synthetically - // cancelled after a touch timeout. + // cancelled after a touch timeout or before a portal activation. bool drop_remaining_touches_in_sequence_; // Optional handler for timed-out touch event acks.
diff --git a/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc b/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc index 8d51360..631defe 100644 --- a/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc +++ b/content/browser/renderer_host/input/passthrough_touch_event_queue_unittest.cc
@@ -495,36 +495,36 @@ EXPECT_EQ(INPUT_EVENT_ACK_STATE_CONSUMED, acked_event_state()); } -// Tests that addition of a touch handler during a touch sequence will not cause -// the remaining sequence to be forwarded. +// Tests that addition of a touch handler during a touch sequence will continue +// forwarding events. TEST_F(PassthroughTouchEventQueueTest, - ActiveSequenceNotForwardedWhenHandlersAdded) { + ActiveSequenceStillForwardedWhenHandlersAdded) { OnHasTouchEventHandlers(false); // Send a touch-press event while there is no handler. PressTouchPoint(1, 1); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(1U, queued_event_count()); OnHasTouchEventHandlers(true); - // The remaining touch sequence should not be forwarded. + // The remaining touch sequence should be forwarded. MoveTouchPoint(0, 5, 5); ReleaseTouchPoint(0); - EXPECT_EQ(2U, GetAndResetAckedEventCount()); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(0U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(3U, queued_event_count()); - // A new touch sequence should resume forwarding. + // A new touch sequence should continue forwarding. PressTouchPoint(1, 1); - EXPECT_EQ(1U, queued_event_count()); + EXPECT_EQ(4U, queued_event_count()); EXPECT_EQ(1U, GetAndResetSentEventCount()); } -// Tests that removal of a touch handler during a touch sequence will prevent -// the remaining sequence from being forwarded, even if another touch handler is -// registered during the same touch sequence. +// Tests that removal of a touch handler during a touch sequence will not +// prevent the remaining sequence from being forwarded, even if another touch +// handler is registered during the same touch sequence. TEST_F(PassthroughTouchEventQueueTest, ActiveSequenceDroppedWhenHandlersRemoved) { // Send a touch-press event. @@ -543,8 +543,7 @@ EXPECT_EQ(0U, GetAndResetAckedEventCount()); EXPECT_EQ(2U, queued_event_count()); - // Repeated registration/unregstration of handlers should have no effect as - // we're still awaiting the ack arrival. + // Repeated registration/unregstration of handlers should have no effect. OnHasTouchEventHandlers(true); EXPECT_EQ(0U, GetAndResetAckedEventCount()); EXPECT_EQ(2U, queued_event_count()); @@ -552,13 +551,13 @@ EXPECT_EQ(0U, GetAndResetAckedEventCount()); EXPECT_EQ(2U, queued_event_count()); - // clear the queue . + // Clear the queue. SendTouchEventAck(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); SendTouchEventAck(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); EXPECT_EQ(2U, GetAndResetAckedEventCount()); EXPECT_EQ(0U, queued_event_count()); - // Events should be dropped while there is no touch handler. + // TouchMove events should be dropped while there is no touch handler. MoveTouchPoint(0, 10, 10); EXPECT_EQ(0U, queued_event_count()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); @@ -567,15 +566,15 @@ // Simulate touch handler registration in the middle of a touch sequence. OnHasTouchEventHandlers(true); - // The touch end for the interrupted sequence should be dropped. + // The touch end for the interrupted sequence should be sent. ReleaseTouchPoint(0); - EXPECT_EQ(0U, queued_event_count()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); - EXPECT_EQ(0U, GetAndResetSentEventCount()); + EXPECT_EQ(1U, queued_event_count()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); // A new touch sequence should be forwarded properly. PressTouchPoint(1, 1); - EXPECT_EQ(1U, queued_event_count()); + EXPECT_EQ(2U, queued_event_count()); EXPECT_EQ(1U, GetAndResetSentEventCount()); } @@ -626,16 +625,14 @@ EXPECT_EQ(0U, GetAndResetAckedEventCount()); } -// Tests that touch-move events are not sent to the renderer if the preceding -// touch-press event did not have a consumer (and consequently, did not hit the -// main thread in the renderer). +// Tests that touch-move events are not sent to the renderer even if the +// preceding touch-press event did not have a consumer. TEST_F(PassthroughTouchEventQueueTest, NoConsumer) { // The first touch-press should reach the renderer. PressTouchPoint(1, 1); EXPECT_EQ(1U, GetAndResetSentEventCount()); - // The second touch should be sent since we don't know if there is - // a consumer or not. + // The second touch should be sent too. MoveTouchPoint(0, 5, 5); EXPECT_EQ(1U, GetAndResetSentEventCount()); EXPECT_EQ(2U, queued_event_count()); @@ -647,14 +644,13 @@ EXPECT_EQ(2U, GetAndResetAckedEventCount()); EXPECT_EQ(0U, GetAndResetSentEventCount()); - // Send a release event. This should not reach the renderer. + // Send a release event. This should reach the renderer. ReleaseTouchPoint(0); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(WebInputEvent::kTouchEnd, acked_event().GetType()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(WebInputEvent::kTouchMove, acked_event().GetType()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); - // Send a press-event, followed by move a following move should not - // be sent but held in the queue. + // Send a press-event, followed by a move should be sent. PressTouchPoint(10, 10); MoveTouchPoint(0, 5, 5); @@ -665,9 +661,9 @@ MoveTouchPoint(0, 6, 5); EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(0U, GetAndResetAckedEventCount()); - EXPECT_EQ(2U, queued_event_count()); + EXPECT_EQ(3U, queued_event_count()); SendTouchEventAck(INPUT_EVENT_ACK_STATE_CONSUMED); - EXPECT_EQ(2U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetAckedEventCount()); } TEST_F(PassthroughTouchEventQueueTest, AckTouchEventInReverse) { @@ -844,31 +840,32 @@ EXPECT_EQ(WebInputEvent::kTouchMove, acked_event().GetType()); } -// Tests basic TouchEvent forwarding suppression. +// Tests that basic TouchEvent forwarding suppression has been disabled. TEST_F(PassthroughTouchEventQueueTest, NoTouchBasic) { - // Disable TouchEvent forwarding. + // The old behaviour was to suppress events when there were no handlers. + // Signal the no-handler case and test that events still get forwarded. OnHasTouchEventHandlers(false); PressTouchPoint(30, 5); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); // TouchMove should not be sent to renderer. MoveTouchPoint(0, 65, 10); EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); - // TouchEnd should not be sent to renderer. + // TouchEnd should be sent to renderer. ReleaseTouchPoint(0); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); - // Enable TouchEvent forwarding. + // Signal handlers-present and make sure events are still getting forwarded. OnHasTouchEventHandlers(true); PressTouchPoint(80, 10); EXPECT_EQ(1U, GetAndResetSentEventCount()); SendTouchEventAck(INPUT_EVENT_ACK_STATE_NOT_CONSUMED); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(2U, GetAndResetAckedEventCount()); MoveTouchPoint(0, 80, 20); EXPECT_EQ(1U, GetAndResetSentEventCount()); @@ -1172,23 +1169,23 @@ EXPECT_EQ(1U, GetAndResetSentEventCount()); EXPECT_EQ(0U, GetAndResetAckedEventCount()); - // Ack the cancel event. Normally, this would resume touch forwarding, + // Ack the cancel event. Normally, this would resume touch forwarding, // but we're still within a scroll gesture so it remains disabled. SendTouchEventAck(INPUT_EVENT_ACK_STATE_CONSUMED); EXPECT_FALSE(IsTimeoutRunning()); EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(0U, GetAndResetAckedEventCount()); - // Try to forward touch events for the current sequence. + // Forward touch events for the current sequence. GetAndResetSentEventCount(); GetAndResetAckedEventCount(); MoveTouchPoint(0, 1, 1); ReleaseTouchPoint(0); EXPECT_FALSE(IsTimeoutRunning()); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(2U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(1U, GetAndResetAckedEventCount()); - // Now end the scroll sequence, resuming touch handling. + // Now end the scroll sequence. SendGestureEvent(blink::WebInputEvent::kGestureScrollEnd); PressTouchPoint(0, 1); EXPECT_TRUE(IsTimeoutRunning()); @@ -1385,7 +1382,7 @@ ASSERT_EQ(1U, GetAndResetSentEventCount()); ASSERT_EQ(1U, GetAndResetAckedEventCount()); - // Events should not be forwarded, as the point had no consumer. + // TouchMove events should not be forwarded, as the point had no consumer. MoveTouchPoint(0, 0, 15); EXPECT_EQ(0U, queued_event_count()); EXPECT_EQ(0U, GetAndResetSentEventCount()); @@ -1566,11 +1563,11 @@ EXPECT_EQ(0U, GetAndResetSentEventCount()); EXPECT_EQ(1U, GetAndResetAckedEventCount()); - // Give the touchmove a valid id after release it shouldn't be sent. + // Give the touchmove a valid id after release; it should be sent. event.touches[0].id = press_id; SendTouchEvent(event); - EXPECT_EQ(0U, GetAndResetSentEventCount()); - EXPECT_EQ(1U, GetAndResetAckedEventCount()); + EXPECT_EQ(1U, GetAndResetSentEventCount()); + EXPECT_EQ(0U, GetAndResetAckedEventCount()); } // Tests that touch points states are correct in TouchMove events. @@ -1795,14 +1792,14 @@ FilterBeforeForwarding(event)); } -TEST_F(PassthroughTouchEventQueueTest, TouchStartWithoutPageHandlersFiltered) { +TEST_F(PassthroughTouchEventQueueTest, + TouchStartWithoutPageHandlersUnfiltered) { OnHasTouchEventHandlers(false); SyntheticWebTouchEvent event; event.PressPoint(1, 1); - EXPECT_EQ( - PassthroughTouchEventQueue::PreFilterResult::kFilteredNoPageHandlers, - FilterBeforeForwarding(event)); + EXPECT_EQ(PassthroughTouchEventQueue::PreFilterResult::kUnfiltered, + FilterBeforeForwarding(event)); } TEST_F(PassthroughTouchEventQueueTest, TouchStartWithPageHandlersUnfiltered) { @@ -1831,7 +1828,7 @@ FilterBeforeForwarding(event)); } -TEST_F(PassthroughTouchEventQueueTest, TouchMoveWithoutPageHandlersFiltered) { +TEST_F(PassthroughTouchEventQueueTest, TouchMoveWithoutPageHandlersUnfiltered) { OnHasTouchEventHandlers(false); // Start the touch sequence. PressTouchPoint(1, 1); @@ -1912,7 +1909,7 @@ } TEST_F(PassthroughTouchEventQueueTest, - TouchMoveWithoutSequenceHandlerFiltered) { + TouchMoveWithoutSequenceHandlerUnfiltered) { OnHasTouchEventHandlers(true); // Start the touch sequence. PressTouchPoint(1, 1); @@ -1920,7 +1917,7 @@ // Send an ack indicating that there's no handler for the current sequence. SendTouchEventAck(INPUT_EVENT_ACK_STATE_NO_CONSUMER_EXISTS); - // Any subsequent touches in the sequence should be filtered. + // Any subsequent touches in the sequence should be unfiltered. SyntheticWebTouchEvent event; int id = event.PressPoint(1, 1); event.MovePoint(id, 3, 3);
diff --git a/content/browser/renderer_host/render_view_host_impl.cc b/content/browser/renderer_host/render_view_host_impl.cc index f81232a..0cda89d4 100644 --- a/content/browser/renderer_host/render_view_host_impl.cc +++ b/content/browser/renderer_host/render_view_host_impl.cc
@@ -266,7 +266,12 @@ GetWidget()->GetRoutingID()); } + // Destroy the RenderWidgetHost. GetWidget()->ShutdownAndDestroyWidget(false); + if (IsRenderViewLive()) { + // Destroy the RenderView, which will also destroy the RenderWidget. + GetProcess()->GetRendererInterface()->DestroyView(GetRoutingID()); + } ui::GpuSwitchingManager::GetInstance()->RemoveObserver(this); @@ -373,6 +378,9 @@ GetWidget()->GetVisualProperties(¶ms->visual_properties, &needs_ack); GetWidget()->SetInitialVisualProperties(params->visual_properties, needs_ack); + // The RenderView is owned by this process. This call must be accompanied by a + // DestroyView [see destructor] or else there will be a leak in the renderer + // process. GetProcess()->GetRendererInterface()->CreateView(std::move(params)); // Let our delegate know that we created a RenderView.
diff --git a/content/browser/renderer_host/render_widget_host_browsertest.cc b/content/browser/renderer_host/render_widget_host_browsertest.cc index 4d86c87..185347a 100644 --- a/content/browser/renderer_host/render_widget_host_browsertest.cc +++ b/content/browser/renderer_host/render_widget_host_browsertest.cc
@@ -92,7 +92,8 @@ private: EventTypeVector dispatched_events_; - blink::WebInputEvent::Type acked_touch_event_type_; + blink::WebInputEvent::Type acked_touch_event_type_ = + blink::WebInputEvent::Type::kUndefined; }; class RenderWidgetHostTouchEmulatorBrowserTest : public ContentBrowserTest { @@ -137,6 +138,11 @@ router_->RouteMouseEvent(view_, &event, ui::LatencyInfo()); } + void WaitForAckWith(blink::WebInputEvent::Type type) { + InputMsgWatcher watcher(host(), type); + watcher.GetAckStateWaitIfNecessary(); + } + RenderWidgetHostImpl* host() { return host_; } private: @@ -145,7 +151,7 @@ RenderWidgetHostInputEventRouter* router_; base::TimeTicks last_simulated_event_time_; - base::TimeDelta simulated_event_time_delta_; + const base::TimeDelta simulated_event_time_delta_; }; // Synthetic mouse events not allowed on Android. @@ -211,8 +217,6 @@ IN_PROC_BROWSER_TEST_F(RenderWidgetHostTouchEmulatorBrowserTest, TouchEmulator) { - // All touches will be immediately acked instead of sending them to the - // renderer since the test page does not have a touch handler. host()->GetTouchEmulator()->Enable( TouchEmulator::Mode::kEmulatingTouchFromMouse, ui::GestureProviderConfigType::GENERIC_MOBILE); @@ -220,6 +224,8 @@ TestInputEventObserver observer; host()->AddInputEventObserver(&observer); + // Simulate a mouse move without any pressed buttons. This should not + // generate any touch events. SimulateRoutedMouseEvent(blink::WebInputEvent::kMouseMove, 10, 10, 0, false); TestInputEventObserver::EventTypeVector dispatched_events = observer.GetAndResetDispatchedEventTypes(); @@ -227,6 +233,7 @@ // Mouse press becomes touch start which in turn becomes tap. SimulateRoutedMouseEvent(blink::WebInputEvent::kMouseDown, 10, 10, 0, true); + WaitForAckWith(blink::WebInputEvent::kTouchStart); EXPECT_EQ(blink::WebInputEvent::kTouchStart, observer.acked_touch_event_type()); dispatched_events = observer.GetAndResetDispatchedEventTypes(); @@ -300,6 +307,7 @@ // Another mouse down continues scroll. SimulateRoutedMouseEvent(blink::WebInputEvent::kMouseDown, 10, 80, 0, true); + WaitForAckWith(blink::WebInputEvent::kTouchStart); EXPECT_EQ(blink::WebInputEvent::kTouchStart, observer.acked_touch_event_type()); dispatched_events = observer.GetAndResetDispatchedEventTypes(); @@ -359,6 +367,7 @@ // Another touch. SimulateRoutedMouseEvent(blink::WebInputEvent::kMouseDown, 10, 10, 0, true); + WaitForAckWith(blink::WebInputEvent::kTouchStart); EXPECT_EQ(blink::WebInputEvent::kTouchStart, observer.acked_touch_event_type()); dispatched_events = observer.GetAndResetDispatchedEventTypes();
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 0ccc622..5f9c72d 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -599,8 +599,10 @@ CancelKeyboardLock(); RejectMouseLockOrUnlockIfNecessary(); - if (process_->IsInitializedAndNotDead()) { - // Tell the RendererWidget to close. + if (process_->IsInitializedAndNotDead() && !owner_delegate()) { + // Tell the RendererWidget to close. We only want to do this if the + // RenderWidget is the root of the renderer object graph, which is for + // pepper fullscreen and popups. bool rv = Send(new WidgetMsg_Close(routing_id_)); DCHECK(rv); } @@ -2686,26 +2688,13 @@ auto* input_event_router = delegate() ? delegate()->GetInputEventRouter() : nullptr; - auto it = touch_event_acks_to_ignore_.find(event.event.unique_touch_event_id); - if (it != touch_event_acks_to_ignore_.end()) { - touch_event_acks_to_ignore_.erase(it); - return; - } - - // With portals, if a touch event triggers an activation, it is possible to - // receive a touch ack after activation. The view is destroyed on activation - // and any pending events in the touch ack queue have already been cleared, so - // we just ignore this ack. - if (!view_) - return; - // At present interstitial pages might not have an input event router, so we // just have the view process the ack directly in that case; the view is // guaranteed to be a top-level view with an appropriate implementation of // ProcessAckedTouchEvent(). if (input_event_router) input_event_router->ProcessAckedTouchEvent(event, ack_result, view_.get()); - else + else if (view_) view_->ProcessAckedTouchEvent(event, ack_result); } @@ -3120,12 +3109,6 @@ return rvh->CollectSurfaceIdsForEviction(); } -void RenderWidgetHostImpl::IgnoreTouchEventAcks( - const std::unordered_set<uint32_t>& acks_to_ignore) { - touch_event_acks_to_ignore_.insert(acks_to_ignore.begin(), - acks_to_ignore.end()); -} - std::unique_ptr<RenderWidgetHostIterator> RenderWidgetHostImpl::GetEmbeddedRenderWidgetHosts() { // This iterates over all RenderWidgetHosts and returns those whose Views
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index cf54a5f..f16ebcf4d 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -120,6 +120,34 @@ // This implements the RenderWidgetHost interface that is exposed to // embedders of content, and adds things only visible to content. +// +// Several core rendering primitives are mirrored between the browser and +// renderer. These are RenderWidget, RenderFrame and RenderView. Their browser +// counterparts are RenderWidgetHost, RenderFrameHost and RenderViewHost. +// +// For simplicity and clarity, we want the object ownership graph in the +// renderer to mirror the object ownership graph in the browser. The IPC message +// that tears down the renderer object graph should be targeted at the root +// object, and should be sent by the destructor/finalizer of the root object in +// the browser. +// +// Note: We must tear down the renderer object graph with a single IPC to avoid +// inconsistencies in renderer state. +// +// RenderWidget represents a surface that can paint and receive input. It is +// used in four contexts: +// * Main frame for webpage +// * Child frame for webpage +// * Popups +// * Pepper Fullscreen +// +// In the first two cases, the RenderFrame is not the root of the renderer +// object graph. For the main frame, the root is the RenderView. For child +// frames, the root is RenderFrame. As such, for the first two cases, +// destruction of the RenderWidgetHost will not trigger destruction of the +// RenderWidget. +// +// Note: We want to converge on RenderFrame always being the root. class CONTENT_EXPORT RenderWidgetHostImpl : public RenderWidgetHost, public FrameTokenMessageQueue::Client, @@ -742,10 +770,6 @@ // Marks all views in the frame tree as evicted. std::vector<viz::SurfaceId> CollectSurfaceIdsForEviction(); - // Ignore any future TouchEvent acks that have an event ID that is in - // |acks_to_ignore|. - void IgnoreTouchEventAcks(const std::unordered_set<uint32_t>& acks_to_ignore); - protected: // --------------------------------------------------------------------------- // The following method is overridden by RenderViewHost to send upwards to @@ -969,6 +993,8 @@ RenderWidgetHostDelegate* delegate_; // The delegate of the owner of this object. + // This member is non-null if and only if this RenderWidgetHost is associated + // with a main frame RenderWidget. RenderWidgetHostOwnerDelegate* owner_delegate_ = nullptr; // Created during construction and guaranteed never to be NULL, but its @@ -1205,9 +1231,6 @@ // necessarily sent yet. bool autoscroll_in_progress_ = false; - // Event IDs for touch event acks that should be ignored. - std::unordered_set<uint32_t> touch_event_acks_to_ignore_; - base::WeakPtrFactory<RenderWidgetHostImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostImpl);
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 8389fbd..dd85b56 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -121,9 +121,6 @@ void UpdateQueueAfterTargetDestroyed(RenderWidgetHostViewBase* target_view); - std::vector<AckData> GetQueueEntriesForRootView( - RenderWidgetHostViewBase* root_view) const; - size_t length_for_testing() { return ack_queue_.size(); } private: @@ -235,17 +232,6 @@ ProcessAckedTouchEvents(); } -std::vector<TouchEventAckQueue::AckData> -TouchEventAckQueue::GetQueueEntriesForRootView( - RenderWidgetHostViewBase* root_view) const { - std::vector<TouchEventAckQueue::AckData> acks; - for (const auto& data : ack_queue_) { - if (data.root_view == root_view) - acks.push_back(data); - } - return acks; -} - RenderWidgetHostInputEventRouter::TouchscreenPinchState::TouchscreenPinchState() : state_(PinchState::NONE) {} @@ -349,22 +335,6 @@ return owner_map_.size(); } -void RenderWidgetHostInputEventRouter::IgnoreUnackedTouchEvents( - RenderWidgetHostViewBase* root_view) { - DCHECK(!root_view->IsRenderWidgetHostViewChildFrame()); - std::vector<TouchEventAckQueue::AckData> acks = - touch_event_ack_queue_->GetQueueEntriesForRootView(root_view); - std::map<RenderWidgetHostViewBase*, std::unordered_set<uint32_t>> - events_for_target; - for (auto& ack : acks) { - events_for_target[ack.target_view].insert( - ack.touch_event.event.unique_touch_event_id); - } - for (auto& pair : events_for_target) { - pair.first->host()->IgnoreTouchEventAcks(pair.second); - } -} - void RenderWidgetHostInputEventRouter::OnRenderWidgetHostViewBaseDestroyed( RenderWidgetHostViewBase* view) { // RenderWidgetHostViewBase::RemoveObserver() should only ever be called
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 3eee383..f6168c3 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -189,12 +189,6 @@ route_to_root_for_devtools_ = route; } - // Makes the appropriate RenderWidgetHosts ignore touch acks for events - // rooted at |root_view| that are pending acks. This is used when we replace - // the view of a RenderWidgetHost with a new view and should be called before - // destroying the old view. - void IgnoreUnackedTouchEvents(RenderWidgetHostViewBase* root_view); - private: FRIEND_TEST_ALL_PREFIXES(BrowserSideFlingBrowserTest, InertialGSUBubblingStopsWhenParentCannotScroll);
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 b90ab4a..08a0871 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
@@ -1477,13 +1477,14 @@ ui::ET_TOUCH_RELEASED, gfx::Point(20, 20), ui::EventTimeForNow(), ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, 0)); - // The touch events should get forwarded from the view, but they should not - // reach the renderer. + // The touch events should get forwarded from the view but only the discrete + // events should make it all the way to the renderer. view_->OnTouchEvent(&press); base::RunLoop().RunUntilIdle(); MockWidgetInputHandler::MessageVector events = GetAndResetDispatchedMessages(); - EXPECT_EQ(0U, events.size()); + EXPECT_EQ(1U, events.size()); + EXPECT_EQ("TouchStart", GetMessageNames(events)); EXPECT_TRUE(press.synchronous_handling_disabled()); EXPECT_EQ(ui::MotionEvent::Action::DOWN, pointer_state().GetAction()); @@ -1498,7 +1499,8 @@ view_->OnTouchEvent(&release); base::RunLoop().RunUntilIdle(); events = GetAndResetDispatchedMessages(); - EXPECT_EQ(0U, events.size()); + EXPECT_EQ(1U, events.size()); + EXPECT_EQ("TouchEnd", GetMessageNames(events)); EXPECT_TRUE(press.synchronous_handling_disabled()); EXPECT_EQ(0U, pointer_state().GetPointerCount()); @@ -1562,7 +1564,8 @@ EXPECT_TRUE(press.synchronous_handling_disabled()); EXPECT_EQ(0U, pointer_state().GetPointerCount()); events = GetAndResetDispatchedMessages(); - EXPECT_EQ(0U, events.size()); + EXPECT_EQ(1U, events.size()); + EXPECT_EQ("TouchEnd", GetMessageNames(events)); } // The DOM KeyCode map for Fuchsia maps all DomCodes to 0. This means that
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc index fbb86a38..5b25482 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc
@@ -66,14 +66,9 @@ base::checked_cast<uint32_t>(widget_host->GetProcess()->GetID()), base::checked_cast<uint32_t>(widget_host->GetRoutingID())), frame_connector_(nullptr), - enable_viz_(features::IsVizDisplayCompositorEnabled()), - enable_surface_synchronization_( - features::IsSurfaceSynchronizationEnabled()) { + enable_viz_(features::IsVizDisplayCompositorEnabled()) { GetHostFrameSinkManager()->RegisterFrameSinkId( - frame_sink_id_, this, - enable_surface_synchronization_ - ? viz::ReportFirstSurfaceActivation::kNo - : viz::ReportFirstSurfaceActivation::kYes); + frame_sink_id_, this, viz::ReportFirstSurfaceActivation::kNo); GetHostFrameSinkManager()->SetFrameSinkDebugLabel( frame_sink_id_, "RenderWidgetHostViewChildFrame"); CreateCompositorFrameSinkSupport(); @@ -156,8 +151,6 @@ manager->AddObserver(this); } } - - SendSurfaceInfoToEmbedder(); } void RenderWidgetHostViewChildFrame::UpdateIntrinsicSizingInfo( @@ -590,14 +583,6 @@ } } -void RenderWidgetHostViewChildFrame::SendSurfaceInfoToEmbedder() { - if (enable_surface_synchronization_) - return; - if (!last_activated_surface_info_.is_valid()) - return; - FirstSurfaceActivation(last_activated_surface_info_); -} - void RenderWidgetHostViewChildFrame::FirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { if (frame_connector_) @@ -728,10 +713,8 @@ } viz::SurfaceId RenderWidgetHostViewChildFrame::GetCurrentSurfaceId() const { - return enable_surface_synchronization_ - ? viz::SurfaceId(frame_sink_id_, - GetLocalSurfaceIdAllocation().local_surface_id()) - : last_activated_surface_info_.id(); + return viz::SurfaceId(frame_sink_id_, + GetLocalSurfaceIdAllocation().local_surface_id()); } bool RenderWidgetHostViewChildFrame::HasSize() const { @@ -884,14 +867,7 @@ } void RenderWidgetHostViewChildFrame::OnFirstSurfaceActivation( - const viz::SurfaceInfo& surface_info) { - if (enable_surface_synchronization_) { - NOTREACHED(); - return; - } - last_activated_surface_info_ = surface_info; - FirstSurfaceActivation(surface_info); -} + const viz::SurfaceInfo& surface_info) {} void RenderWidgetHostViewChildFrame::OnFrameTokenChanged(uint32_t frame_token) { OnFrameTokenChangedForView(frame_token);
diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h index b88f2c73..de59a7bd 100644 --- a/content/browser/renderer_host/render_widget_host_view_child_frame.h +++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h
@@ -241,8 +241,6 @@ // parent was already set then it also unregisters hierarchy. void SetParentFrameSinkId(const viz::FrameSinkId& parent_frame_sink_id); - void SendSurfaceInfoToEmbedder(); - // Clears current compositor surface, if one is in use. void ClearCompositorSurfaceIfNecessary(); @@ -305,7 +303,6 @@ viz::FrameSinkId parent_frame_sink_id_; const bool enable_viz_; - const bool enable_surface_synchronization_; viz::mojom::CompositorFrameSinkClient* renderer_compositor_frame_sink_ = nullptr;
diff --git a/content/browser/renderer_interface_binders.cc b/content/browser/renderer_interface_binders.cc index cfdfae7..8671f63 100644 --- a/content/browser/renderer_interface_binders.cc +++ b/content/browser/renderer_interface_binders.cc
@@ -171,8 +171,13 @@ // RenderFrameHostImpl instead. NativeFileSystemManagerImpl::BindRequestFromUIThread( static_cast<StoragePartitionImpl*>(host->GetStoragePartition()), - NativeFileSystemManagerImpl::BindingContext(origin, host->GetID(), - MSG_ROUTING_NONE), + NativeFileSystemManagerImpl::BindingContext( + origin, + // TODO(https://crbug.com/989323): Obtain and use a better URL + // for workers instead of the origin as source url. This URL + // will be used for SafeBrowsing checks and for the Quarantine + // Service. + origin.GetURL(), host->GetID(), MSG_ROUTING_NONE), std::move(request)); })); }
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc index e825653..174c92b3 100644 --- a/content/browser/service_worker/embedded_worker_instance.cc +++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -137,15 +137,15 @@ factory_bundle_for_renderer; if (!process_manager) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce( - std::move(callback), blink::ServiceWorkerStatusCode::kErrorAbort, - std::move(params), std::move(process_info), - std::move(devtools_proxy), - std::move(factory_bundle_for_new_scripts), - std::move(factory_bundle_for_renderer), nullptr /* cache_storage */, - thread_hop_time, base::Time::Now())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), + blink::ServiceWorkerStatusCode::kErrorAbort, + std::move(params), std::move(process_info), + std::move(devtools_proxy), + std::move(factory_bundle_for_new_scripts), + std::move(factory_bundle_for_renderer), + nullptr /* cache_storage */, thread_hop_time, + base::Time::Now())); return; } @@ -155,7 +155,7 @@ embedded_worker_id, params->script_url, can_use_existing_process, process_info.get()); if (status != blink::ServiceWorkerStatusCode::kOk) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), status, std::move(params), std::move(process_info), std::move(devtools_proxy), @@ -245,7 +245,7 @@ process_manager->browser_context(), std::move(watcher_ptr)); // Continue to OnSetupCompleted on the IO thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), status, std::move(params), std::move(process_info), std::move(devtools_proxy), @@ -296,8 +296,7 @@ DevToolsProxy(int process_id, int agent_route_id) : process_id_(process_id), agent_route_id_(agent_route_id), - ui_task_runner_( - base::CreateSequencedTaskRunnerWithTraits({BrowserThread::UI})) {} + ui_task_runner_(base::CreateSequencedTaskRunner({BrowserThread::UI})) {} ~DevToolsProxy() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); @@ -741,8 +740,7 @@ devtools_attached_(false), network_accessed_for_script_(false), foreground_notified_(false), - ui_task_runner_( - base::CreateSequencedTaskRunnerWithTraits({BrowserThread::UI})) { + ui_task_runner_(base::CreateSequencedTaskRunner({BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(context_); }
diff --git a/content/browser/service_worker/embedded_worker_test_helper.cc b/content/browser/service_worker/embedded_worker_test_helper.cc index 8698fcc4..e187617 100644 --- a/content/browser/service_worker/embedded_worker_test_helper.cc +++ b/content/browser/service_worker/embedded_worker_test_helper.cc
@@ -40,6 +40,7 @@ NOTREACHED(); } void CreateView(mojom::CreateViewParamsPtr) override { NOTREACHED(); } + void DestroyView(int32_t) override { NOTREACHED(); } void CreateFrame(mojom::CreateFrameParamsPtr) override { NOTREACHED(); } void SetUpEmbeddedWorkerChannelForServiceWorker( blink::mojom::EmbeddedWorkerInstanceClientRequest client_request)
diff --git a/content/browser/service_worker/payment_handler_support.cc b/content/browser/service_worker/payment_handler_support.cc index 9e2874c6..54a3c21 100644 --- a/content/browser/service_worker/payment_handler_support.cc +++ b/content/browser/service_worker/payment_handler_support.cc
@@ -50,7 +50,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (response_callback_) { DCHECK(fallback_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(fallback_), std::move(response_callback_))); } @@ -58,7 +58,7 @@ void Run(bool success, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback_), std::move(response_callback_), success, render_process_id, render_frame_id)); @@ -100,12 +100,11 @@ response_callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(context); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ShowPaymentHandlerWindowOnUI, - base::WrapRefCounted(context->wrapper()), url, - std::move(callback), std::move(fallback), - std::move(response_callback))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ShowPaymentHandlerWindowOnUI, + base::WrapRefCounted(context->wrapper()), url, + std::move(callback), std::move(fallback), + std::move(response_callback))); } } // namespace content
diff --git a/content/browser/service_worker/service_worker_browsertest.cc b/content/browser/service_worker/service_worker_browsertest.cc index dfe8ced..a92bb267 100644 --- a/content/browser/service_worker/service_worker_browsertest.cc +++ b/content/browser/service_worker/service_worker_browsertest.cc
@@ -126,7 +126,7 @@ void RunOnIOThreadWithDelay(base::OnceClosure closure, base::TimeDelta delay) { base::RunLoop run_loop; - base::PostDelayedTaskWithTraits( + base::PostDelayedTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&RunAndQuit, std::move(closure), run_loop.QuitClosure(), base::RetainedRef(base::ThreadTaskRunnerHandle::Get())), @@ -141,7 +141,7 @@ void RunOnIOThread( base::OnceCallback<void(base::OnceClosure continuation)> callback) { base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( std::move(callback), @@ -168,7 +168,7 @@ scoped_refptr<ServiceWorkerRegistration> registration) { *out_status = status; if (!quit.is_null()) - base::PostTaskWithTraits(FROM_HERE, {run_quit_thread}, std::move(quit)); + base::PostTask(FROM_HERE, {run_quit_thread}, std::move(quit)); } ServiceWorkerStorage::FindRegistrationCallback CreateFindRegistrationReceiver( @@ -216,9 +216,8 @@ context_->RemoveObserver(this); version_id_ = version_id; registration_id_ = version->registration_id(); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&WorkerActivatedObserver::Quit, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&WorkerActivatedObserver::Quit, this)); } } void Wait() { run_loop_.Run(); } @@ -512,10 +511,9 @@ int line_number, const GURL& source_url) override { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ConsoleListener::OnReportConsoleMessageOnUI, - base::Unretained(this), message)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ConsoleListener::OnReportConsoleMessageOnUI, + base::Unretained(this), message)); } void WaitForConsoleMessages(size_t expected_message_count) { @@ -619,7 +617,7 @@ // Dispatch install on a worker. base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop install_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::InstallOnIOThread, base::Unretained(this), install_run_loop.QuitClosure(), &status)); @@ -628,17 +626,16 @@ // Stop the worker. base::RunLoop stop_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StopOnIOThread, base::Unretained(this), - stop_run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StopOnIOThread, base::Unretained(this), + stop_run_loop.QuitClosure())); stop_run_loop.Run(); } void ActivateTestHelper(blink::ServiceWorkerStatusCode expected_status) { base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::ActivateOnIOThread, base::Unretained(this), run_loop.QuitClosure(), &status)); @@ -657,7 +654,7 @@ FetchResult fetch_result; fetch_result.status = blink::ServiceWorkerStatusCode::kErrorFailed; base::RunLoop fetch_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::FetchOnIOThread, base::Unretained(this), fetch_run_loop.QuitClosure(), path, &prepare_result, @@ -736,7 +733,7 @@ ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop start_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::StartOnIOThread, base::Unretained(this), start_run_loop.QuitClosure(), &status)); @@ -747,10 +744,9 @@ void StopWorker() { ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::RunLoop stop_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StopOnIOThread, base::Unretained(this), - stop_run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StopOnIOThread, base::Unretained(this), + stop_run_loop.QuitClosure())); stop_run_loop.Run(); } @@ -759,7 +755,7 @@ ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop store_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::StoreOnIOThread, base::Unretained(this), store_run_loop.QuitClosure(), &status, version_id)); @@ -775,7 +771,7 @@ blink::ServiceWorkerStatusCode* out_status, bool* out_update_found) { base::RunLoop update_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &self::UpdateOnIOThread, base::Unretained(this), registration_id, @@ -792,11 +788,10 @@ blink::ServiceWorkerStatusCode status = blink::ServiceWorkerStatusCode::kErrorFailed; base::RunLoop run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::FindRegistrationForIdOnIOThread, - base::Unretained(this), run_loop.QuitClosure(), &status, - id, origin)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::FindRegistrationForIdOnIOThread, + base::Unretained(this), + run_loop.QuitClosure(), &status, id, origin)); run_loop.Run(); ASSERT_EQ(expected_status, status); } @@ -871,7 +866,7 @@ *out_result = mojo::ConvertTo<blink::ServiceWorkerStatusCode>(status); if (!done.is_null()) - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(done)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(done)); } void StoreOnIOThread(base::OnceClosure done, @@ -933,7 +928,7 @@ *out_status = status; *out_update_found = !!registration->installing_version(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, done_on_ui); + base::PostTask(FROM_HERE, {BrowserThread::UI}, done_on_ui); } void FetchOnIOThread(base::OnceClosure done, @@ -959,7 +954,7 @@ base::Time GetLastUpdateCheck(int64_t registration_id) { base::Time last_update_time; base::RunLoop time_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::GetLastUpdateCheckOnIOThread, base::Unretained(this), registration_id, @@ -976,7 +971,7 @@ wrapper()->context()->GetLiveRegistration(registration_id); ASSERT_TRUE(registration); *out_time = registration->last_update_check(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, done_on_ui); + base::PostTask(FROM_HERE, {BrowserThread::UI}, done_on_ui); } void SetLastUpdateCheckOnIOThread(int64_t registration_id, @@ -987,7 +982,7 @@ wrapper()->context()->GetLiveRegistration(registration_id); ASSERT_TRUE(registration); registration->set_last_update_check(last_update_time); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, done_on_ui); + base::PostTask(FROM_HERE, {BrowserThread::UI}, done_on_ui); } // Contrary to the style guide, the output parameter of this function comes @@ -1016,7 +1011,7 @@ out_result->response->blob->uuid); } if (!quit.is_null()) - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(quit)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(quit)); } ServiceWorkerFetchDispatcher::FetchCallback CreateResponseReceiver( @@ -1065,19 +1060,17 @@ // Start a worker. base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop start_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StartOnIOThread, base::Unretained(this), - start_run_loop.QuitClosure(), &status)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StartOnIOThread, base::Unretained(this), + start_run_loop.QuitClosure(), &status)); start_run_loop.Run(); ASSERT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value()); // Stop the worker. base::RunLoop stop_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StopOnIOThread, base::Unretained(this), - stop_run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StopOnIOThread, base::Unretained(this), + stop_run_loop.QuitClosure())); stop_run_loop.Run(); } @@ -1092,10 +1085,9 @@ // Start a worker. base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop start_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StartOnIOThread, base::Unretained(this), - start_run_loop.QuitClosure(), &status)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StartOnIOThread, base::Unretained(this), + start_run_loop.QuitClosure(), &status)); start_run_loop.Run(); ASSERT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value()); @@ -1105,10 +1097,9 @@ // Stop the worker. base::RunLoop stop_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StopOnIOThread, base::Unretained(this), - stop_run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StopOnIOThread, base::Unretained(this), + stop_run_loop.QuitClosure())); stop_run_loop.Run(); // Expect no PageVisits count. EXPECT_EQ(nullptr, base::StatisticsRecorder::FindHistogram( @@ -1286,7 +1277,7 @@ // Dispatch install on a worker. base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop install_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::InstallOnIOThread, base::Unretained(this), install_run_loop.QuitClosure(), &status)); @@ -1349,7 +1340,7 @@ void OnScriptEvaluationStart() override { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(quit_); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(quit_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(quit_)); } private: @@ -1370,10 +1361,9 @@ RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::AddObserver, base::Unretained(version_->embedded_worker()), &wait_for_load)); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StartOnIOThread, base::Unretained(this), - start_run_loop.QuitClosure(), &status)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StartOnIOThread, base::Unretained(this), + start_run_loop.QuitClosure(), &status)); load_run_loop.Run(); RunOnIOThread(base::BindOnce(&EmbeddedWorkerInstance::RemoveObserver, base::Unretained(version_->embedded_worker()), @@ -1402,16 +1392,15 @@ // Start a worker. base::Optional<blink::ServiceWorkerStatusCode> status; base::RunLoop start_run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&self::StartOnIOThread, base::Unretained(this), - start_run_loop.QuitClosure(), &status)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&self::StartOnIOThread, base::Unretained(this), + start_run_loop.QuitClosure(), &status)); start_run_loop.Run(); ASSERT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value()); // Dispatch an event. base::RunLoop install_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::InstallOnIOThread, base::Unretained(this), install_run_loop.QuitClosure(), &status)); @@ -1615,7 +1604,7 @@ { last_update_time = base::Time::Now() - base::TimeDelta::FromHours(24); base::RunLoop time_run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&self::SetLastUpdateCheckOnIOThread, base::Unretained(this), registration_id, @@ -1960,7 +1949,7 @@ // Simulate to attach DevTools. base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( [](base::OnceClosure done, ServiceWorkerContextWrapper* wrapper, @@ -2990,8 +2979,7 @@ void OnRunningStateChanged(ServiceWorkerVersion* version) override { if (version->running_status() == EmbeddedWorkerStatus::STOPPED) { DCHECK(quit_closure_); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(quit_closure_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(quit_closure_)); } } @@ -3179,8 +3167,8 @@ size_t size) override { DCHECK(cache_updated_closure_); metadata_size_ = size; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(cache_updated_closure_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + std::move(cache_updated_closure_)); } private:
diff --git a/content/browser/service_worker/service_worker_client_utils.cc b/content/browser/service_worker/service_worker_client_utils.cc index 44443c1f..2e7ad1d 100644 --- a/content/browser/service_worker/service_worker_client_utils.cc +++ b/content/browser/service_worker/service_worker_client_utils.cc
@@ -99,10 +99,9 @@ DCHECK(web_contents()); DCHECK(callback_); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback_), render_process_id, - render_frame_id)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback_), render_process_id, + render_frame_id)); Observe(nullptr); base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } @@ -176,7 +175,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!web_contents) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); @@ -216,7 +215,7 @@ RenderProcessHost* render_process_host = RenderProcessHost::FromID(worker_process_id); if (render_process_host->IsForGuestsOnly()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); @@ -227,7 +226,7 @@ context_wrapper->process_manager()->GetSiteInstanceForWorker(worker_id); if (!site_instance) { // Worker isn't running anymore. Fail. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); @@ -277,7 +276,7 @@ WebContents* web_contents = WebContents::FromRenderFrameHost(rfhi); if (!rfhi || !web_contents) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); @@ -291,7 +290,7 @@ rfhi->frame_tree_node()->frame_tree()->root()->navigation_request(); if (ongoing_navigation_request && ongoing_navigation_request->browser_initiated()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), ChildProcessHost::kInvalidUniqueID, MSG_ROUTING_NONE)); @@ -378,9 +377,8 @@ out_clients->push_back(std::move(info)); } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), std::move(out_clients))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), std::move(out_clients))); } struct ServiceWorkerClientInfoSort { @@ -478,7 +476,7 @@ return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OnGetWindowClientsOnUI, clients_info, controller->script_url(), @@ -512,7 +510,7 @@ CHECK_EQ(provider_host->url().GetOrigin(), sane_origin); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&GetWindowClientInfoOnUI, provider_host->process_id(), provider_host->frame_id(), provider_host->create_time(), @@ -527,7 +525,7 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(blink::mojom::ServiceWorkerClientType::kWindow, provider_host->client_type()); - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&FocusOnUI, provider_host->process_id(), provider_host->frame_id(), provider_host->create_time(), @@ -543,7 +541,7 @@ WindowType type, NavigationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &OpenWindowOnUI, url, script_url, worker_id, worker_process_id, @@ -559,7 +557,7 @@ const base::WeakPtr<ServiceWorkerContextCore>& context, NavigationCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &NavigateClientOnUI, url, script_url, process_id, frame_id, @@ -580,7 +578,7 @@ << client_type; if (client_type == blink::mojom::ServiceWorkerClientType::kWindow) { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&GetWindowClientInfoOnUI, provider_host->process_id(), provider_host->frame_id(), provider_host->create_time(), @@ -594,9 +592,8 @@ provider_host->client_uuid(), provider_host->client_type(), /*page_hidden=*/true, /*is_focused=*/false, base::TimeTicks(), provider_host->create_time()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), std::move(client_info))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), std::move(client_info))); } void GetClients(const base::WeakPtr<ServiceWorkerVersion>& controller,
diff --git a/content/browser/service_worker/service_worker_clients_api_browsertest.cc b/content/browser/service_worker/service_worker_clients_api_browsertest.cc index 1a4425a..634add7 100644 --- a/content/browser/service_worker/service_worker_clients_api_browsertest.cc +++ b/content/browser/service_worker/service_worker_clients_api_browsertest.cc
@@ -141,12 +141,11 @@ void DispatchNotificationClickEvent(int64_t version_id) { base::RunLoop run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ServiceWorkerClientsApiBrowserTest:: - DispatchNotificationClickEventOnIOThread, - base::Unretained(this), version_id, - run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ServiceWorkerClientsApiBrowserTest:: + DispatchNotificationClickEventOnIOThread, + base::Unretained(this), version_id, + run_loop.QuitClosure())); run_loop.Run(); }
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index 10c3d4d1..75d7a70 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -193,8 +193,7 @@ friend class base::RefCounted<ClearAllServiceWorkersHelper>; ~ClearAllServiceWorkersHelper() { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(callback_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(callback_)); } base::OnceClosure callback_; @@ -360,7 +359,7 @@ provider_host_iterator.Advance(); } - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&FrameListContainsMainFrameOnUI, std::move(render_frames)), std::move(callback));
diff --git a/content/browser/service_worker/service_worker_context_watcher.cc b/content/browser/service_worker/service_worker_context_watcher.cc index 2946bc79..f7dfb141 100644 --- a/content/browser/service_worker/service_worker_context_watcher.cc +++ b/content/browser/service_worker/service_worker_context_watcher.cc
@@ -43,7 +43,7 @@ void ServiceWorkerContextWatcher::Start() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWatcher::GetStoredRegistrationsOnIOThread, @@ -53,7 +53,7 @@ void ServiceWorkerContextWatcher::Stop() { DCHECK_CURRENTLY_ON(BrowserThread::UI); stop_called_ = true; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWatcher::StopOnIOThread, this)); } @@ -102,12 +102,12 @@ ++version_it; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerRegistrationUpdatedCallback, this, std::move(registrations))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerVersionUpdatedCallback, this, @@ -162,7 +162,7 @@ registrations->push_back( ServiceWorkerRegistrationInfo(scope, registration_id, delete_flag)); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerRegistrationUpdatedCallback, @@ -175,7 +175,7 @@ std::unique_ptr<std::vector<ServiceWorkerVersionInfo>> versions = std::make_unique<std::vector<ServiceWorkerVersionInfo>>(); versions->push_back(version_info); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerVersionUpdatedCallback, this, @@ -307,7 +307,7 @@ auto it = version_info_map_.find(version_id); if (it != version_info_map_.end()) registration_id = it->second->registration_id; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerErrorReportedCallback, this, @@ -325,7 +325,7 @@ if (it != version_info_map_.end()) registration_id = it->second->registration_id; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerContextWatcher::RunWorkerErrorReportedCallback, this,
diff --git a/content/browser/service_worker/service_worker_context_wrapper.cc b/content/browser/service_worker/service_worker_context_wrapper.cc index 8a9e819..a95ea42 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.cc +++ b/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -57,8 +57,8 @@ void WorkerStarted(ServiceWorkerContextWrapper::StatusCallback callback, blink::ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), status)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), status)); } void StartActiveWorkerOnIO( @@ -75,7 +75,7 @@ base::BindOnce(WorkerStarted, std::move(callback))); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), blink::ServiceWorkerStatusCode::kErrorNotFound)); @@ -151,19 +151,17 @@ const std::string& status_message, int64_t registration_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), - status == blink::ServiceWorkerStatusCode::kOk)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), + status == blink::ServiceWorkerStatusCode::kOk)); } void FinishUnregistrationOnIO(ServiceWorkerContext::ResultCallback callback, blink::ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), - status == blink::ServiceWorkerStatusCode::kOk)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), + status == blink::ServiceWorkerStatusCode::kOk)); } void MessageFinishedSending(ServiceWorkerContext::ResultCallback callback, @@ -236,8 +234,9 @@ // TODO(falken): Only block shutdown for that particular task, when someday // task runners support mixing task shutdown behaviors. scoped_refptr<base::SequencedTaskRunner> database_task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}); InitInternal(user_data_directory, std::move(database_task_runner), quota_manager_proxy, special_storage_policy, blob_context, loader_factory_getter, @@ -256,7 +255,7 @@ watcher_->Stop(); watcher_ = nullptr; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::ShutdownOnIO, this)); } @@ -391,15 +390,15 @@ const blink::mojom::ServiceWorkerRegistrationOptions& options, ResultCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::RegisterServiceWorker, this, script_url, options, std::move(callback))); return; } if (!context_core_) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), false)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), false)); return; } blink::mojom::ServiceWorkerRegistrationOptions options_to_pass( @@ -414,15 +413,15 @@ const GURL& scope, ResultCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::UnregisterServiceWorker, this, scope, std::move(callback))); return; } if (!context_core_) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), false)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), false)); return; } @@ -461,7 +460,7 @@ const GURL& origin, CountExternalRequestsCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::CountExternalRequests, this, origin, std::move(callback))); @@ -471,7 +470,7 @@ GetUsageInfoCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!context_core_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(std::move(callback), std::vector<StorageUsageInfo>())); return; @@ -484,15 +483,14 @@ void ServiceWorkerContextWrapper::DeleteForOrigin(const GURL& origin, ResultCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ServiceWorkerContextWrapper::DeleteForOrigin, this, - origin, std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ServiceWorkerContextWrapper::DeleteForOrigin, + this, origin, std::move(callback))); return; } if (!context_core_) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), false)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), false)); return; } context()->DeleteForOrigin( @@ -514,17 +512,16 @@ const GURL& url, CheckHasServiceWorkerCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::CheckHasServiceWorker, this, url, std::move(callback))); return; } if (!context_core_) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), - ServiceWorkerCapability::NO_SERVICE_WORKER)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), + ServiceWorkerCapability::NO_SERVICE_WORKER)); return; } context()->CheckHasServiceWorker( @@ -536,7 +533,7 @@ void ServiceWorkerContextWrapper::ClearAllServiceWorkersForTest( base::OnceClosure callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::ClearAllServiceWorkersForTest, this, @@ -544,8 +541,7 @@ return; } if (!context_core_) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(callback)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(callback)); return; } context_core_->ClearAllServiceWorkersForTest(std::move(callback)); @@ -678,7 +674,7 @@ "document_url", document_url.spec()); DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::StartServiceWorkerForNavigationHintOnIO, @@ -691,7 +687,7 @@ void ServiceWorkerContextWrapper::StopAllServiceWorkersForOrigin( const GURL& origin) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::StopAllServiceWorkersForOrigin, this, @@ -712,7 +708,7 @@ void ServiceWorkerContextWrapper::StopAllServiceWorkers( base::OnceClosure callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::StopAllServiceWorkersOnIO, this, std::move(callback), @@ -726,7 +722,7 @@ void ServiceWorkerContextWrapper::GetAllServiceWorkerRunningInfos( GetAllServiceWorkerRunningInfosCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::GetAllServiceWorkerRunningInfosOnIO, @@ -737,7 +733,7 @@ int64_t version_id, GetServiceWorkerRunningInfoCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::GetServiceWorkerRunningInfoOnIO, this, @@ -1051,17 +1047,16 @@ void ServiceWorkerContextWrapper::StartServiceWorker(const GURL& scope, StatusCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::StartServiceWorker, this, scope, std::move(callback))); return; } if (!context_core_) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), - blink::ServiceWorkerStatusCode::kErrorAbort)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), + blink::ServiceWorkerStatusCode::kErrorAbort)); return; } context_core_->storage()->FindRegistrationForScope( @@ -1071,7 +1066,7 @@ void ServiceWorkerContextWrapper::SkipWaitingWorker(const GURL& scope) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::SkipWaitingWorker, this, scope)); @@ -1086,7 +1081,7 @@ void ServiceWorkerContextWrapper::UpdateRegistration(const GURL& scope) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::UpdateRegistration, this, scope)); @@ -1103,7 +1098,7 @@ void ServiceWorkerContextWrapper::SetForceUpdateOnPageLoad( bool force_update_on_page_load) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerContextWrapper::SetForceUpdateOnPageLoad, this, force_update_on_page_load)); @@ -1145,7 +1140,7 @@ std::unique_ptr<blink::URLLoaderFactoryBundleInfo> non_network_loader_factory_bundle_info_for_update_check) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerContextWrapper::InitInternal, this, @@ -1307,8 +1302,8 @@ ServiceWorkerCapability capability) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), capability)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), capability)); } void ServiceWorkerContextWrapper::DidFindRegistrationForUpdate( @@ -1347,7 +1342,7 @@ } } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), pending_external_request_count)); } @@ -1426,8 +1421,8 @@ StartServiceWorkerForNavigationHintResult result) { DCHECK_CURRENTLY_ON(BrowserThread::IO); ServiceWorkerMetrics::RecordStartServiceWorkerForNavigationHintResult(result); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), result)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), result)); } void ServiceWorkerContextWrapper::StopAllServiceWorkersOnIO(
diff --git a/content/browser/service_worker/service_worker_fetch_dispatcher.cc b/content/browser/service_worker/service_worker_fetch_dispatcher.cc index 9c5536d..455c790f 100644 --- a/content/browser/service_worker/service_worker_fetch_dispatcher.cc +++ b/content/browser/service_worker/service_worker_fetch_dispatcher.cc
@@ -181,10 +181,9 @@ if (!worker_id_ || !devtools_enabled_) return; while (!devtools_callbacks.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(devtools_callbacks.front()), *worker_id_, - devtools_request_id_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(devtools_callbacks.front()), + *worker_id_, devtools_request_id_)); devtools_callbacks.pop(); } } @@ -675,11 +674,10 @@ network::mojom::URLLoaderFactoryPtr network_factory; auto factory_request = mojo::MakeRequest(&network_factory); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&CreateNetworkFactoryForNavigationPreloadOnUI, - frame_tree_node_id, std::move(context_wrapper), - mojo::MakeRequest(&network_factory))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&CreateNetworkFactoryForNavigationPreloadOnUI, + frame_tree_node_id, std::move(context_wrapper), + mojo::MakeRequest(&network_factory))); factory = base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>( std::move(network_factory));
diff --git a/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc b/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc index 09f09bb..6744d0e6 100644 --- a/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc +++ b/content/browser/service_worker/service_worker_installed_scripts_sender_unittest.cc
@@ -44,10 +44,9 @@ std::move(quit_closure).Run(); return; case MOJO_RESULT_SHOULD_WAIT: - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ReadDataPipeInternal, handle, result, - std::move(quit_closure))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ReadDataPipeInternal, handle, result, + std::move(quit_closure))); return; case MOJO_RESULT_OK: EXPECT_NE(nullptr, buffer);
diff --git a/content/browser/service_worker/service_worker_internals_ui.cc b/content/browser/service_worker/service_worker_internals_ui.cc index dfea213..9e7d791 100644 --- a/content/browser/service_worker/service_worker_internals_ui.cc +++ b/content/browser/service_worker/service_worker_internals_ui.cc
@@ -55,9 +55,9 @@ int callback_id, blink::ServiceWorkerStatusCode status) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(OperationCompleteCallback, - internals, callback_id, status)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(OperationCompleteCallback, internals, + callback_id, status)); return; } DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -206,7 +206,7 @@ blink::ServiceWorkerStatusCode status, const std::vector<ServiceWorkerRegistrationInfo>& stored_registrations) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), context->GetAllLiveRegistrationInfo(), context->GetAllLiveVersionInfo(), stored_registrations)); @@ -419,7 +419,7 @@ std::move(new_observer); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( GetRegistrationsOnIOThread, context, @@ -563,11 +563,10 @@ int64_t version_id, StatusCallback callback) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&ServiceWorkerInternalsUI::StopWorkerWithId, - base::Unretained(this), context, version_id, - std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&ServiceWorkerInternalsUI::StopWorkerWithId, + base::Unretained(this), context, version_id, + std::move(callback))); return; } @@ -589,7 +588,7 @@ const GURL& scope, ServiceWorkerInternalsUI::StatusCallback callback) const { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerInternalsUI::UnregisterWithScope, base::Unretained(this), context, scope,
diff --git a/content/browser/service_worker/service_worker_metrics.cc b/content/browser/service_worker/service_worker_metrics.cc index 7551791..39eac4d6 100644 --- a/content/browser/service_worker/service_worker_metrics.cc +++ b/content/browser/service_worker/service_worker_metrics.cc
@@ -319,10 +319,9 @@ if (ShouldExcludeSiteFromHistogram(site)) return; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&RecordURLMetricOnUI, "ServiceWorker.ControlledPageUrl", - url)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&RecordURLMetricOnUI, + "ServiceWorker.ControlledPageUrl", url)); } void ServiceWorkerMetrics::RecordStartInstalledWorkerStatus(
diff --git a/content/browser/service_worker/service_worker_navigation_handle.cc b/content/browser/service_worker/service_worker_navigation_handle.cc index d25a8650..e65fdc17 100644 --- a/content/browser/service_worker/service_worker_navigation_handle.cc +++ b/content/browser/service_worker/service_worker_navigation_handle.cc
@@ -47,7 +47,7 @@ // We may have failed to pre-create the provider host. if (!provider_info_) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &ServiceWorkerNavigationHandleCore::OnBeginNavigationCommit, @@ -57,7 +57,7 @@ void ServiceWorkerNavigationHandle::OnBeginWorkerCommit() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ServiceWorkerNavigationHandleCore::OnBeginWorkerCommit, base::Unretained(core_)));
diff --git a/content/browser/service_worker/service_worker_navigation_handle_core.cc b/content/browser/service_worker/service_worker_navigation_handle_core.cc index e23d3e6..2d58f84 100644 --- a/content/browser/service_worker/service_worker_navigation_handle_core.cc +++ b/content/browser/service_worker/service_worker_navigation_handle_core.cc
@@ -37,7 +37,7 @@ DCHECK(provider_info->host_ptr_info.is_valid() && provider_info->client_request.is_pending()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ServiceWorkerNavigationHandle::OnCreatedProviderHost, ui_handle_, std::move(provider_info)));
diff --git a/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc b/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc index 9538957..df8431f 100644 --- a/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc +++ b/content/browser/service_worker/service_worker_navigation_loader_interceptor.cc
@@ -41,13 +41,12 @@ handle_core->interceptor()->MaybeCreateSubresourceLoaderParams(); } - PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &ServiceWorkerNavigationLoaderInterceptor::LoaderCallbackWrapper, - interceptor_on_ui, std::move(provider_info), - std::move(subresource_loader_params), std::move(loader_callback), - std::move(handler))); + PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce( + &ServiceWorkerNavigationLoaderInterceptor::LoaderCallbackWrapper, + interceptor_on_ui, std::move(provider_info), + std::move(subresource_loader_params), std::move(loader_callback), + std::move(handler))); } void FallbackCallbackWrapperOnIO( @@ -55,7 +54,7 @@ NavigationLoaderInterceptor::FallbackCallback fallback_callback, bool reset_subresource_loader_params) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - PostTaskWithTraits( + PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ServiceWorkerNavigationLoaderInterceptor::FallbackCallbackWrapper, @@ -198,7 +197,7 @@ // Start the inner interceptor on the IO thread. It will call back to // LoaderCallbackWrapper() on the UI thread. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&MaybeCreateLoaderOnIO, GetWeakPtr(), handle_->core(), params_, tentative_resource_request, browser_context, @@ -269,11 +268,10 @@ network::mojom::URLLoaderRequest request, network::mojom::URLLoaderClientPtr client) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(InvokeRequestHandlerOnIO, std::move(handler_on_io), - resource_request, std::move(request), - client.PassInterface())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(InvokeRequestHandlerOnIO, + std::move(handler_on_io), resource_request, + std::move(request), client.PassInterface())); } } // namespace content
diff --git a/content/browser/service_worker/service_worker_provider_host.cc b/content/browser/service_worker/service_worker_provider_host.cc index c4544dfb..1193f830 100644 --- a/content/browser/service_worker/service_worker_provider_host.cc +++ b/content/browser/service_worker/service_worker_provider_host.cc
@@ -1241,11 +1241,11 @@ mojo::ScopedMessagePipeHandle interface_pipe) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(IsProviderForServiceWorker()); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce( - &GetInterfaceImpl, interface_name, std::move(interface_pipe), - running_hosted_version_->script_origin(), render_process_id_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&GetInterfaceImpl, interface_name, + std::move(interface_pipe), + running_hosted_version_->script_origin(), + render_process_id_)); } blink::mojom::ServiceWorkerRegistrationObjectInfoPtr
diff --git a/content/browser/service_worker/service_worker_register_job.cc b/content/browser/service_worker/service_worker_register_job.cc index 4e55175..daaa9e3 100644 --- a/content/browser/service_worker/service_worker_register_job.cc +++ b/content/browser/service_worker/service_worker_register_job.cc
@@ -101,9 +101,9 @@ ? base::TaskTraits(BrowserThread::IO) : base::TaskTraits(BrowserThread::IO, base::TaskPriority::BEST_EFFORT); - base::PostTaskWithTraits(FROM_HERE, std::move(traits), - base::BindOnce(&ServiceWorkerRegisterJob::StartImpl, - weak_factory_.GetWeakPtr())); + base::PostTask(FROM_HERE, std::move(traits), + base::BindOnce(&ServiceWorkerRegisterJob::StartImpl, + weak_factory_.GetWeakPtr())); } void ServiceWorkerRegisterJob::StartImpl() {
diff --git a/content/browser/service_worker/service_worker_registration_object_host.cc b/content/browser/service_worker/service_worker_registration_object_host.cc index b6e61e4..4452eabf 100644 --- a/content/browser/service_worker/service_worker_registration_object_host.cc +++ b/content/browser/service_worker/service_worker_registration_object_host.cc
@@ -235,11 +235,10 @@ return; } - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(update_function), - blink::ServiceWorkerStatusCode::kOk), - delay); + base::PostDelayedTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(update_function), + blink::ServiceWorkerStatusCode::kOk), + delay); } void ServiceWorkerRegistrationObjectHost::Unregister(
diff --git a/content/browser/service_worker/service_worker_request_handler_unittest.cc b/content/browser/service_worker/service_worker_request_handler_unittest.cc index 969c09f..820797b 100644 --- a/content/browser/service_worker/service_worker_request_handler_unittest.cc +++ b/content/browser/service_worker/service_worker_request_handler_unittest.cc
@@ -55,7 +55,7 @@ static std::unique_ptr<ServiceWorkerNavigationHandleCore> CreateNavigationHandleCore(ServiceWorkerContextWrapper* context_wrapper) { std::unique_ptr<ServiceWorkerNavigationHandleCore> navigation_handle_core; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {BrowserThread::UI}, base::BindOnce( [](ServiceWorkerContextWrapper* wrapper) {
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc index 721870a1..dc470025 100644 --- a/content/browser/service_worker/service_worker_storage.cc +++ b/content/browser/service_worker/service_worker_storage.cc
@@ -2206,8 +2206,10 @@ // TODO(nhiroki): What if there is a bunch of files in the cache directory? // Deleting the directory could take a long time and restart could be delayed. // We should probably rename the directory and delete it later. - PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, + PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(&base::DeleteFile, GetDiskCachePath(), true), base::BindOnce(&ServiceWorkerStorage::DidDeleteDiskCache, weak_factory_.GetWeakPtr(), std::move(callback)));
diff --git a/content/browser/service_worker/service_worker_test_utils.h b/content/browser/service_worker/service_worker_test_utils.h index 28d744c..aeabf90 100644 --- a/content/browser/service_worker/service_worker_test_utils.h +++ b/content/browser/service_worker/service_worker_test_utils.h
@@ -46,7 +46,7 @@ Arg actual) { *out = actual; if (!quit.is_null()) - base::PostTaskWithTraits(FROM_HERE, {run_quit_thread}, std::move(quit)); + base::PostTask(FROM_HERE, {run_quit_thread}, std::move(quit)); } template <typename Arg>
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index 13758bb..becc3e0 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -25,7 +25,6 @@ #include "base/task/post_task.h" #include "base/time/default_clock.h" #include "build/build_config.h" -#include "components/variations/net/variations_http_headers.h" #include "content/browser/background_fetch/background_fetch_context.h" #include "content/browser/blob_storage/blob_registry_wrapper.h" #include "content/browser/blob_storage/chrome_blob_storage_context.h"
diff --git a/content/browser/webauth/virtual_authenticator.cc b/content/browser/webauth/virtual_authenticator.cc index 67f2e9fe..6b319b7 100644 --- a/content/browser/webauth/virtual_authenticator.cc +++ b/content/browser/webauth/virtual_authenticator.cc
@@ -10,6 +10,8 @@ #include "base/containers/span.h" #include "base/guid.h" #include "crypto/ec_private_key.h" +#include "device/fido/public_key_credential_rp_entity.h" +#include "device/fido/public_key_credential_user_entity.h" #include "device/fido/virtual_ctap2_device.h" #include "device/fido/virtual_u2f_device.h" @@ -43,26 +45,39 @@ bool VirtualAuthenticator::AddRegistration( std::vector<uint8_t> key_handle, - const std::vector<uint8_t>& rp_id_hash, + base::span<const uint8_t, device::kRpIdHashLength> rp_id_hash, const std::vector<uint8_t>& private_key, int32_t counter) { - if (rp_id_hash.size() != device::kRpIdHashLength) - return false; - auto ec_private_key = crypto::ECPrivateKey::CreateFromPrivateKeyInfo(private_key); if (!ec_private_key) return false; return state_->registrations - .emplace( - std::move(key_handle), - ::device::VirtualFidoDevice::RegistrationData( - std::move(ec_private_key), - base::make_span<device::kRpIdHashLength>(rp_id_hash), counter)) + .emplace(std::move(key_handle), + ::device::VirtualFidoDevice::RegistrationData( + std::move(ec_private_key), std::move(rp_id_hash), counter)) .second; } +bool VirtualAuthenticator::AddResidentRegistration( + std::vector<uint8_t> key_handle, + std::string rp_id, + const std::vector<uint8_t>& private_key, + int32_t counter, + std::vector<uint8_t> user_handle) { + auto ec_private_key = + crypto::ECPrivateKey::CreateFromPrivateKeyInfo(private_key); + if (!ec_private_key) + return false; + + return state_->InjectResidentKey( + std::move(key_handle), + device::PublicKeyCredentialRpEntity(std::move(rp_id)), + device::PublicKeyCredentialUserEntity(std::move(user_handle)), counter, + std::move(ec_private_key)); +} + void VirtualAuthenticator::ClearRegistrations() { state_->registrations.clear(); } @@ -118,9 +133,16 @@ void VirtualAuthenticator::AddRegistration( blink::test::mojom::RegisteredKeyPtr registration, AddRegistrationCallback callback) { - std::move(callback).Run(AddRegistration( - std::move(registration->key_handle), registration->application_parameter, - registration->private_key, registration->counter)); + if (registration->application_parameter.size() != device::kRpIdHashLength) { + std::move(callback).Run(false); + return; + } + + std::move(callback).Run( + AddRegistration(std::move(registration->key_handle), + base::make_span<device::kRpIdHashLength>( + registration->application_parameter), + registration->private_key, registration->counter)); } void VirtualAuthenticator::ClearRegistrations(
diff --git a/content/browser/webauth/virtual_authenticator.h b/content/browser/webauth/virtual_authenticator.h index 37668b96..dd2f6f65 100644 --- a/content/browser/webauth/virtual_authenticator.h +++ b/content/browser/webauth/virtual_authenticator.h
@@ -43,10 +43,19 @@ // Register a new credential. Returns true if the registration was successful, // false otherwise. - bool AddRegistration(std::vector<uint8_t> key_handle, - const std::vector<uint8_t>& rp_id_hash, - const std::vector<uint8_t>& private_key, - int32_t counter); + bool AddRegistration( + std::vector<uint8_t> key_handle, + base::span<const uint8_t, device::kRpIdHashLength> rp_id_hash, + const std::vector<uint8_t>& private_key, + int32_t counter); + + // Register a new resident credential. Returns true if the registration was + // successful, false otherwise. + bool AddResidentRegistration(std::vector<uint8_t> key_handle, + std::string rp_id, + const std::vector<uint8_t>& private_key, + int32_t counter, + std::vector<uint8_t> user_handle); // Removes all the credentials. void ClearRegistrations(); @@ -61,6 +70,8 @@ is_user_verified_ = is_user_verified; } + bool has_resident_key() const { return has_resident_key_; } + ::device::FidoTransportProtocol transport() const { return state_->transport; }
diff --git a/content/browser/webrtc/webrtc_stress_image_capture_browsertest.cc b/content/browser/webrtc/webrtc_stress_image_capture_browsertest.cc index dc9b036..4f9c57a 100644 --- a/content/browser/webrtc/webrtc_stress_image_capture_browsertest.cc +++ b/content/browser/webrtc/webrtc_stress_image_capture_browsertest.cc
@@ -65,6 +65,7 @@ void SetUp() override { ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); + embedded_test_server()->StartAcceptingConnections(); UsingRealWebcam_WebRtcWebcamBrowserTest::SetUp(); } @@ -96,7 +97,6 @@ IN_PROC_BROWSER_TEST_P(WebRtcImageCaptureStressBrowserTest, MANUAL_Take10Photos) { - embedded_test_server()->StartAcceptingConnections(); ASSERT_TRUE(RunImageCaptureTestCase("testTake10PhotosSucceeds()")); }
diff --git a/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc b/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc index 8b0ed34d..2b18674 100644 --- a/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc +++ b/content/child/dwrite_font_proxy/dwrite_font_proxy_win.cc
@@ -360,8 +360,9 @@ void DWriteFontCollectionProxy::SetProxy( blink::mojom::DWriteFontProxyPtrInfo proxy) { font_proxy_ = blink::mojom::ThreadSafeDWriteFontProxyPtr::Create( - std::move(proxy), base::CreateSequencedTaskRunnerWithTraits( - {base::WithBaseSyncPrimitives()})); + std::move(proxy), + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::WithBaseSyncPrimitives()})); } blink::mojom::DWriteFontProxy& DWriteFontCollectionProxy::GetFontProxy() {
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 9583eca..88cddca 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -690,9 +690,6 @@ IPC_MESSAGE_ROUTED1(FrameMsg_IntrinsicSizingInfoOfChildChanged, blink::WebIntrinsicSizingInfo) -IPC_MESSAGE_ROUTED1(FrameMsg_FirstSurfaceActivation, - viz::SurfaceInfo /* surface_info */) - // Notifies the embedding frame that the process rendering the child frame's // contents has terminated. IPC_MESSAGE_ROUTED0(FrameMsg_ChildFrameProcessGone)
diff --git a/content/common/mac/font_loader.mm b/content/common/mac/font_loader.mm index 10ec3e3..642602c9 100644 --- a/content/common/mac/font_loader.mm +++ b/content/common/mac/font_loader.mm
@@ -132,9 +132,9 @@ // a user installing a third-party font manager. See crbug.com/72727. Web page // rendering can't continue until a font is returned. constexpr base::TaskTraits kTraits = { - base::MayBlock(), base::TaskPriority::USER_VISIBLE, + base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}; - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, kTraits, base::BindOnce(&LoadFontOnFileThread, font_name, font_point_size), base::BindOnce(&ReplyOnUIThread, std::move(callback)));
diff --git a/content/common/renderer.mojom b/content/common/renderer.mojom index 38377b2..d34c59f 100644 --- a/content/common/renderer.mojom +++ b/content/common/renderer.mojom
@@ -183,6 +183,11 @@ // Tells the renderer to create a new view. CreateView(CreateViewParams params); + // Tells the renderer to destroy an existing view. This method must be called + // exactly once for each invocation of CreateView. |view_id| is synonymous + // with |routing_id|. + DestroyView(int32 view_id); + // Tells the renderer to create a new RenderFrame. CreateFrame(CreateFrameParams params);
diff --git a/content/gpu/gpu_service_factory.cc b/content/gpu/gpu_service_factory.cc index 71ae3de..b7cf5c5d 100644 --- a/content/gpu/gpu_service_factory.cc +++ b/content/gpu/gpu_service_factory.cc
@@ -63,8 +63,8 @@ task_runner = task_runner_; #else // TODO(crbug.com/786169): Check whether this needs to be single threaded. - task_runner = base::CreateSingleThreadTaskRunnerWithTraits( - {base::TaskPriority::USER_BLOCKING}); + task_runner = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::TaskPriority::USER_BLOCKING}); #endif // defined(OS_WIN) using FactoryCallback =
diff --git a/content/public/browser/background_tracing_manager.h b/content/public/browser/background_tracing_manager.h index c6d47000..e4d064b 100644 --- a/content/public/browser/background_tracing_manager.h +++ b/content/public/browser/background_tracing_manager.h
@@ -35,7 +35,7 @@ // // void Upload(const scoped_refptr<base::RefCountedString>& data, // FinishedProcessingCallback done_callback) { - // base::PostTaskWithTraitsAndReply( + // base::PostTaskAndReply( // FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, // base::BindOnce(&DoUploadInBackground, data), // std::move(done_callback));
diff --git a/content/public/browser/browser_associated_interface.h b/content/public/browser/browser_associated_interface.h index b0f6cab0..5a3a1dd 100644 --- a/content/public/browser/browser_associated_interface.h +++ b/content/public/browser/browser_associated_interface.h
@@ -76,9 +76,8 @@ void ClearBindings() { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&InternalState::ClearBindings, this)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&InternalState::ClearBindings, this)); return; } bindings_.reset();
diff --git a/content/public/browser/browser_message_filter.cc b/content/public/browser/browser_message_filter.cc index a52d3c1..ecdda14 100644 --- a/content/public/browser/browser_message_filter.cc +++ b/content/public/browser/browser_message_filter.cc
@@ -75,7 +75,7 @@ return DispatchMessage(message); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {thread}, base::BindOnce(base::IgnoreResult(&Internal::DispatchMessage), this, message)); @@ -146,7 +146,7 @@ } if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(base::IgnoreResult(&BrowserMessageFilter::Send), this, message));
diff --git a/content/public/browser/browser_task_traits.h b/content/public/browser/browser_task_traits.h index f90334b..82c655b 100644 --- a/content/public/browser/browser_task_traits.h +++ b/content/public/browser/browser_task_traits.h
@@ -48,10 +48,10 @@ // to a BrowserThread. // // To post a task to the UI thread (analogous for IO thread): -// base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, task); +// base::PostTask(FROM_HERE, {BrowserThread::UI}, task); // // To obtain a TaskRunner for the UI thread (analogous for the IO thread): -// base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); +// base::CreateSingleThreadTaskRunner({BrowserThread::UI}); // // Tasks posted to the same BrowserThread with the same traits will be executed // in the order they were posted, regardless of the TaskRunners they were
diff --git a/content/public/browser/browser_thread.h b/content/public/browser/browser_thread.h index 8ec1c9af..7cfc1154 100644 --- a/content/public/browser/browser_thread.h +++ b/content/public/browser/browser_thread.h
@@ -58,7 +58,7 @@ IO, // NOTE: do not add new threads here. Instead you should just use - // base::Create*TaskRunnerWithTraits to run tasks on the ThreadPool. + // base::Create*TaskRunner to run tasks on the ThreadPool. // This identifier does not represent a thread. Instead it counts the // number of well-known threads. Insert new well-known threads before this @@ -70,7 +70,7 @@ // browser_task_traits.h. // TODO(crbug.com/878356): Consider replacing callsites of this with - // base::CreateTaskRunnerWithTraits({id})->DeleteSoon(..). + // base::CreateTaskRunner({id})->DeleteSoon(..). template <class T> static bool DeleteSoon(ID identifier, const base::Location& from_here,
diff --git a/content/public/browser/native_file_system_entry_factory.h b/content/public/browser/native_file_system_entry_factory.h index 38fcc33b9..3666fc7 100644 --- a/content/public/browser/native_file_system_entry_factory.h +++ b/content/public/browser/native_file_system_entry_factory.h
@@ -11,6 +11,7 @@ #include "content/public/browser/browser_thread.h" #include "ipc/ipc_message.h" #include "third_party/blink/public/mojom/native_file_system/native_file_system_directory_handle.mojom-forward.h" +#include "url/gurl.h" #include "url/origin.h" namespace content { @@ -23,11 +24,20 @@ // Context from which a created handle is going to be used. This is used for // security and permission checks. Pass in MSG_ROUTING_NONE as frame_id if // the context is a worker, otherwise use the routing id of the relevant - // RenderFrameHost. + // RenderFrameHost. Pass in the URL most relevant as the url parameter. + // This url will be used for verifications later for SafeBrowsing and + // Quarantine Service if used for writes. struct CONTENT_EXPORT BindingContext { - BindingContext(const url::Origin& origin, int process_id, int frame_id) - : origin(origin), process_id(process_id), frame_id(frame_id) {} + BindingContext(const url::Origin& origin, + const GURL& url, + int process_id, + int frame_id) + : origin(origin), + url(url), + process_id(process_id), + frame_id(frame_id) {} url::Origin origin; + GURL url; int process_id; int frame_id; bool is_worker() const { return frame_id == MSG_ROUTING_NONE; }
diff --git a/content/public/browser/push_messaging_service.cc b/content/public/browser/push_messaging_service.cc index f2853b28..7e7ed4d 100644 --- a/content/public/browser/push_messaging_service.cc +++ b/content/public/browser/push_messaging_service.cc
@@ -31,15 +31,14 @@ DCHECK_EQ(1u, data.size()); result = data[0]; } - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, result, success, not_found)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, result, success, not_found)); } void CallClosureFromIO(base::OnceClosure callback, blink::ServiceWorkerStatusCode status) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, std::move(callback)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(callback)); } void GetUserDataOnIO( @@ -96,7 +95,7 @@ int64_t service_worker_registration_id, const StringCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&GetUserDataOnIO, GetServiceWorkerContext(browser_context, origin), @@ -111,7 +110,7 @@ int64_t service_worker_registration_id, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ClearPushSubscriptionIdOnIO, GetServiceWorkerContext(browser_context, origin), @@ -127,7 +126,7 @@ const std::string& sender_id, const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&StorePushSubscriptionOnIOForTesting, GetServiceWorkerContext(browser_context, origin),
diff --git a/content/public/browser/url_data_source.cc b/content/public/browser/url_data_source.cc index 14a367a..696bee3 100644 --- a/content/public/browser/url_data_source.cc +++ b/content/public/browser/url_data_source.cc
@@ -45,7 +45,7 @@ BrowserContext* browser_context, const GURL& url, base::OnceCallback<void(URLDataSource*)> callback) { - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&GetSourceForURLHelper, browser_context->GetResourceContext(), url), @@ -54,7 +54,7 @@ scoped_refptr<base::SingleThreadTaskRunner> URLDataSource::TaskRunnerForRequestPath(const std::string& path) { - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); } bool URLDataSource::ShouldReplaceExistingSource() {
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 3ba069c..cfdb7314 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -336,10 +336,6 @@ "PauseExecutionContextOnBackgroundFreeze", base::FEATURE_ENABLED_BY_DEFAULT}; -// Whether PDF files should be rendered in diffent processes based on origin. -const base::Feature kPdfIsolation = {"PdfIsolation", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Whether web apps can run periodic tasks upon network connectivity. const base::Feature kPeriodicBackgroundSync{"PeriodicBackgroundSync", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 99f2a31..aad0552 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -80,7 +80,6 @@ CONTENT_EXPORT extern const base::Feature kPauseExecutionContextOnBackgroundFreeze; CONTENT_EXPORT extern const base::Feature kPaymentRequestHasEnrolledInstrument; -CONTENT_EXPORT extern const base::Feature kPdfIsolation; CONTENT_EXPORT extern const base::Feature kPeriodicBackgroundSync; CONTENT_EXPORT extern const base::Feature kPerNavigationMojoInterface; CONTENT_EXPORT extern const base::Feature kPepper3DImageChromium;
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index c554c356..cb0218d 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -723,6 +723,12 @@ // that's needed to show a dialog. const char kRendererStartupDialog[] = "renderer-startup-dialog"; +// Manual tests only run when --run-manual is specified. This allows writing +// tests that don't run automatically but are still in the same test binary. +// This is useful so that a team that wants to run a few tests doesn't have to +// add a new binary that must be compiled on all builds. +const char kRunManualTestsFlag[] = "run-manual"; + // Causes the process to run as a sandbox IPC subprocess. const char kSandboxIPCProcess[] = "sandbox-ipc";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index 20b8bcf1..040997f 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -210,6 +210,7 @@ CONTENT_EXPORT extern const char kRendererProcess[]; CONTENT_EXPORT extern const char kRendererProcessLimit[]; CONTENT_EXPORT extern const char kRendererStartupDialog[]; +CONTENT_EXPORT extern const char kRunManualTestsFlag[]; extern const char kSandboxIPCProcess[]; extern const char kShowLayoutShiftRegions[]; extern const char kShowPaintRects[];
diff --git a/content/public/test/background_sync_test_util.cc b/content/public/test/background_sync_test_util.cc index 9fa2e0b..f5814862 100644 --- a/content/public/test/background_sync_test_util.cc +++ b/content/public/test/background_sync_test_util.cc
@@ -54,7 +54,7 @@ // static void SetOnline(WebContents* web_contents, bool online) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &SetOnlineOnIOThread,
diff --git a/content/public/test/browser_test_base.cc b/content/public/test/browser_test_base.cc index 5a5aac01..76c3dfa68 100644 --- a/content/public/test/browser_test_base.cc +++ b/content/public/test/browser_test_base.cc
@@ -101,6 +101,9 @@ namespace content { namespace { +// See kRunManualTestsFlag in "content_switches.cc". +const char kManualTestPrefix[] = "MANUAL_"; + #if defined(OS_POSIX) // On SIGSEGV or SIGTERM (sent by the runner on timeouts), dump a stack trace // (to make debugging easier) and also exit with a known error code (so that @@ -132,8 +135,7 @@ void RunTaskOnRendererThread(base::OnceClosure task, base::OnceClosure quit_task) { std::move(task).Run(); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(quit_task)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(quit_task)); } void TraceStopTracingComplete(const base::Closure& quit, @@ -202,6 +204,9 @@ void BrowserTestBase::SetUp() { set_up_called_ = true; + if (BrowserTestBase::ShouldSkipManualTests()) + GTEST_SKIP(); + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); // Features that depend on external factors (e.g. memory pressure monitor) can @@ -513,6 +518,14 @@ InitializeNetworkProcess(); } +bool BrowserTestBase::ShouldSkipManualTests() { + return (base::StartsWith( + ::testing::UnitTest::GetInstance()->current_test_info()->name(), + kManualTestPrefix, base::CompareCase::SENSITIVE) && + !base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kRunManualTestsFlag)); +} + #if defined(OS_ANDROID) void BrowserTestBase::WaitUntilJavaIsReady(base::OnceClosure quit_closure) { if (testing::android::JavaAsyncStartupTasksCompleteForBrowserTests()) {
diff --git a/content/public/test/browser_test_base.h b/content/public/test/browser_test_base.h index fa44d7e7..6632b7b3 100644 --- a/content/public/test/browser_test_base.h +++ b/content/public/test/browser_test_base.h
@@ -98,6 +98,13 @@ // This is meant to be inherited only by the test harness. virtual void PostRunTestOnMainThread() = 0; + // Returns true if this test should be skipped. Tests starting with 'MANUAL_' + // are skipped unless the command line flag "--run-manual" is supplied. + // In case overriding SetUp() breaks, add: + // if (ShouldSkipManualTest()) + // GTEST_SKIP(); + bool ShouldSkipManualTests(); + // Sets expected browser exit code, in case it's different than 0 (success). void set_expected_exit_code(int code) { expected_exit_code_ = code; }
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index fdcab07d2..6cea8ab1 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -473,14 +473,14 @@ private: // NavigationThrottle: NavigationThrottle::ThrottleCheckResult WillStartRequest() override { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - on_will_start_request_closure_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + on_will_start_request_closure_); return NavigationThrottle::DEFER; } NavigationThrottle::ThrottleCheckResult WillProcessResponse() override { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - on_will_process_response_closure_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + on_will_process_response_closure_); return NavigationThrottle::DEFER; } @@ -2597,7 +2597,7 @@ bool MainThreadFrameObserver::OnMessageReceived(const IPC::Message& msg) { if (msg.type() == WidgetHostMsg_WaitForNextFrameForTests_ACK::ID && msg.routing_id() == routing_id_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&MainThreadFrameObserver::Quit, base::Unretained(this))); } @@ -2973,11 +2973,10 @@ FileSystemManagerImpl* file_system = static_cast<RenderProcessHostImpl*>(rph) ->GetFileSystemManagerForTesting(); blink::mojom::FileSystemManagerPtr file_system_manager_ptr; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&FileSystemManagerImpl::BindRequest, - base::Unretained(file_system), - mojo::MakeRequest(&file_system_manager_ptr))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&FileSystemManagerImpl::BindRequest, + base::Unretained(file_system), + mojo::MakeRequest(&file_system_manager_ptr))); return file_system_manager_ptr; } } // namespace @@ -3096,7 +3095,7 @@ FrameHostMsg_ContextMenu::Param params; FrameHostMsg_ContextMenu::Read(&message, ¶ms); content::ContextMenuParams menu_params = std::get<0>(params); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&ContextMenuFilter::OnContextMenu, this, menu_params)); } @@ -3314,14 +3313,14 @@ 1.f / visual_properties.screen_info.device_scale_factor)); } // Track each rect updates. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &SynchronizeVisualPropertiesMessageFilter::OnUpdatedFrameRectOnUI, this, screen_space_rect_in_dip)); // Track each surface id update. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &SynchronizeVisualPropertiesMessageFilter::OnUpdatedSurfaceIdOnUI, @@ -3340,7 +3339,7 @@ // We can't nest on the IO thread. So tests will wait on the UI thread, so // post there to exit the nesting. - base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::UI}) + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}) ->PostTask(FROM_HERE, base::BindOnce(&SynchronizeVisualPropertiesMessageFilter:: OnUpdatedFrameSinkIdOnUI,
diff --git a/content/public/test/content_browser_test_utils.cc b/content/public/test/content_browser_test_utils.cc index d4f4c17..5759d0d8 100644 --- a/content/public/test/content_browser_test_utils.cc +++ b/content/public/test/content_browser_test_utils.cc
@@ -134,7 +134,7 @@ MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( [](MediaStreamManager* media_stream_manager,
diff --git a/content/public/test/download_test_observer.cc b/content/public/test/download_test_observer.cc index 8dd20f3..83ffbf8 100644 --- a/content/public/test/download_test_observer.cc +++ b/content/public/test/download_test_observer.cc
@@ -148,7 +148,7 @@ case ON_DANGEROUS_DOWNLOAD_ACCEPT: // Fake user click on "Accept". Delay the actual click, as the // real UI would. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadTestObserver::AcceptDangerousDownload, weak_factory_.GetWeakPtr(), download->GetId())); @@ -157,7 +157,7 @@ case ON_DANGEROUS_DOWNLOAD_DENY: // Fake a user click on "Deny". Delay the actual click, as the // real UI would. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadTestObserver::DenyDangerousDownload, weak_factory_.GetWeakPtr(), download->GetId())); @@ -311,9 +311,8 @@ // Helper method to post a task to IO thread to ensure remaining operations on // the IO thread complete. void PingFileThread(int cycle, base::OnceClosure callback) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&PingIOThread, cycle, std::move(callback))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&PingIOThread, cycle, std::move(callback))); } // Post a task to file thread, and wait for it to be posted back on to the IO @@ -324,8 +323,7 @@ DownloadManager::GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&PingFileThread, cycle, std::move(callback))); } else { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(callback)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(callback)); } }
diff --git a/content/public/test/fake_speech_recognition_manager.cc b/content/public/test/fake_speech_recognition_manager.cc index 39afbf4..8412264 100644 --- a/content/public/test/fake_speech_recognition_manager.cc +++ b/content/public/test/fake_speech_recognition_manager.cc
@@ -95,9 +95,8 @@ base::Unretained(this))); } if (!recognition_started_closure_.is_null()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&RunCallback, recognition_started_closure_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&RunCallback, recognition_started_closure_)); } }
diff --git a/content/public/test/render_view_test.cc b/content/public/test/render_view_test.cc index b2b8182..4b4bc5a 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -84,24 +84,29 @@ namespace { +// This class records, and then tears down all existing RenderViews. It's +// important to do this in two steps, since tearing down a RenderView will +// mutate the container that RenderView::ForEach() iterates over. class CloseMessageSendingRenderViewVisitor : public RenderViewVisitor { public: CloseMessageSendingRenderViewVisitor() = default; ~CloseMessageSendingRenderViewVisitor() override = default; + void CloseRenderViews() { + for (RenderView* render_view : live_render_views) { + RenderViewImpl* view_impl = static_cast<RenderViewImpl*>(render_view); + view_impl->Destroy(); + } + } + protected: bool Visit(RenderView* render_view) override { - // Simulate the Widget receiving a close message. This should result on - // releasing the internal reference counts and destroying the internal - // state. - RenderWidget* render_widget = - static_cast<RenderViewImpl*>(render_view)->GetWidget(); - WidgetMsg_Close msg(render_widget->routing_id()); - render_widget->OnMessageReceived(msg); + live_render_views.push_back(render_view); return true; } private: + std::vector<RenderView*> live_render_views; DISALLOW_COPY_AND_ASSIGN(CloseMessageSendingRenderViewVisitor); }; @@ -458,6 +463,7 @@ // opened by the test. CloseMessageSendingRenderViewVisitor closing_visitor; RenderView::ForEach(&closing_visitor); + closing_visitor.CloseRenderViews(); // |view_| is ref-counted and deletes itself during the RunUntilIdle() call // below.
diff --git a/content/public/test/service_worker_test_helpers.cc b/content/public/test/service_worker_test_helpers.cc index 5712484..9652a30 100644 --- a/content/public/test/service_worker_test_helpers.cc +++ b/content/public/test/service_worker_test_helpers.cc
@@ -67,9 +67,8 @@ void OnStopped() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&StoppedObserver::OnStopped, this)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&StoppedObserver::OnStopped, this)); return; } std::move(completion_callback_ui_).Run(); @@ -100,10 +99,9 @@ const GURL& scope, base::OnceClosure completion_callback_ui) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&StopServiceWorkerForScope, context, scope, - std::move(completion_callback_ui))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&StopServiceWorkerForScope, context, scope, + std::move(completion_callback_ui))); return; } auto* context_wrapper = static_cast<ServiceWorkerContextWrapper*>(context);
diff --git a/content/public/test/test_browser_thread_bundle.cc b/content/public/test/test_browser_thread_bundle.cc index 50b989b7..9d5e289 100644 --- a/content/public/test/test_browser_thread_bundle.cc +++ b/content/public/test/test_browser_thread_bundle.cc
@@ -137,7 +137,7 @@ base::WaitableEvent io_thread_idle( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( [](base::WaitableEvent* io_thread_idle) {
diff --git a/content/public/test/test_browser_thread_bundle_unittest.cc b/content/public/test/test_browser_thread_bundle_unittest.cc index e5760e9a..0726a62c 100644 --- a/content/public/test/test_browser_thread_bundle_unittest.cc +++ b/content/public/test/test_browser_thread_bundle_unittest.cc
@@ -48,9 +48,8 @@ if (iteration == kNumHops) return; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&PostToThreadPool, iteration + 1, tasks_run)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&PostToThreadPool, iteration + 1, tasks_run)); } } // namespace @@ -85,7 +84,7 @@ if (iteration == kNumHops) return; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PostRecurringTaskToIOThread, iteration + 1, tasks_run)); } @@ -143,10 +142,9 @@ // Should create a real IO thread. If it was on the same thread the following // will timeout. base::WaitableEvent signaled_on_real_io_thread; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&base::WaitableEvent::Signal, - Unretained(&signaled_on_real_io_thread))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&base::WaitableEvent::Signal, + Unretained(&signaled_on_real_io_thread))); signaled_on_real_io_thread.TimedWait(base::TimeDelta::FromSeconds(5)); EXPECT_TRUE(signaled_on_real_io_thread.IsSignaled());
diff --git a/content/public/test/test_download_http_response.cc b/content/public/test/test_download_http_response.cc index e922ac82..5235b06 100644 --- a/content/public/test/test_download_http_response.cc +++ b/content/public/test/test_download_http_response.cc
@@ -60,8 +60,8 @@ void OnResponseSentOnServerIOThread( const TestDownloadHttpResponse::OnResponseSentCallback& callback, std::unique_ptr<TestDownloadHttpResponse::CompletedRequest> request) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(callback, std::move(request))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(callback, std::move(request))); } // The shim response object used by embedded_test_server. After this object is @@ -264,12 +264,11 @@ parameters_.injected_errors.front() <= range_.last_byte_position() && parameters_.injected_errors.front() >= range_.first_byte_position() && !parameters_.inject_error_cb.is_null()) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(parameters_.inject_error_cb, - range_.first_byte_position(), - parameters_.injected_errors.front() - - range_.first_byte_position())); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(parameters_.inject_error_cb, + range_.first_byte_position(), + parameters_.injected_errors.front() - + range_.first_byte_position())); } // Pause before sending headers. @@ -546,7 +545,7 @@ // Continue to send data after resumption. // TODO(xingliu): Unwind thread hopping callbacks here. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( pause_callback,
diff --git a/content/public/test/test_file_error_injector.cc b/content/public/test/test_file_error_injector.cc index 8146c65a..ab6f667 100644 --- a/content/public/test/test_file_error_injector.cc +++ b/content/public/test/test_file_error_injector.cc
@@ -161,7 +161,7 @@ if (download::DOWNLOAD_INTERRUPT_REASON_NONE != error_to_return) { // Don't execute a, probably successful, Initialize; just // return the error. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback_to_use), error_to_return, 0)); return; @@ -218,7 +218,7 @@ if (download::DOWNLOAD_INTERRUPT_REASON_NONE != error_to_return) { // Don't execute a, probably successful, RenameAndUniquify; just // return the error. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(callback, error_to_return, base::FilePath())); return; @@ -251,7 +251,7 @@ if (download::DOWNLOAD_INTERRUPT_REASON_NONE != error_to_return) { // Don't execute a, probably successful, RenameAndAnnotate; just // return the error. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(callback, error_to_return, base::FilePath())); return; @@ -408,13 +408,13 @@ } void TestFileErrorInjector::RecordDownloadFileConstruction() { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TestFileErrorInjector::DownloadFileCreated, this)); } void TestFileErrorInjector::RecordDownloadFileDestruction() { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TestFileErrorInjector::DestroyingDownloadFile, this)); }
diff --git a/content/public/test/test_launcher.cc b/content/public/test/test_launcher.cc index 20fe7eb4..249effa0 100644 --- a/content/public/test/test_launcher.cc +++ b/content/public/test/test_launcher.cc
@@ -69,12 +69,6 @@ // that span browser restarts. const char kPreTestPrefix[] = "PRE_"; -// Manual tests only run when --run-manual is specified. This allows writing -// tests that don't run automatically but are still in the same test binary. -// This is useful so that a team that wants to run a few tests doesn't have to -// add a new binary that must be compiled on all builds. -const char kManualTestPrefix[] = "MANUAL_"; - TestLauncherDelegate* g_launcher_delegate = nullptr; #if !defined(OS_ANDROID) // ContentMain is not run on Android in the test process, and is run via @@ -132,8 +126,7 @@ // base::TestLauncherDelegate: bool GetTests(std::vector<base::TestIdentifier>* output) override; - bool WillRunTest(const std::string& test_case_name, - const std::string& test_name) override; + base::CommandLine GetCommandLine(const std::vector<std::string>& test_names, const base::FilePath& temp_dir, base::FilePath* output_file) override; @@ -182,17 +175,6 @@ return test_name.find(kPreTestPrefix) != std::string::npos; } -bool WrapperTestLauncherDelegate::WillRunTest(const std::string& test_case_name, - const std::string& test_name) { - if (base::StartsWith(test_name, kManualTestPrefix, - base::CompareCase::SENSITIVE) && - !base::CommandLine::ForCurrentProcess()->HasSwitch(kRunManualTestsFlag)) { - return false; - } - - return true; -} - size_t WrapperTestLauncherDelegate::GetBatchSize() { return 1u; } @@ -326,9 +308,6 @@ const char kLaunchAsBrowser[] = "as-browser"; -// See kManualTestPrefix above. -const char kRunManualTestsFlag[] = "run-manual"; - const char kSingleProcessTestsFlag[] = "single_process"; const char kWaitForDebuggerWebUI[] = "wait-for-debugger-webui";
diff --git a/content/public/test/test_launcher.h b/content/public/test/test_launcher.h index b57325f31a..062640c7 100644 --- a/content/public/test/test_launcher.h +++ b/content/public/test/test_launcher.h
@@ -24,7 +24,6 @@ extern const char kEmptyTestName[]; extern const char kHelpFlag[]; extern const char kLaunchAsBrowser[]; -extern const char kRunManualTestsFlag[]; extern const char kSingleProcessTestsFlag[]; // Flag that causes only the kEmptyTestName test to be run.
diff --git a/content/public/test/test_navigation_throttle.cc b/content/public/test/test_navigation_throttle.cc index 9277210..09244ece 100644 --- a/content/public/test/test_navigation_throttle.cc +++ b/content/public/test/test_navigation_throttle.cc
@@ -87,7 +87,7 @@ method_properties_[method].result; if (method_properties_[method].synchrony == ASYNCHRONOUS) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TestNavigationThrottle::TestNavigationThrottle:: CancelAsynchronously,
diff --git a/content/public/test/test_service_manager_context.cc b/content/public/test/test_service_manager_context.cc index 011e1b2..8f1261e1 100644 --- a/content/public/test/test_service_manager_context.cc +++ b/content/public/test/test_service_manager_context.cc
@@ -14,7 +14,7 @@ TestServiceManagerContext::TestServiceManagerContext() { context_.reset(new ServiceManagerContext( - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}))); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}))); auto* system_connection = ServiceManagerConnection::GetForProcess(); system_connection->Start(); }
diff --git a/content/public/test/test_utils.cc b/content/public/test/test_utils.cc index acaaaf6..8b00402 100644 --- a/content/public/test/test_utils.cc +++ b/content/public/test/test_utils.cc
@@ -343,7 +343,7 @@ } void InProcessUtilityThreadHelper::CheckHasRunningChildProcess() { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &InProcessUtilityThreadHelper::CheckHasRunningChildProcessOnIO,
diff --git a/content/public/test/text_input_test_utils_mac.mm b/content/public/test/text_input_test_utils_mac.mm index f396c2a..3a8d16a 100644 --- a/content/public/test/text_input_test_utils_mac.mm +++ b/content/public/test/text_input_test_utils_mac.mm
@@ -43,8 +43,8 @@ DCHECK_CURRENTLY_ON(BrowserThread::IO); if (message.type() == TextInputClientReplyMsg_GotStringForRange::ID) { if (!string_for_range_callback_.is_null()) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - string_for_range_callback_); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + string_for_range_callback_); } received_string_from_range_ = true; @@ -60,8 +60,8 @@ // Stop the message loop if it is running. if (message_loop_runner_) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - message_loop_runner_->QuitClosure()); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + message_loop_runner_->QuitClosure()); } }
diff --git a/content/public/test/url_loader_interceptor.cc b/content/public/test/url_loader_interceptor.cc index 40c16f1..b229021 100644 --- a/content/public/test/url_loader_interceptor.cc +++ b/content/public/test/url_loader_interceptor.cc
@@ -479,7 +479,7 @@ if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) { if (use_runloop_) { base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&URLLoaderInterceptor::IOState::Initialize, io_thread_, std::move(completion_status_callback), @@ -488,12 +488,11 @@ } else { base::OnceClosure wrapped_callback = base::BindOnce( [](base::OnceClosure callback) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - std::move(callback)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, std::move(callback)); }, std::move(ready_callback)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&URLLoaderInterceptor::IOState::Initialize, io_thread_, std::move(completion_status_callback), @@ -527,16 +526,14 @@ if (use_runloop_) { base::RunLoop run_loop; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&URLLoaderInterceptor::IOState::Shutdown, io_thread_, - run_loop.QuitClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&URLLoaderInterceptor::IOState::Shutdown, + io_thread_, run_loop.QuitClosure())); run_loop.Run(); } else { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&URLLoaderInterceptor::IOState::Shutdown, io_thread_, - base::OnceClosure())); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&URLLoaderInterceptor::IOState::Shutdown, + io_thread_, base::OnceClosure())); } } @@ -611,7 +608,7 @@ int process_id, network::mojom::URLLoaderFactoryPtrInfo original_factory) { if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce( &URLLoaderInterceptor::CreateURLLoaderFactoryForSubresources,
diff --git a/content/renderer/DEPS b/content/renderer/DEPS index d486d6c..41ba9c59 100644 --- a/content/renderer/DEPS +++ b/content/renderer/DEPS
@@ -1,6 +1,9 @@ include_rules = [ # Allow inclusion of specific components that we depend on. # See comment in content/DEPS for which components are allowed. + # *********************************** NOTE *********************************** + # If adding a new component dependency, email content/OWNERS first. + # **************************************************************************** "+components/discardable_memory/client", "+components/metrics", "+components/metrics:single_sample_metrics", @@ -8,6 +11,10 @@ "+components/url_formatter", "+components/viz/client", "+components/viz/common", + # *********************************** NOTE *********************************** + # If adding a new component dependency, email content/OWNERS first. + # **************************************************************************** + "+content/public/child", "+content/public/renderer", "+content/child",
diff --git a/content/renderer/compositor/layer_tree_view.cc b/content/renderer/compositor/layer_tree_view.cc index fd82a29..09f92248 100644 --- a/content/renderer/compositor/layer_tree_view.cc +++ b/content/renderer/compositor/layer_tree_view.cc
@@ -84,8 +84,9 @@ // The image worker thread needs to allow waiting since it makes discardable // shared memory allocations which need to make synchronous calls to the // IO thread. - params.image_worker_task_runner = base::CreateSequencedTaskRunnerWithTraits( - {base::WithBaseSyncPrimitives(), base::TaskPriority::USER_VISIBLE, + params.image_worker_task_runner = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::WithBaseSyncPrimitives(), + base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}); } if (!is_threaded) {
diff --git a/content/renderer/input/widget_input_handler_manager.cc b/content/renderer/input/widget_input_handler_manager.cc index a527fddc..cc82b0f 100644 --- a/content/renderer/input/widget_input_handler_manager.cc +++ b/content/renderer/input/widget_input_handler_manager.cc
@@ -469,6 +469,11 @@ bool sync_compositing) { DCHECK(InputThreadTaskRunner()->BelongsToCurrentThread()); + // It is possible that the input_handle has already been destroyed before this + // Init() call was invoked. If so, early out. + if (!input_handler) + return; + // If there's no compositor thread (i.e. we're in a LayoutTest), force input // to go through the main thread. bool force_input_handling_on_main = !compositor_task_runner_;
diff --git a/content/renderer/loader/code_cache_loader_impl.cc b/content/renderer/loader/code_cache_loader_impl.cc index 9c639fd..55d1bf99 100644 --- a/content/renderer/loader/code_cache_loader_impl.cc +++ b/content/renderer/loader/code_cache_loader_impl.cc
@@ -25,7 +25,7 @@ base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({}); + base::CreateSingleThreadTaskRunner({base::ThreadPool()}); // Also watch for terminate requests from the main thread when running on // worker threads.
diff --git a/content/renderer/loader/resource_dispatcher.cc b/content/renderer/loader/resource_dispatcher.cc index 36f4031d..f2f028b1 100644 --- a/content/renderer/loader/resource_dispatcher.cc +++ b/content/renderer/loader/resource_dispatcher.cc
@@ -450,7 +450,7 @@ // pointers to |sync_load_response| and |event| as this stack frame will // survive until the request is complete. scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({}); + base::CreateSingleThreadTaskRunner({base::ThreadPool()}); task_runner->PostTask( FROM_HERE, base::BindOnce(&SyncLoadContext::StartAsyncWithWaitableEvent,
diff --git a/content/renderer/loader/web_worker_fetch_context_impl.cc b/content/renderer/loader/web_worker_fetch_context_impl.cc index 34bd415f..669fd4a0 100644 --- a/content/renderer/loader/web_worker_fetch_context_impl.cc +++ b/content/renderer/loader/web_worker_fetch_context_impl.cc
@@ -589,8 +589,9 @@ mojo::MakeRequest(&host_ptr_info)); // To avoid potential dead-lock while synchronous loading, create the // SubresourceLoaderFactory on a background thread. - auto task_runner = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + auto task_runner = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, base::BindOnce(
diff --git a/content/renderer/media/android/stream_texture_factory.cc b/content/renderer/media/android/stream_texture_factory.cc index 6fcea5f..fb59771b 100644 --- a/content/renderer/media/android/stream_texture_factory.cc +++ b/content/renderer/media/android/stream_texture_factory.cc
@@ -77,9 +77,12 @@ const gfx::Size& size, gpu::Mailbox* mailbox, gpu::SyncToken* unverified_sync_token) { + // TODO(vikassoni): Remove CHECK after debugging. + CHECK(host_); *mailbox = host_->CreateSharedImage(size); if (!mailbox) return; + CHECK(host_); *unverified_sync_token = host_->GenUnverifiedSyncToken(); }
diff --git a/content/renderer/media/audio/audio_device_factory.cc b/content/renderer/media/audio/audio_device_factory.cc index 869349c0..11ddcb5 100644 --- a/content/renderer/media/audio/audio_device_factory.cc +++ b/content/renderer/media/audio/audio_device_factory.cc
@@ -195,8 +195,8 @@ // There's one process wide instance that lives on the render thread. static base::NoDestructor<AudioRendererSinkCacheImpl> cache( - base::CreateSequencedTaskRunnerWithTraits( - {base::TaskPriority::BEST_EFFORT, + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}), base::BindRepeating(&AudioDeviceFactory::NewAudioRendererSink, blink::WebAudioDeviceSourceType::kNone),
diff --git a/content/renderer/media/stream/user_media_client_impl.cc b/content/renderer/media/stream/user_media_client_impl.cc index 2bfbf5b4..7a10a7b 100644 --- a/content/renderer/media/stream/user_media_client_impl.cc +++ b/content/renderer/media/stream/user_media_client_impl.cc
@@ -51,7 +51,8 @@ } // namespace -UserMediaClientImpl::Request::Request(std::unique_ptr<UserMediaRequest> request) +UserMediaClientImpl::Request::Request( + std::unique_ptr<UserMediaRequestInfo> request) : user_media_request_(std::move(request)) { DCHECK(user_media_request_); DCHECK(apply_constraints_request_.IsNull()); @@ -95,7 +96,7 @@ Request&& other) = default; UserMediaClientImpl::Request::~Request() = default; -std::unique_ptr<UserMediaRequest> +std::unique_ptr<UserMediaRequestInfo> UserMediaClientImpl::Request::MoveUserMediaRequest() { return std::move(user_media_request_); } @@ -171,8 +172,9 @@ web_request.OwnerDocument().IsNull() ? nullptr : web_request.OwnerDocument().GetFrame()); - std::unique_ptr<UserMediaRequest> request_info = - std::make_unique<UserMediaRequest>(request_id, web_request, user_gesture); + std::unique_ptr<UserMediaRequestInfo> request_info = + std::make_unique<UserMediaRequestInfo>(request_id, web_request, + user_gesture); pending_request_infos_.push_back(Request(std::move(request_info))); if (!is_processing_request_) MaybeProcessNextRequestInfo(); @@ -252,7 +254,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); { // TODO(guidou): Remove this conditional logging. https://crbug.com/764293 - UserMediaRequest* request = user_media_processor_->CurrentRequest(); + UserMediaRequestInfo* request = user_media_processor_->CurrentRequest(); if (request && request->web_request == web_request) { blink::WebRtcLogMessage(base::StringPrintf( "UMCI::CancelUserMediaRequest. request_id=%d", request->request_id));
diff --git a/content/renderer/media/stream/user_media_client_impl.h b/content/renderer/media/stream/user_media_client_impl.h index fa063637..4565f1c 100644 --- a/content/renderer/media/stream/user_media_client_impl.h +++ b/content/renderer/media/stream/user_media_client_impl.h
@@ -69,16 +69,16 @@ private: class Request { public: - explicit Request(std::unique_ptr<UserMediaRequest> request); + explicit Request(std::unique_ptr<UserMediaRequestInfo> request); explicit Request(const blink::WebApplyConstraintsRequest& request); explicit Request(const blink::WebMediaStreamTrack& request); Request(Request&& other); Request& operator=(Request&& other); ~Request(); - std::unique_ptr<UserMediaRequest> MoveUserMediaRequest(); + std::unique_ptr<UserMediaRequestInfo> MoveUserMediaRequest(); - UserMediaRequest* user_media_request() const { + UserMediaRequestInfo* user_media_request() const { return user_media_request_.get(); } const blink::WebApplyConstraintsRequest& apply_constraints_request() const { @@ -95,7 +95,7 @@ bool IsStopTrack() const { return !web_track_to_stop_.IsNull(); } private: - std::unique_ptr<UserMediaRequest> user_media_request_; + std::unique_ptr<UserMediaRequestInfo> user_media_request_; blink::WebApplyConstraintsRequest apply_constraints_request_; blink::WebMediaStreamTrack web_track_to_stop_; };
diff --git a/content/renderer/media/stream/user_media_client_impl_unittest.cc b/content/renderer/media/stream/user_media_client_impl_unittest.cc index 3ba1eb6..3598936 100644 --- a/content/renderer/media/stream/user_media_client_impl_unittest.cc +++ b/content/renderer/media/stream/user_media_client_impl_unittest.cc
@@ -17,7 +17,6 @@ #include "base/test/scoped_task_environment.h" #include "content/child/child_process.h" #include "content/renderer/media/stream/mock_mojo_media_stream_dispatcher_host.h" -#include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "media/audio/audio_device_description.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gtest/include/gtest/gtest.h" @@ -158,8 +157,7 @@ : public blink::MockMediaStreamVideoSource { public: MockMediaStreamVideoCapturerSource(const blink::MediaStreamDevice& device, - const SourceStoppedCallback& stop_callback, - PeerConnectionDependencyFactory* factory) + const SourceStoppedCallback& stop_callback) : blink::MockMediaStreamVideoSource() { SetDevice(device); SetStopCallback(stop_callback); @@ -301,7 +299,6 @@ class UserMediaProcessorUnderTest : public UserMediaProcessor { public: UserMediaProcessorUnderTest( - PeerConnectionDependencyFactory* dependency_factory, std::unique_ptr<blink::WebMediaStreamDeviceObserver> media_stream_device_observer, blink::mojom::MediaDevicesDispatcherHostPtr media_devices_dispatcher, @@ -313,7 +310,6 @@ &UserMediaProcessorUnderTest::media_devices_dispatcher, base::Unretained(this)), blink::scheduler::GetSingleThreadTaskRunnerForTesting()), - factory_(dependency_factory), media_devices_dispatcher_(std::move(media_devices_dispatcher)), state_(state) {} @@ -356,7 +352,7 @@ const blink::WebPlatformMediaStreamSource::SourceStoppedCallback& stop_callback) override { video_source_ = - new MockMediaStreamVideoCapturerSource(device, stop_callback, factory_); + new MockMediaStreamVideoCapturerSource(device, stop_callback); return base::WrapUnique(video_source_); } @@ -423,7 +419,6 @@ .Run(source, blink::mojom::MediaStreamRequestResult::OK, ""); } - PeerConnectionDependencyFactory* factory_; blink::mojom::MediaDevicesDispatcherHostPtr media_devices_dispatcher_; MockMediaStreamVideoCapturerSource* video_source_ = nullptr; MockLocalMediaStreamAudioSource* local_audio_source_ = nullptr; @@ -473,15 +468,13 @@ void SetUp() override { // Create our test object. - dependency_factory_.reset(new MockPeerConnectionDependencyFactory()); - msd_observer_ = new blink::WebMediaStreamDeviceObserver(nullptr); blink::mojom::MediaDevicesDispatcherHostPtr user_media_processor_host_proxy; binding_user_media_processor_.Bind( mojo::MakeRequest(&user_media_processor_host_proxy)); user_media_processor_ = new UserMediaProcessorUnderTest( - dependency_factory_.get(), base::WrapUnique(msd_observer_), + base::WrapUnique(msd_observer_), std::move(user_media_processor_host_proxy), &state_); blink::mojom::MediaStreamDispatcherHostPtr dispatcher_host = mock_dispatcher_host_.CreateInterfacePtrAndBind(); @@ -649,7 +642,6 @@ UserMediaProcessorUnderTest* user_media_processor_ = nullptr; // Owned by |user_media_client_impl_| std::unique_ptr<UserMediaClientImplUnderTest> user_media_client_impl_; - std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_; RequestState state_ = REQUEST_NOT_STARTED; };
diff --git a/content/renderer/media/stream/user_media_processor.cc b/content/renderer/media/stream/user_media_processor.cc index 5d1b0a03..370dcca 100644 --- a/content/renderer/media/stream/user_media_processor.cc +++ b/content/renderer/media/stream/user_media_processor.cc
@@ -209,7 +209,7 @@ } // namespace -UserMediaRequest::UserMediaRequest( +UserMediaRequestInfo::UserMediaRequestInfo( int request_id, const blink::WebUserMediaRequest& web_request, bool is_processing_user_gesture) @@ -231,7 +231,7 @@ GENERATED, }; - explicit RequestInfo(std::unique_ptr<UserMediaRequest> request); + explicit RequestInfo(std::unique_ptr<UserMediaRequestInfo> request); void StartAudioTrack(const blink::WebMediaStreamTrack& track, bool is_pending); @@ -247,7 +247,7 @@ MediaStreamRequestResult result, const blink::WebString& result_name); - UserMediaRequest* request() { return request_.get(); } + UserMediaRequestInfo* request() { return request_.get(); } int request_id() const { return request_->request_id; } State state() const { return state_; } @@ -328,7 +328,7 @@ // that |this| might be deleted when the function returns. void CheckAllTracksStarted(); - std::unique_ptr<UserMediaRequest> request_; + std::unique_ptr<UserMediaRequestInfo> request_; State state_ = State::NOT_SENT_FOR_GENERATION; blink::AudioCaptureSettings audio_capture_settings_; bool is_audio_content_capture_ = false; @@ -352,7 +352,7 @@ // TODO(guidou): Initialize request_result_name_ as a null blink::WebString. // https://crbug.com/764293 UserMediaProcessor::RequestInfo::RequestInfo( - std::unique_ptr<UserMediaRequest> request) + std::unique_ptr<UserMediaRequestInfo> request) : request_(std::move(request)), security_origin_(url::Origin(request_->web_request.GetSecurityOrigin())), request_result_name_("") {} @@ -464,12 +464,12 @@ StopAllProcessing(); } -UserMediaRequest* UserMediaProcessor::CurrentRequest() { +UserMediaRequestInfo* UserMediaProcessor::CurrentRequest() { return current_request_info_ ? current_request_info_->request() : nullptr; } void UserMediaProcessor::ProcessRequest( - std::unique_ptr<UserMediaRequest> request, + std::unique_ptr<UserMediaRequestInfo> request, base::OnceClosure callback) { DCHECK(!request_completed_cb_); DCHECK(!current_request_info_);
diff --git a/content/renderer/media/stream/user_media_processor.h b/content/renderer/media/stream/user_media_processor.h index 332997e5..ed69043 100644 --- a/content/renderer/media/stream/user_media_processor.h +++ b/content/renderer/media/stream/user_media_processor.h
@@ -45,10 +45,10 @@ // TODO(guidou): Add |request_id| and |is_processing_user_gesture| to // blink::WebUserMediaRequest and remove this struct. -struct UserMediaRequest { - UserMediaRequest(int request_id, - const blink::WebUserMediaRequest& web_request, - bool is_processing_user_gesture); +struct UserMediaRequestInfo { + UserMediaRequestInfo(int request_id, + const blink::WebUserMediaRequest& web_request, + bool is_processing_user_gesture); const int request_id; const blink::WebUserMediaRequest web_request; const bool is_processing_user_gesture; @@ -78,13 +78,13 @@ // during the execution of a task on the main thread unless ProcessRequest or // DeleteWebRequest are invoked. // TODO(guidou): Remove this method. https://crbug.com/764293 - UserMediaRequest* CurrentRequest(); + UserMediaRequestInfo* CurrentRequest(); // Starts processing |request| in order to create a new MediaStream. When // processing of |request| is complete, it notifies by invoking |callback|. // This method must be called only if there is no request currently being // processed. - void ProcessRequest(std::unique_ptr<UserMediaRequest> request, + void ProcessRequest(std::unique_ptr<UserMediaRequestInfo> request, base::OnceClosure callback); // If |web_request| is the request currently being processed, stops processing
diff --git a/content/renderer/mhtml_handle_writer.cc b/content/renderer/mhtml_handle_writer.cc index c6eb1c0..8a0cfc50 100644 --- a/content/renderer/mhtml_handle_writer.cc +++ b/content/renderer/mhtml_handle_writer.cc
@@ -96,8 +96,9 @@ mhtml_contents_ = std::move(mhtml_contents); scoped_refptr<base::SequencedTaskRunner> task_runner = - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, base::BindOnce(&MHTMLProducerHandleWriter::BeginWatchingHandle,
diff --git a/content/renderer/pepper/host_globals.cc b/content/renderer/pepper/host_globals.cc index a98bbec..1a4558a 100644 --- a/content/renderer/pepper/host_globals.cc +++ b/content/renderer/pepper/host_globals.cc
@@ -189,7 +189,8 @@ base::TaskRunner* HostGlobals::GetFileTaskRunner() { if (!file_task_runner_) - file_task_runner_ = base::CreateTaskRunnerWithTraits({base::MayBlock()}); + file_task_runner_ = + base::CreateTaskRunner({base::ThreadPool(), base::MayBlock()}); return file_task_runner_.get(); }
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 60cc6f4..27dd917 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -761,18 +761,17 @@ void WriteContents(std::vector<WebThreadSafeData> mhtml_contents) { // Using base::Unretained is safe, as calls to WriteContents() always // deletes |handle| upon Finish(). - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, + base::PostTask( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&MHTMLHandleWriter::WriteContents, base::Unretained(handle_), std::move(mhtml_contents))); } // Within the context of the delegate, only for premature write finish. void Finish(mojom::MhtmlSaveStatus save_status) { - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock()}, - base::BindOnce(&MHTMLHandleWriter::Finish, base::Unretained(handle_), - save_status)); + base::PostTask(FROM_HERE, {base::ThreadPool(), base::MayBlock()}, + base::BindOnce(&MHTMLHandleWriter::Finish, + base::Unretained(handle_), save_status)); } private: @@ -3142,8 +3141,7 @@ } base::Optional<url::Origin> origin_lock; - if (base::FeatureList::IsEnabled(features::kPdfIsolation) && - GetContentClient()->renderer()->IsOriginIsolatedPepperPlugin(info.path)) { + if (GetContentClient()->renderer()->IsOriginIsolatedPepperPlugin(info.path)) { origin_lock = url::Origin::Create(GURL(params.url)); }
diff --git a/content/renderer/render_frame_proxy.cc b/content/renderer/render_frame_proxy.cc index d22af61..2a420de 100644 --- a/content/renderer/render_frame_proxy.cc +++ b/content/renderer/render_frame_proxy.cc
@@ -11,7 +11,6 @@ #include "base/command_line.h" #include "base/lazy_instance.h" -#include "components/viz/common/features.h" #include "components/viz/common/surfaces/local_surface_id_allocation.h" #include "content/common/content_switches_internal.h" #include "content/common/frame_message_structs.h" @@ -253,8 +252,6 @@ g_frame_proxy_map.Get().insert(std::make_pair(web_frame_, this)); CHECK(result.second) << "Inserted a duplicate item."; - enable_surface_synchronization_ = features::IsSurfaceSynchronizationEnabled(); - if (parent_is_local) compositing_helper_ = std::make_unique<ChildFrameCompositingHelper>(this); @@ -389,8 +386,6 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameProxy, msg) IPC_MESSAGE_HANDLER(FrameMsg_ChildFrameProcessGone, OnChildFrameProcessGone) - IPC_MESSAGE_HANDLER(FrameMsg_FirstSurfaceActivation, - OnFirstSurfaceActivation) IPC_MESSAGE_HANDLER(FrameMsg_IntrinsicSizingInfoOfChildChanged, OnIntrinsicSizingInfoOfChildChanged) IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener, OnUpdateOpener) @@ -457,21 +452,6 @@ screen_info().device_scale_factor); } -void RenderFrameProxy::OnFirstSurfaceActivation( - const viz::SurfaceInfo& surface_info) { - DCHECK(!enable_surface_synchronization_); - - // If this WebFrame has already been detached, its parent will be null. This - // can happen when swapping a WebRemoteFrame with a WebLocalFrame, where this - // message may arrive after the frame was removed from the frame tree, but - // before the frame has been destroyed. http://crbug.com/446575. - if (!web_frame()->Parent()) - return; - - compositing_helper_->SetSurfaceId(surface_info.id(), local_frame_size(), - cc::DeadlinePolicy::UseDefaultDeadline()); -} - void RenderFrameProxy::OnIntrinsicSizingInfoOfChildChanged( blink::WebIntrinsicSizingInfo sizing_info) { web_frame()->IntrinsicSizingInfoChanged(sizing_info); @@ -673,16 +653,13 @@ ->GetCurrentLocalSurfaceIdAllocation(); } - if (enable_surface_synchronization_) { - // If we're synchronizing surfaces, then use an infinite deadline to ensure - // everything is synchronized. - cc::DeadlinePolicy deadline = - capture_sequence_number_changed - ? cc::DeadlinePolicy::UseInfiniteDeadline() - : cc::DeadlinePolicy::UseDefaultDeadline(); - viz::SurfaceId surface_id(frame_sink_id_, GetLocalSurfaceId()); - compositing_helper_->SetSurfaceId(surface_id, local_frame_size(), deadline); - } + // If we're synchronizing surfaces, then use an infinite deadline to ensure + // everything is synchronized. + cc::DeadlinePolicy deadline = capture_sequence_number_changed + ? cc::DeadlinePolicy::UseInfiniteDeadline() + : cc::DeadlinePolicy::UseDefaultDeadline(); + viz::SurfaceId surface_id(frame_sink_id_, GetLocalSurfaceId()); + compositing_helper_->SetSurfaceId(surface_id, local_frame_size(), deadline); bool rect_changed = !sent_visual_properties_ || sent_visual_properties_->screen_space_rect !=
diff --git a/content/renderer/render_frame_proxy.h b/content/renderer/render_frame_proxy.h index d8fca3b..37145f1 100644 --- a/content/renderer/render_frame_proxy.h +++ b/content/renderer/render_frame_proxy.h
@@ -32,10 +32,6 @@ struct WebScrollIntoViewParams; } -namespace viz { -class SurfaceInfo; -} - namespace content { class ChildFrameCompositingHelper; @@ -235,7 +231,6 @@ void OnDeleteProxy(); void OnChildFrameProcessGone(); void OnCompositorFrameSwapped(const IPC::Message& message); - void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info); void OnIntrinsicSizingInfoOfChildChanged( blink::WebIntrinsicSizingInfo sizing_info); void OnUpdateOpener(int opener_routing_id); @@ -327,8 +322,6 @@ std::unique_ptr<viz::ParentLocalSurfaceIdAllocator> parent_local_surface_id_allocator_; - bool enable_surface_synchronization_ = false; - gfx::Rect last_intersection_rect_; gfx::Rect last_compositor_visible_rect_; blink::FrameOcclusionState last_occlusion_state_ =
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 06fa941..97b0d7cb 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -1142,9 +1142,9 @@ // be the same thread on which the rendering context was initialized. This // is why this must be a SingleThreadTaskRunner instead of a // SequencedTaskRunner. - video_frame_compositor_task_runner_ = - base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + video_frame_compositor_task_runner_ = base::CreateSingleThreadTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); } return video_frame_compositor_task_runner_; @@ -2023,6 +2023,12 @@ GetWebMainThreadScheduler()->DefaultTaskRunner()); } +void RenderThreadImpl::DestroyView(int32_t view_id) { + RenderViewImpl* view = RenderViewImpl::FromRoutingID(view_id); + DCHECK(view); + view->Destroy(); +} + void RenderThreadImpl::CreateFrame(mojom::CreateFrameParamsPtr params) { CompositorDependencies* compositor_deps = this; service_manager::mojom::InterfaceProviderPtr interface_provider(
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 543b682..05da31b 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -506,6 +506,7 @@ void CreateEmbedderRendererService( service_manager::mojom::ServiceRequest service_request) override; void CreateView(mojom::CreateViewParamsPtr params) override; + void DestroyView(int32_t view_id) override; void CreateFrame(mojom::CreateFrameParamsPtr params) override; void CreateFrameProxy( int32_t routing_id,
diff --git a/content/renderer/render_thread_impl_browsertest.cc b/content/renderer/render_thread_impl_browsertest.cc index 99e099c..a9896ca 100644 --- a/content/renderer/render_thread_impl_browsertest.cc +++ b/content/renderer/render_thread_impl_browsertest.cc
@@ -162,7 +162,7 @@ browser_threads_.reset( new TestBrowserThreadBundle(TestBrowserThreadBundle::REAL_IO_THREAD)); scoped_refptr<base::SingleThreadTaskRunner> io_task_runner = - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); + base::CreateSingleThreadTaskRunner({BrowserThread::IO}); InitializeMojo(); mojo_ipc_support_.reset(new mojo::core::ScopedIPCSupport(
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index bf66006..1b8b9cf9e 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -435,17 +435,6 @@ webview->MainFrame()->VisibleContentRect().width; } - // Closes a view created during the test, i.e. not the |view()|. Checks that - // the main frame is detached and deleted, and makes sure the view does not - // leak. - void CloseRenderWidget(RenderWidget* widget) { - WidgetMsg_Close msg(widget->routing_id()); - widget->OnMessageReceived(msg); - - // WidgetMsg_Close posts a task to do the actual closing. Let that run. - base::RunLoop().RunUntilIdle(); - } - private: std::unique_ptr<MockKeyboard> mock_keyboard_; }; @@ -872,9 +861,6 @@ ->BeginNavigation(std::move(popup_navigation_info)); EXPECT_TRUE(render_thread_->sink().GetUniqueMessageMatching( FrameHostMsg_OpenURL::ID)); - - RenderWidget* render_widget = new_view->GetWidget(); - CloseRenderWidget(render_widget); } class AlwaysForkingRenderViewTest : public RenderViewImplTest {
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 0335070..689d764 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -476,14 +476,8 @@ scoped_refptr<base::SingleThreadTaskRunner> task_runner) { DCHECK(RenderThread::IsMainThread()); - // RenderView used to inherit from RenderWidget. Creating a delegate - // interface and explicitly passing ownership of ourselves to the - // RenderWidget preserves the lifetime semantics. This is a stepping - // stone to having RenderWidget creation taken out of the RenderViewImpl - // constructor. See the corresponding explicit reset() of the delegate - // in the ~RenderWidget(). Also, I hate inheritance. render_widget_ = render_widget; - GetWidget()->set_delegate(base::WrapUnique(this)); + GetWidget()->set_delegate(this); RenderThread::Get()->AddRoute(routing_id_, this); #if defined(OS_ANDROID) @@ -1055,6 +1049,12 @@ return render_view; } +void RenderViewImpl::Destroy() { + GetWidget()->PrepareForClose(); + GetWidget()->Close(); + delete this; +} + // static void RenderViewImpl::InstallCreateHook(RenderViewImpl* ( *create_render_view_impl)(CompositorDependencies* compositor_deps,
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index caf21b4..3e525b05 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -103,8 +103,6 @@ public RenderWidgetDelegate, public RenderView { public: - ~RenderViewImpl() override; - // Creates a new RenderView. Note that if the original opener has been closed, // |params.window_was_created_with_opener| will be true and // |params.opener_frame_route_id| will be MSG_ROUTING_NONE. @@ -119,6 +117,11 @@ RenderWidget::ShowCallback show_callback, scoped_refptr<base::SingleThreadTaskRunner> task_runner); + // Instances of this object are created by and destroyed by the browser + // process. This method must be called exactly once by the IPC subsystem when + // the browser wishes the object to be destroyed. + void Destroy(); + // Used by web_test_support to hook into the creation of RenderViewImpls. static void InstallCreateHook(RenderViewImpl* (*create_render_view_impl)( CompositorDependencies* compositor_deps, @@ -293,6 +296,7 @@ protected: RenderViewImpl(CompositorDependencies* compositor_deps, const mojom::CreateViewParams& params); + ~RenderViewImpl() override; // Called when Page visibility is changed, to update the View/Page in blink. // This is separate from the IPC handlers as tests may call this and need to
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 1590e2b..e4d0c2f 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -448,6 +448,7 @@ : routing_id_(widget_routing_id), compositor_deps_(compositor_deps), webwidget_internal_(nullptr), + delegate_(nullptr), auto_resize_mode_(false), is_hidden_(hidden), compositor_never_visible_(never_visible), @@ -525,7 +526,13 @@ void RenderWidget::CloseForFrame() { DCHECK(for_child_local_root_frame_); - OnClose(); + PrepareForClose(); + + // The RenderWidget may be deattached from JS, which in turn may be called + // in a re-entrant context. We cannot synchronously destroy the object, so we + // post a task to do so later. + GetCleanupTaskRunner()->PostNonNestableTask( + FROM_HERE, base::BindOnce(&RenderWidget::Close, this)); } void RenderWidget::Init(ShowCallback show_callback, WebWidget* web_widget) { @@ -571,8 +578,9 @@ mouse_lock_dispatcher_.reset(new RenderWidgetMouseLockDispatcher(this)); RenderThread::Get()->AddRoute(routing_id_, this); - // Take a reference on behalf of the RenderThread. This will be balanced - // when we receive WidgetMsg_Close. + // Take a reference. This object is either owned by the browser process, or by + // RenderFrame. Both will eventually call Close() when they wish to destroy + // this object. AddRef(); } @@ -705,6 +713,14 @@ } void RenderWidget::OnClose() { + // It is always safe to synchronously destroy this object from an IPC message. + // That's because the IPC message is asynchronous, which means it can never be + // called from a nested context. + PrepareForClose(); + Close(); +} + +void RenderWidget::PrepareForClose() { DCHECK(RenderThread::IsMainThread()); if (closing_) return; @@ -732,23 +748,6 @@ // already-deleted frame. CloseWebWidget(); } - // If there is a Send call on the stack, then it could be dangerous to close - // now. Post a task that only gets invoked when there are no nested message - // loops. - // - // The asynchronous Close() takes an owning reference to |this| keeping the - // object alive beyond the Release() below. It is the last reference to this - // object. - // - // TODO(https://crbug.com/545684): The actual lifetime for RenderWidget - // seems to be single-owner. It is either owned by "IPC" events (popup, - // mainframe, and fullscreen), or a RenderFrame. If Close() self-deleting, - // all the ref-counting mess could be removed. - GetCleanupTaskRunner()->PostNonNestableTask( - FROM_HERE, base::BindOnce(&RenderWidget::Close, this)); - - // Balances the AddRef taken when we called AddRoute. - Release(); } void RenderWidget::OnSynchronizeVisualProperties( @@ -1945,6 +1944,9 @@ // Note the ACK is a control message going to the RenderProcessHost. RenderThread::Get()->Send(new WidgetHostMsg_Close_ACK(routing_id())); closed_ = true; + + // Balances the AddRef in Init. + Release(); } void RenderWidget::CloseWebWidget() {
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index ca3618a..3b3fac5b 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -217,16 +217,13 @@ void InitForChildLocalRoot(blink::WebFrameWidget* web_frame_widget); // Sets a delegate to handle certain RenderWidget operations that need an - // escape to the RenderView. Also take ownership until RenderWidget lifetime - // has been reassociated with the RenderFrame. This is only set on Widgets - // that are associated with the RenderView. - // TODO(ajwong): Do not have RenderWidget own the delegate. - void set_delegate(std::unique_ptr<RenderWidgetDelegate> delegate) { + // escape to the RenderView. + void set_delegate(RenderWidgetDelegate* delegate) { DCHECK(!delegate_); - delegate_ = std::move(delegate); + delegate_ = delegate; } - RenderWidgetDelegate* delegate() const { return delegate_.get(); } + RenderWidgetDelegate* delegate() const { return delegate_; } // Returns the RenderWidget for the given routing ID. static RenderWidget* FromRoutingID(int32_t routing_id); @@ -234,6 +231,15 @@ // Closes a RenderWidget that was created by |CreateForFrame|. void CloseForFrame(); + // RenderWidgets cannot always be synchronously destroyed, since that may + // happen in a re-entrancy scenario, and there may be existing references on + // the stack. This method shuts down further sources of input to the + // RenderWidget. This must be called before Close(). + void PrepareForClose(); + + // Close the underlying WebWidget and stop the compositor. + virtual void Close(); + int32_t routing_id() const { return routing_id_; } CompositorDependencies* compositor_deps() const { return compositor_deps_; } @@ -699,9 +705,6 @@ mojom::WidgetRequest widget_request); ~RenderWidget() override; - // Close the underlying WebWidget and stop the compositor. - virtual void Close(); - // Notify subclasses that we initiated the paint operation. virtual void DidInitiatePaint() {} @@ -936,7 +939,9 @@ blink::WebWidget* webwidget_internal_; // The delegate for this object which is just a RenderViewImpl. - std::unique_ptr<RenderWidgetDelegate> delegate_; + // This member is non-null if and only if the RenderWidget is associated with + // a RenderViewImpl. + RenderWidgetDelegate* delegate_; // This is lazily constructed and must not outlive webwidget_. std::unique_ptr<LayerTreeView> layer_tree_view_;
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 86699f8c..f3db3ef 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -226,7 +226,6 @@ protected: ~InteractiveRenderWidget() override { - Close(); webwidget_internal_ = nullptr; } @@ -270,13 +269,18 @@ // testing::Test implementation. void SetUp() override { widget_ = new InteractiveRenderWidget(&compositor_deps_); - // RenderWidget::Init does an AddRef that's balanced by a browser-initiated - // Close IPC. That Close will never happen in this test, so do a Release - // here to ensure |widget_| is properly freed. - widget_->Release(); - DCHECK(widget_->HasOneRef()); } + void DestroyWidget() { + if (widget_) { + widget_->PrepareForClose(); + widget_->Close(); + widget_.reset(); + } + } + + void TearDown() override { DestroyWidget(); } + InteractiveRenderWidget* widget() const { return widget_.get(); } const base::HistogramTester& histogram_tester() const { @@ -501,11 +505,6 @@ // testing::Test implementation. void SetUp() override { widget_ = new PopupRenderWidget(&compositor_deps_); - // RenderWidget::Init does an AddRef that's balanced by a browser-initiated - // Close IPC. That Close will never happen in this test, so do a Release - // here to ensure |widget_| is properly freed. - widget_->Release(); - DCHECK(widget_->HasOneRef()); } PopupRenderWidget* widget() const { return widget_.get(); } @@ -579,7 +578,9 @@ EXPECT_FALSE(layer_tree_host->is_external_pinch_gesture_active_for_testing()); // Repeat with a 'mainframe' widget. - widget()->set_delegate(std::make_unique<StubRenderWidgetDelegate>()); + std::unique_ptr<StubRenderWidgetDelegate> delegate = + std::make_unique<StubRenderWidgetDelegate>(); + widget()->set_delegate(delegate.get()); visual_properties.is_pinch_gesture_active = true; widget()->OnSynchronizeVisualProperties(visual_properties); // We do not expect the |is_pinch_gesture_active| value to propagate to the @@ -588,6 +589,7 @@ // not a pinch gesture is active, and so we shouldn't propagate this // information to the layer tree for a main-frame's widget. EXPECT_FALSE(layer_tree_host->is_external_pinch_gesture_active_for_testing()); + DestroyWidget(); } TEST_F(RenderWidgetPopupUnittest, EmulatingPopupRect) { @@ -616,10 +618,11 @@ scoped_refptr<PopupRenderWidget> parent_widget( new PopupRenderWidget(&compositor_deps_)); - parent_widget->Release(); // Balance Init(). // Emulation only happens for RenderWidgets with a delegate. - parent_widget->set_delegate(std::make_unique<StubRenderWidgetDelegate>()); + std::unique_ptr<StubRenderWidgetDelegate> delegate = + std::make_unique<StubRenderWidgetDelegate>(); + parent_widget->set_delegate(delegate.get()); // Setup emulation on the |parent_widget|. parent_widget->OnSynchronizeVisualProperties(visual_properties);
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 9587f14..feac8073 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -950,8 +950,8 @@ if (!code_cache_host_) { code_cache_host_ = blink::mojom::ThreadSafeCodeCacheHostPtr::Create( std::move(code_cache_host_info_), - base::CreateSequencedTaskRunnerWithTraits( - {base::WithBaseSyncPrimitives()})); + base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::WithBaseSyncPrimitives()})); } return **code_cache_host_; }
diff --git a/content/renderer/service_worker/service_worker_provider_context.cc b/content/renderer/service_worker/service_worker_provider_context.cc index a069ec6..2546411b 100644 --- a/content/renderer/service_worker/service_worker_provider_context.cc +++ b/content/renderer/service_worker/service_worker_provider_context.cc
@@ -117,8 +117,9 @@ // Create a SubresourceLoaderFactory on a background thread to avoid // extra contention on the main thread. - auto task_runner = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); + auto task_runner = base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask( FROM_HERE, base::BindOnce(&CreateSubresourceLoaderFactoryForProviderContext,
diff --git a/content/renderer/stream_texture_host_android.cc b/content/renderer/stream_texture_host_android.cc index b4f28bc..d0b4ab1d 100644 --- a/content/renderer/stream_texture_host_android.cc +++ b/content/renderer/stream_texture_host_android.cc
@@ -85,6 +85,9 @@ } gpu::SyncToken StreamTextureHost::GenUnverifiedSyncToken() { + // TODO(vikassoni): Remove CHECK after debugging. + CHECK(channel_); + return gpu::SyncToken(gpu::CommandBufferNamespace::GPU_IO, gpu::CommandBufferIdFromChannelAndRoute( channel_->channel_id(), route_id_),
diff --git a/content/shell/browser/shell_download_manager_delegate.cc b/content/shell/browser/shell_download_manager_delegate.cc index a181f0e..9c8ff8bb 100644 --- a/content/shell/browser/shell_download_manager_delegate.cc +++ b/content/shell/browser/shell_download_manager_delegate.cc
@@ -83,15 +83,15 @@ &ShellDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), callback); - PostTaskWithTraits( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&ShellDownloadManagerDelegate::GenerateFilename, - download->GetURL(), download->GetContentDisposition(), - download->GetSuggestedFilename(), download->GetMimeType(), - default_download_path_, - std::move(filename_determined_callback))); + PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&ShellDownloadManagerDelegate::GenerateFilename, + download->GetURL(), download->GetContentDisposition(), + download->GetSuggestedFilename(), + download->GetMimeType(), default_download_path_, + std::move(filename_determined_callback))); return true; } @@ -126,8 +126,8 @@ base::CreateDirectory(suggested_directory); base::FilePath suggested_path(suggested_directory.Append(generated_name)); - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(std::move(callback), suggested_path)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(std::move(callback), suggested_path)); } void ShellDownloadManagerDelegate::OnDownloadPathGenerated(
diff --git a/content/shell/browser/shell_speech_recognition_manager_delegate.cc b/content/shell/browser/shell_speech_recognition_manager_delegate.cc index d38d3c1..0216a3b 100644 --- a/content/shell/browser/shell_speech_recognition_manager_delegate.cc +++ b/content/shell/browser/shell_speech_recognition_manager_delegate.cc
@@ -19,8 +19,8 @@ // Therefore we simply authorize it by calling back with is_allowed=true. The // first parameter, ask_user, is set to false because we don't want to prompt // the user for permission with an infobar. - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, - base::BindOnce(std::move(callback), false, true)); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(std::move(callback), false, true)); } SpeechRecognitionEventListener*
diff --git a/content/shell/browser/shell_views.cc b/content/shell/browser/shell_views.cc index 870c8e71..8933e9ae 100644 --- a/content/shell/browser/shell_views.cc +++ b/content/shell/browser/shell_views.cc
@@ -413,7 +413,7 @@ params.delegate = new ShellWindowDelegateView(this); params.wm_class_class = "chromium-content_shell"; params.wm_class_name = params.wm_class_class; - window_widget_->Init(params); + window_widget_->Init(std::move(params)); #endif content_size_ = gfx::Size(width, height);
diff --git a/content/shell/browser/web_test/web_test_background_fetch_delegate.cc b/content/shell/browser/web_test/web_test_background_fetch_delegate.cc index 1c5ba68..4744f23e 100644 --- a/content/shell/browser/web_test/web_test_background_fetch_delegate.cc +++ b/content/shell/browser/web_test/web_test_background_fetch_delegate.cc
@@ -281,7 +281,7 @@ simple_key, std::move(clients), GetNetworkConnectionTracker(), base::FilePath(), std::make_unique<TestBlobContextGetterFactory>(browser_context_), - base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({BrowserThread::IO}), url_loader_factory); } }
diff --git a/content/shell/browser/web_test/web_test_content_browser_client.cc b/content/shell/browser/web_test/web_test_content_browser_client.cc index 14c8b66a..c604956 100644 --- a/content/shell/browser/web_test/web_test_content_browser_client.cc +++ b/content/shell/browser/web_test/web_test_content_browser_client.cc
@@ -140,8 +140,7 @@ blink::AssociatedInterfaceRegistry* associated_registry, RenderProcessHost* render_process_host) { scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner = - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}); + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}); registry->AddInterface( base::BindRepeating(&WebTestBluetoothFakeAdapterSetterImpl::Create), ui_task_runner);
diff --git a/content/shell/browser/web_test/web_test_message_filter.cc b/content/shell/browser/web_test/web_test_message_filter.cc index 463c3b0..530133c 100644 --- a/content/shell/browser/web_test/web_test_message_filter.cc +++ b/content/shell/browser/web_test/web_test_message_filter.cc
@@ -97,7 +97,7 @@ case WebTestHostMsg_InitiateCaptureDump::ID: case WebTestHostMsg_InspectSecondaryWindow::ID: case WebTestHostMsg_DeleteAllCookies::ID: - return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}); + return base::CreateSingleThreadTaskRunner({BrowserThread::UI}); } return nullptr; }
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 4d4f1c96..57744f3 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -339,7 +339,6 @@ public_deps = [ "//components/download/public/common:test_support", - "//components/variations:test_support", "//content/public/app:both", "//content/public/browser", "//content/public/common",
diff --git a/content/test/content_browser_test_test.cc b/content/test/content_browser_test_test.cc index 109d74d..c87d7bc0 100644 --- a/content/test/content_browser_test_test.cc +++ b/content/test/content_browser_test_test.cc
@@ -80,7 +80,7 @@ base::CommandLine(base::CommandLine::ForCurrentProcess()->GetProgram()); new_test.AppendSwitchASCII(base::kGTestFilterFlag, "ContentBrowserTest.MANUAL_RendererCrash"); - new_test.AppendSwitch(kRunManualTestsFlag); + new_test.AppendSwitch(switches::kRunManualTestsFlag); new_test.AppendSwitch(kSingleProcessTestsFlag); #if defined(THREAD_SANITIZER) @@ -121,7 +121,7 @@ base::CommandLine(base::CommandLine::ForCurrentProcess()->GetProgram()); new_test.AppendSwitchASCII(base::kGTestFilterFlag, "ContentBrowserTest.MANUAL_BrowserCrash"); - new_test.AppendSwitch(kRunManualTestsFlag); + new_test.AppendSwitch(switches::kRunManualTestsFlag); new_test.AppendSwitch(kSingleProcessTestsFlag); std::string output; base::GetAppOutputAndError(new_test, &output);
diff --git a/content/test/content_browser_test_utils_internal.cc b/content/test/content_browser_test_utils_internal.cc index d411eb23..3cdfd2b 100644 --- a/content/test/content_browser_test_utils_internal.cc +++ b/content/test/content_browser_test_utils_internal.cc
@@ -411,19 +411,17 @@ void ShowWidgetMessageFilter::OnShowWidget(int route_id, const gfx::Rect& initial_rect) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this, route_id, - initial_rect)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ShowWidgetMessageFilter::OnShowWidgetOnUI, + this, route_id, initial_rect)); } #if defined(OS_MACOSX) || defined(OS_ANDROID) void ShowWidgetMessageFilter::OnShowPopup( const FrameHostMsg_ShowPopup_Params& params) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&ShowWidgetMessageFilter::OnShowWidgetOnUI, this, - MSG_ROUTING_NONE, params.bounds)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ShowWidgetMessageFilter::OnShowWidgetOnUI, + this, MSG_ROUTING_NONE, params.bounds)); } #endif
diff --git a/content/test/mock_platform_notification_service.cc b/content/test/mock_platform_notification_service.cc index faa8e541..ba59828 100644 --- a/content/test/mock_platform_notification_service.cc +++ b/content/test/mock_platform_notification_service.cc
@@ -89,7 +89,7 @@ for (const auto& notification_id : non_persistent_notifications_) displayed_notifications.insert(notification_id); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, base::BindOnce(std::move(callback), std::move(displayed_notifications), true /* supports_synchronization */));
diff --git a/content/test/renderer_audio_output_stream_factory_context_impl_unittest.cc b/content/test/renderer_audio_output_stream_factory_context_impl_unittest.cc index 31596b7..a0a6828 100644 --- a/content/test/renderer_audio_output_stream_factory_context_impl_unittest.cc +++ b/content/test/renderer_audio_output_stream_factory_context_impl_unittest.cc
@@ -81,7 +81,7 @@ // least one task will be run. 20 iterations should be enough for our code. for (int i = 0; i < 20; ++i) { base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle(); - SyncWith(base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); + SyncWith(base::CreateSingleThreadTaskRunner({BrowserThread::IO})); SyncWith(media::AudioManager::Get()->GetWorkerTaskRunner()); } }
diff --git a/content/test/storage_partition_test_utils.cc b/content/test/storage_partition_test_utils.cc index 1f613d54..740e027 100644 --- a/content/test/storage_partition_test_utils.cc +++ b/content/test/storage_partition_test_utils.cc
@@ -24,7 +24,7 @@ scoped_refptr<network::SharedURLLoaderFactory>* out_shared_factory) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {BrowserThread::IO}, base::BindOnce( [](SharedURLLoaderFactoryGetterCallback getter, @@ -46,7 +46,7 @@ [](network::SimpleURLLoader::BodyAsStringCallback callback, std::unique_ptr<std::string> response_body) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(std::move(callback), std::move(response_body))); }, @@ -106,19 +106,18 @@ network::SimpleURLLoader::Create(std::move(request), TRAFFIC_ANNOTATION_FOR_TESTS); - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce( - [](network::SimpleURLLoader* loader, - network::mojom::URLLoaderFactory* factory, - network::SimpleURLLoader::BodyAsStringCallback - body_as_string_callback) { - loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( - factory, std::move(body_as_string_callback)); - }, - base::Unretained(simple_loader.get()), - base::Unretained(shared_url_loader_factory_.get()), - RunOnUIThread(simple_loader_helper.GetCallback()))); + base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce( + [](network::SimpleURLLoader* loader, + network::mojom::URLLoaderFactory* factory, + network::SimpleURLLoader::BodyAsStringCallback + body_as_string_callback) { + loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + factory, std::move(body_as_string_callback)); + }, + base::Unretained(simple_loader.get()), + base::Unretained(shared_url_loader_factory_.get()), + RunOnUIThread(simple_loader_helper.GetCallback()))); simple_loader_helper.WaitForCallback(); return simple_loader->NetError();
diff --git a/device/fido/fido_constants.h b/device/fido/fido_constants.h index ee25ae5..6899a96 100644 --- a/device/fido/fido_constants.h +++ b/device/fido/fido_constants.h
@@ -69,6 +69,10 @@ // https://www.w3.org/TR/webauthn/#sec-authenticator-data constexpr size_t kRpIdHashLength = 32; +// Max length for the user handle: +// https://www.w3.org/TR/webauthn/#user-handle +constexpr size_t kUserHandleMaxLength = 64; + static_assert(kU2fApplicationParamLength == kRpIdHashLength, "kU2fApplicationParamLength must be equal to kRpIdHashLength.");
diff --git a/device/fido/virtual_fido_device.cc b/device/fido/virtual_fido_device.cc index 777140d5..874b6a4 100644 --- a/device/fido/virtual_fido_device.cc +++ b/device/fido/virtual_fido_device.cc
@@ -83,7 +83,9 @@ bool VirtualFidoDevice::State::InjectResidentKey( base::span<const uint8_t> credential_id, device::PublicKeyCredentialRpEntity rp, - device::PublicKeyCredentialUserEntity user) { + device::PublicKeyCredentialUserEntity user, + int32_t signature_counter, + std::unique_ptr<crypto::ECPrivateKey> private_key) { auto application_parameter = fido_parsing_utils::CreateSHA256Hash(rp.id); // Cannot create a duplicate credential for the same (RP ID, user ID) pair. @@ -95,12 +97,9 @@ } } - auto private_key = crypto::ECPrivateKey::Create(); - DCHECK(private_key); - RegistrationData registration(std::move(private_key), std::move(application_parameter), - 0 /* signature counter */); + signature_counter); registration.is_resident = true; registration.rp = std::move(rp); registration.user = std::move(user); @@ -113,6 +112,17 @@ bool VirtualFidoDevice::State::InjectResidentKey( base::span<const uint8_t> credential_id, + device::PublicKeyCredentialRpEntity rp, + device::PublicKeyCredentialUserEntity user) { + auto private_key = crypto::ECPrivateKey::Create(); + DCHECK(private_key); + return InjectResidentKey(std::move(credential_id), std::move(rp), + std::move(user), /*signature_counter=*/0, + std::move(private_key)); +} + +bool VirtualFidoDevice::State::InjectResidentKey( + base::span<const uint8_t> credential_id, const std::string& relying_party_id, base::span<const uint8_t> user_id, const std::string& user_name,
diff --git a/device/fido/virtual_fido_device.h b/device/fido/virtual_fido_device.h index 9660be1..ef94bba 100644 --- a/device/fido/virtual_fido_device.h +++ b/device/fido/virtual_fido_device.h
@@ -157,7 +157,18 @@ bool InjectRegistration(base::span<const uint8_t> credential_id, const std::string& relying_party_id); - // InjectResidentKey adds a resident credential with the specified values. + // Adds a resident credential with the specified values. + // Returns false if there already exists a resident credential for the same + // (RP ID, user ID) pair, or for the same credential ID. Otherwise returns + // true. + bool InjectResidentKey(base::span<const uint8_t> credential_id, + device::PublicKeyCredentialRpEntity rp, + device::PublicKeyCredentialUserEntity user, + int32_t signature_counter, + std::unique_ptr<crypto::ECPrivateKey> private_key); + + // Adds a resident credential with the specified values, creating a new + // private key. // Returns false if there already exists a resident credential for the same // (RP ID, user ID) pair, or for the same credential ID. Otherwise returns // true.
diff --git a/device/gamepad/gamepad_pad_state_provider.h b/device/gamepad/gamepad_pad_state_provider.h index 3ac6476f..621072cb 100644 --- a/device/gamepad/gamepad_pad_state_provider.h +++ b/device/gamepad/gamepad_pad_state_provider.h
@@ -37,7 +37,8 @@ GAMEPAD_SOURCE_WIN_XINPUT, GAMEPAD_SOURCE_WIN_RAW, GAMEPAD_SOURCE_WIN_MR, - kMaxValue = GAMEPAD_SOURCE_WIN_MR, + GAMEPAD_SOURCE_OPENXR, + kMaxValue = GAMEPAD_SOURCE_OPENXR, }; struct PadState {
diff --git a/device/vr/BUILD.gn b/device/vr/BUILD.gn index 3c55705..946f6bf 100644 --- a/device/vr/BUILD.gn +++ b/device/vr/BUILD.gn
@@ -231,8 +231,12 @@ sources += [ "openxr/openxr_api_wrapper.cc", "openxr/openxr_api_wrapper.h", + "openxr/openxr_controller.cc", + "openxr/openxr_controller.h", "openxr/openxr_device.cc", "openxr/openxr_device.h", + "openxr/openxr_gamepad_helper.cc", + "openxr/openxr_gamepad_helper.h", "openxr/openxr_render_loop.cc", "openxr/openxr_render_loop.h", "openxr/openxr_util.cc",
diff --git a/device/vr/OWNERS b/device/vr/OWNERS index f53264a..c31ef2534 100644 --- a/device/vr/OWNERS +++ b/device/vr/OWNERS
@@ -1,7 +1,6 @@ alcooper@chromium.org bajones@chromium.org bialpio@chromium.org -billorr@chromium.org per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/device/vr/isolated_gamepad_data_fetcher.cc b/device/vr/isolated_gamepad_data_fetcher.cc index 89197e3..bd27e429 100644 --- a/device/vr/isolated_gamepad_data_fetcher.cc +++ b/device/vr/isolated_gamepad_data_fetcher.cc
@@ -30,6 +30,11 @@ return true; #endif +#if BUILDFLAG(ENABLE_OPENXR) + if (id == device::mojom::XRDeviceId::OPENXR_DEVICE_ID) + return true; +#endif + return false; } @@ -51,6 +56,11 @@ return GAMEPAD_SOURCE_WIN_MR; #endif +#if BUILDFLAG(ENABLE_OPENXR) + if (id == device::mojom::XRDeviceId::OPENXR_DEVICE_ID) + return GAMEPAD_SOURCE_OPENXR; +#endif + NOTREACHED(); return GAMEPAD_SOURCE_NONE; } @@ -217,7 +227,9 @@ // per runtime, we use the XRDeviceId now to associate the controller with // a headset. This doesn't change behavior, but the device/display naming // could be confusing here. - if (this->source() == GAMEPAD_SOURCE_OPENVR) { + if (this->source() == GAMEPAD_SOURCE_OPENXR) { + dest.SetID(base::UTF8ToUTF16("OpenXR Controller")); + } else if (this->source() == GAMEPAD_SOURCE_OPENVR) { dest.SetID(base::UTF8ToUTF16("OpenVR Gamepad")); } else if (this->source() == GAMEPAD_SOURCE_OCULUS) { if (dest.hand == GamepadHand::kLeft) {
diff --git a/device/vr/openxr/openxr_api_wrapper.cc b/device/vr/openxr/openxr_api_wrapper.cc index aa36d37..1680c0b 100644 --- a/device/vr/openxr/openxr_api_wrapper.cc +++ b/device/vr/openxr/openxr_api_wrapper.cc
@@ -10,6 +10,7 @@ #include <array> #include "base/logging.h" +#include "device/vr/openxr/openxr_gamepad_helper.h" #include "device/vr/openxr/openxr_util.h" #include "ui/gfx/geometry/point3_f.h" #include "ui/gfx/geometry/quaternion.h" @@ -137,7 +138,7 @@ } void OpenXrApiWrapper::Uninitialize() { - // Destroying an instance in OpenXR also destroys all child objects of that + // Destroying an instance in OpenXr also destroys all child objects of that // instance (including the session, swapchain, and spaces objects), // so they don't need to be manually destroyed. if (HasInstance()) { @@ -198,7 +199,7 @@ RETURN_IF_XR_FAILED(xrEnumerateViewConfigurationViews( instance_, system, kSupportedViewConfiguration, 0, &view_count, nullptr)); - // It would be an error for an OpenXR runtime to return anything other than 2 + // It would be an error for an OpenXr runtime to return anything other than 2 // views to an app that only requested // XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO. DCHECK(view_count == kNumViews); @@ -251,7 +252,8 @@ // this OpenXrApiWrapper object on failure to clean up any intermediate // objects that may have been created before the failure. XrResult OpenXrApiWrapper::StartSession( - const Microsoft::WRL::ComPtr<ID3D11Device>& d3d_device) { + const Microsoft::WRL::ComPtr<ID3D11Device>& d3d_device, + std::unique_ptr<OpenXrGamepadHelper>* gamepad_helper) { DCHECK(d3d_device.Get()); DCHECK(IsInitialized()); @@ -262,6 +264,7 @@ RETURN_IF_XR_FAILED( CreateSpace(XR_REFERENCE_SPACE_TYPE_LOCAL, &local_space_)); RETURN_IF_XR_FAILED(CreateSpace(XR_REFERENCE_SPACE_TYPE_VIEW, &view_space_)); + RETURN_IF_XR_FAILED(CreateGamepadHelper(gamepad_helper)); RETURN_IF_XR_FAILED(BeginSession()); // Since the objects in these arrays are used on every frame, @@ -275,6 +278,7 @@ DCHECK(HasColorSwapChain()); DCHECK(HasSpace(XR_REFERENCE_SPACE_TYPE_LOCAL)); DCHECK(HasSpace(XR_REFERENCE_SPACE_TYPE_VIEW)); + DCHECK(gamepad_helper); return xr_result; } @@ -355,6 +359,17 @@ return xrCreateReferenceSpace(session_, &space_create_info, space); } +XrResult OpenXrApiWrapper::CreateGamepadHelper( + std::unique_ptr<OpenXrGamepadHelper>* gamepad_helper) { + DCHECK(HasSession()); + DCHECK(HasSpace(XR_REFERENCE_SPACE_TYPE_LOCAL)); + + XrResult xr_result = OpenXrGamepadHelper::GetOpenXrGamepadHelper( + instance_, session_, local_space_, gamepad_helper); + + return xr_result; +} + XrResult OpenXrApiWrapper::BeginSession() { DCHECK(HasSession());
diff --git a/device/vr/openxr/openxr_api_wrapper.h b/device/vr/openxr/openxr_api_wrapper.h index bd2430a..dcb97426 100644 --- a/device/vr/openxr/openxr_api_wrapper.h +++ b/device/vr/openxr/openxr_api_wrapper.h
@@ -22,6 +22,8 @@ namespace device { +class OpenXrGamepadHelper; + class OpenXrApiWrapper { public: OpenXrApiWrapper(); @@ -32,7 +34,8 @@ static bool IsHardwareAvailable(); static bool IsApiAvailable(); - XrResult StartSession(const Microsoft::WRL::ComPtr<ID3D11Device>& d3d_device); + XrResult StartSession(const Microsoft::WRL::ComPtr<ID3D11Device>& d3d_device, + std::unique_ptr<OpenXrGamepadHelper>* gamepad_helper); XrResult BeginFrame(Microsoft::WRL::ComPtr<ID3D11Texture2D>* texture); XrResult EndFrame(); @@ -59,6 +62,8 @@ XrResult CreateSwapchain(); XrResult CreateSpace(XrReferenceSpaceType type, XrSpace* space); XrResult CreateViewSpace(); + XrResult CreateGamepadHelper( + std::unique_ptr<OpenXrGamepadHelper>* gamepad_helper); XrResult BeginSession(); XrResult UpdateProjectionLayers(); @@ -73,7 +78,7 @@ uint32_t GetRecommendedSwapchainSampleCount() const; - // OpenXR objects + // OpenXr objects // These objects are valid on successful initialization. XrInstance instance_;
diff --git a/device/vr/openxr/openxr_controller.cc b/device/vr/openxr/openxr_controller.cc new file mode 100644 index 0000000..12c2e17 --- /dev/null +++ b/device/vr/openxr/openxr_controller.cc
@@ -0,0 +1,325 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "device/vr/openxr/openxr_controller.h" + +#include <stdint.h> + +#include "base/logging.h" +#include "device/vr/openxr/openxr_util.h" +#include "device/vr/public/mojom/vr_service.mojom.h" + +namespace device { + +namespace { + +constexpr char kMicrosoftInteractionProfileName[] = + "/interaction_profiles/microsoft/motion_controller"; + +const char* GetStringFromType(OpenXrControllerType type) { + switch (type) { + case OpenXrControllerType::kLeft: + return "left"; + case OpenXrControllerType::kRight: + return "right"; + default: + NOTREACHED(); + return ""; + } +} + +} // namespace + +OpenXrController::OpenXrController() + : type_(OpenXrControllerType::kCount), // COUNT refers to invalid. + action_set_(XR_NULL_HANDLE), + palm_pose_action_{XR_NULL_HANDLE}, + palm_pose_space_(XR_NULL_HANDLE) {} + +OpenXrController::~OpenXrController() { + // We don't need to destroy all of the actions because destroying an + // action set destroys all actions that are part of the set. + + if (action_set_ != XR_NULL_HANDLE) { + xrDestroyActionSet(action_set_); + } + if (palm_pose_space_ != XR_NULL_HANDLE) { + xrDestroySpace(palm_pose_space_); + } +} + +XrResult OpenXrController::Initialize( + OpenXrControllerType type, + XrInstance instance, + XrSession session, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings) { + type_ = type; + std::string type_string = GetStringFromType(type_); + + std::string action_set_name = type_string + "_action_set"; + XrActionSetCreateInfo action_set_create_info = { + XR_TYPE_ACTION_SET_CREATE_INFO}; + + errno_t error = + strcpy_s(action_set_create_info.actionSetName, action_set_name.c_str()); + DCHECK(!error); + error = strcpy_s(action_set_create_info.localizedActionSetName, + action_set_name.c_str()); + DCHECK(!error); + + XrResult xr_result; + + RETURN_IF_XR_FAILED( + xrCreateActionSet(session, &action_set_create_info, &action_set_)); + + RETURN_IF_XR_FAILED(InitializeMicrosoftMotionControllers( + instance, session, type_string, bindings)); + + XrActionSpaceCreateInfo action_space_create_info = { + XR_TYPE_ACTION_SPACE_CREATE_INFO}; + action_space_create_info.poseInActionSpace = PoseIdentity(); + RETURN_IF_XR_FAILED(xrCreateActionSpace( + palm_pose_action_, &action_space_create_info, &palm_pose_space_)); + return xr_result; +} + +XrResult OpenXrController::InitializeMicrosoftMotionControllers( + XrInstance instance, + XrSession session, + const std::string& type_string, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings) { + XrResult xr_result; + + const std::string binding_prefix = "/user/hand/" + type_string + "/input/"; + const std::string name_prefix = type_string + "_controller_"; + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_BOOLEAN, kMicrosoftInteractionProfileName, + binding_prefix + "trackpad/click", name_prefix + "trackpad_button_press", + &(button_action_map_[OpenXrButtonType::kTrackpad].press_action), + bindings)); + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_BOOLEAN, kMicrosoftInteractionProfileName, + binding_prefix + "trigger/value", name_prefix + "trigger_button_press", + &(button_action_map_[OpenXrButtonType::kTrigger].press_action), + bindings)); + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_BOOLEAN, kMicrosoftInteractionProfileName, + binding_prefix + "grip/click", name_prefix + "grip_button_press", + &(button_action_map_[OpenXrButtonType::kGrip].press_action), bindings)); + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_BOOLEAN, kMicrosoftInteractionProfileName, + binding_prefix + "menu/click", name_prefix + "menu_button_press", + &(button_action_map_[OpenXrButtonType::kMenu].press_action), bindings)); + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_VECTOR2F, kMicrosoftInteractionProfileName, + binding_prefix + "trackpad", name_prefix + "trackpad_axis", + &(axis_action_map_[OpenXrAxisType::kTrackpad]), bindings)); + + RETURN_IF_XR_FAILED(CreateAction( + instance, XR_INPUT_ACTION_TYPE_VECTOR2F, kMicrosoftInteractionProfileName, + binding_prefix + "thumbstick", name_prefix + "thumbstick_axis", + &(axis_action_map_[OpenXrAxisType::kThumbstick]), bindings)); + + RETURN_IF_XR_FAILED( + CreateAction(instance, XR_INPUT_ACTION_TYPE_POSE, + kMicrosoftInteractionProfileName, binding_prefix + "palm", + name_prefix + "grip_pose", &palm_pose_action_, bindings)); + + return xr_result; +} + +int OpenXrController::GetID() { + return static_cast<int>(type_); +} + +device::mojom::XRHandedness OpenXrController::GetHandness() { + switch (type_) { + case OpenXrControllerType::kLeft: + return device::mojom::XRHandedness::LEFT; + case OpenXrControllerType::kRight: + return device::mojom::XRHandedness::RIGHT; + default: + // LEFT controller and RIGHT controller are currently the only supported + // controllers. In the future, other controllers such as sound (which + // does not have a handedness) will be added here. + NOTREACHED(); + return device::mojom::XRHandedness::NONE; + } +} + +XrResult OpenXrController::GetButton(OpenXrButtonType type, + mojom::XRGamepadButtonPtr* data) { + XrResult xr_result; + XrActionStateBoolean press_state_bool = {XR_TYPE_ACTION_STATE_BOOLEAN}; + RETURN_IF_XR_FAILED( + QueryState(button_action_map_[type].press_action, &press_state_bool)); + RETURN_IF_XR_STATE_IS_NOT_ACTIVE(press_state_bool); + mojom::XRGamepadButtonPtr mojo_button_ptr = + GetGamepadButton(press_state_bool); + *data = std::move(mojo_button_ptr); + return xr_result; +} + +XrResult OpenXrController::GetWebVrButtons( + std::vector<mojom::XRGamepadButtonPtr>* buttons) { + DCHECK(buttons); + XrResult xr_result; + + for (uint32_t i = 0; i <= static_cast<uint32_t>(OpenXrButtonType::kMaxValue); + i++) { + mojom::XRGamepadButtonPtr mojo_button_ptr; + RETURN_IF_XR_FAILED( + GetButton(static_cast<OpenXrButtonType>(i), &mojo_button_ptr)); + if (xr_result == XR_STATE_UNAVAILABLE) { + return xr_result; + } + buttons->push_back(std::move(mojo_button_ptr)); + } + + return xr_result; +} + +XrResult OpenXrController::GetAxes(OpenXrAxisType type, + std::array<double, 2>* axes) { + DCHECK(axes); + XrResult xr_result; + + XrActionStateVector2f axis_state_v2f = {XR_TYPE_ACTION_STATE_VECTOR2F}; + RETURN_IF_XR_FAILED(QueryState(axis_action_map_[type], &axis_state_v2f)); + RETURN_IF_XR_STATE_IS_NOT_ACTIVE(axis_state_v2f); + (*axes)[0] = axis_state_v2f.currentState.x; + (*axes)[1] = axis_state_v2f.currentState.y; + + return xr_result; +} + +XrResult OpenXrController::GetAllWebVrAxes(std::vector<double>* axes) { + DCHECK(axes); + XrResult xr_result; + + for (uint32_t i = 0; i <= static_cast<uint32_t>(OpenXrAxisType::kMaxValue); + i++) { + std::array<double, 2> axe; + RETURN_IF_XR_FAILED(GetAxes(static_cast<OpenXrAxisType>(i), &axe)); + if (xr_result == XR_STATE_UNAVAILABLE) { + return xr_result; + } + axes->insert(axes->end(), axe.begin(), axe.end()); + } + return xr_result; +} + +XrResult OpenXrController::GetPose(XrTime predicted_display_time, + XrSpace local_space, + mojom::XRGamepad* gamepad_ptr) { + XrResult xr_result; + + XrActionStatePose palm_state_pose = {XR_TYPE_ACTION_STATE_POSE}; + RETURN_IF_XR_FAILED(QueryState(palm_pose_action_, &palm_state_pose)); + RETURN_IF_XR_STATE_IS_NOT_ACTIVE(palm_state_pose); + + XrSpaceRelation space_relation = {XR_TYPE_SPACE_RELATION}; + RETURN_IF_XR_FAILED(xrLocateSpace(palm_pose_space_, local_space, + predicted_display_time, &space_relation)); + + gamepad_ptr->pose = mojom::VRPose::New(); + + if (space_relation.relationFlags & XR_SPACE_RELATION_POSITION_VALID_BIT) { + gamepad_ptr->can_provide_position = true; + gamepad_ptr->pose->position = gfx::Point3F(space_relation.pose.position.x, + space_relation.pose.position.y, + space_relation.pose.position.z); + } + + if (space_relation.relationFlags & XR_SPACE_RELATION_ORIENTATION_VALID_BIT) { + gamepad_ptr->can_provide_orientation = true; + gamepad_ptr->pose->orientation = gfx::Quaternion( + space_relation.pose.orientation.x, space_relation.pose.orientation.y, + space_relation.pose.orientation.z, space_relation.pose.orientation.w); + } + + if (space_relation.relationFlags & + XR_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT) { + gamepad_ptr->pose->linear_velocity = gfx::Vector3dF( + space_relation.linearVelocity.x, space_relation.linearVelocity.y, + space_relation.linearVelocity.z); + } + + if (space_relation.relationFlags & + XR_SPACE_RELATION_LINEAR_ACCELERATION_VALID_BIT) { + gamepad_ptr->pose->linear_acceleration = + gfx::Vector3dF(space_relation.linearAcceleration.x, + space_relation.linearAcceleration.y, + space_relation.linearAcceleration.z); + } + + if (space_relation.relationFlags & + XR_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT) { + gamepad_ptr->pose->angular_velocity = gfx::Vector3dF( + space_relation.angularVelocity.x, space_relation.angularVelocity.y, + space_relation.angularVelocity.z); + } + + if (space_relation.relationFlags & + XR_SPACE_RELATION_ANGULAR_ACCELERATION_VALID_BIT) { + gamepad_ptr->pose->angular_acceleration = + gfx::Vector3dF(space_relation.angularAcceleration.x, + space_relation.angularAcceleration.y, + space_relation.angularAcceleration.z); + } + + return xr_result; +} + +mojom::XRGamepadButtonPtr OpenXrController::GetGamepadButton( + const XrActionStateBoolean& action_state) { + mojom::XRGamepadButtonPtr ret = mojom::XRGamepadButton::New(); + bool button_pressed = action_state.currentState; + ret->touched = button_pressed; + ret->pressed = button_pressed; + ret->value = button_pressed ? 1.0 : 0.0; + + return ret; +} + +XrActionSet OpenXrController::GetActionSet() const { + return action_set_; +} + +XrResult OpenXrController::CreateAction( + XrInstance instance, + XrActionType type, + const char* interaction_profile_name, + const std::string& binding_string, + const std::string& action_name, + XrAction* action, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings) { + XrResult xr_result; + + XrActionCreateInfo action_create_info = {XR_TYPE_ACTION_CREATE_INFO}; + action_create_info.actionType = type; + + errno_t error = strcpy_s(action_create_info.actionName, action_name.data()); + DCHECK(error == 0); + error = strcpy_s(action_create_info.localizedActionName, action_name.data()); + DCHECK(error == 0); + + RETURN_IF_XR_FAILED(xrCreateAction(action_set_, &action_create_info, action)); + + XrPath profile_path, action_path; + RETURN_IF_XR_FAILED( + xrStringToPath(instance, interaction_profile_name, &profile_path)); + RETURN_IF_XR_FAILED( + xrStringToPath(instance, binding_string.c_str(), &action_path)); + (*bindings)[profile_path].push_back({*action, action_path}); + + return xr_result; +} + +} // namespace device
diff --git a/device/vr/openxr/openxr_controller.h b/device/vr/openxr/openxr_controller.h new file mode 100644 index 0000000..2add68d --- /dev/null +++ b/device/vr/openxr/openxr_controller.h
@@ -0,0 +1,145 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEVICE_VR_OPENXR_OPENXR_CONTROLLER_H_ +#define DEVICE_VR_OPENXR_OPENXR_CONTROLLER_H_ + +#include <stdint.h> +#include <unordered_map> + +#include "device/vr/public/mojom/isolated_xr_service.mojom.h" +#include "device/vr/util/gamepad_builder.h" +#include "third_party/openxr/include/openxr/openxr.h" + +namespace device { + +enum class OpenXrControllerType { + kLeft = 0, + kRight = 1, + kCount = 2, +}; + +enum class OpenXrButtonType { + kTrackpad = 0, + kTrigger = 1, + kGrip = 2, + kMenu = 3, + kMaxValue = 3, +}; + +enum class OpenXrAxisType { + kTrackpad = 0, + kThumbstick = 1, + kMaxValue = 1, +}; + +class OpenXrController { + public: + OpenXrController(); + ~OpenXrController(); + + XrActionSet GetActionSet() const; + + XrResult Initialize( + OpenXrControllerType type, + XrInstance instance, + XrSession session, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings); + + int GetID(); + + device::mojom::XRHandedness GetHandness(); + + XrResult GetButton(OpenXrButtonType type, mojom::XRGamepadButtonPtr* data); + + XrResult GetWebVrButtons(std::vector<mojom::XRGamepadButtonPtr>* buttons); + + XrResult GetAxes(OpenXrAxisType type, std::array<double, 2>* axes); + + XrResult GetAllWebVrAxes(std::vector<double>* axes); + + XrResult GetPose(XrTime predicted_display_time, + XrSpace local_space, + mojom::XRGamepad* gamepad_ptr); + + private: + // ActionButton struct is used to store all XrAction that is related to the + // button. For example, we may need to query the analog value for button press + // which require a seperate XrAction than the current boolean XrAction. + struct ActionButton { + XrAction press_action; + ActionButton() : press_action(XR_NULL_HANDLE) {} + }; + + XrResult InitializeMicrosoftMotionControllers( + XrInstance instance, + XrSession session, + const std::string& type_string, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings); + + XrResult CreateAction( + XrInstance instance, + XrActionType type, + const char* interaction_profile_name, + const std::string& binding_string, + const std::string& action_name, + XrAction* action, + std::map<XrPath, std::vector<XrActionSuggestedBinding>>* bindings); + + template <typename T> + XrResult QueryState(XrAction action, T* action_state) { + // this function should never be called because each valid XrActionState + // has its own template function defined below. + NOTREACHED(); + return XR_ERROR_ACTION_TYPE_MISMATCH; + } + + template <> + XrResult QueryState<XrActionStateBoolean>( + XrAction action, + XrActionStateBoolean* action_state) { + action_state->type = XR_TYPE_ACTION_STATE_BOOLEAN; + return xrGetActionStateBoolean(action, 0, nullptr, action_state); + } + + template <> + XrResult QueryState<XrActionStateVector1f>( + XrAction action, + XrActionStateVector1f* action_state) { + action_state->type = XR_TYPE_ACTION_STATE_VECTOR1F; + return xrGetActionStateVector1f(action, 0, nullptr, action_state); + } + + template <> + XrResult QueryState<XrActionStateVector2f>( + XrAction action, + XrActionStateVector2f* action_state) { + action_state->type = XR_TYPE_ACTION_STATE_VECTOR2F; + return xrGetActionStateVector2f(action, 0, nullptr, action_state); + } + + template <> + XrResult QueryState<XrActionStatePose>(XrAction action, + XrActionStatePose* action_state) { + action_state->type = XR_TYPE_ACTION_STATE_POSE; + return xrGetActionStatePose(action, XR_NULL_PATH, action_state); + } + + mojom::XRGamepadButtonPtr GetGamepadButton( + const XrActionStateBoolean& action_state); + + OpenXrControllerType type_; + XrActionSet action_set_; + XrAction palm_pose_action_; + XrSpace palm_pose_space_; + + std::unordered_map<OpenXrButtonType, ActionButton> button_action_map_; + std::unordered_map<OpenXrAxisType, XrAction> axis_action_map_; + + DISALLOW_COPY_AND_ASSIGN(OpenXrController); +}; + +} // namespace device + +#endif // DEVICE_VR_OPENXR_OPENXR_CONTROLLER_H_
diff --git a/device/vr/openxr/openxr_device.cc b/device/vr/openxr/openxr_device.cc index 33b87b9..85aa411 100644 --- a/device/vr/openxr/openxr_device.cc +++ b/device/vr/openxr/openxr_device.cc
@@ -127,7 +127,7 @@ base::BindOnce(&OpenXrDevice::OnRequestSessionResult, weak_ptr_factory_.GetWeakPtr(), std::move(callback)); - // OpenXR doesn't need to handle anything when presentation has ended, but + // OpenXr doesn't need to handle anything when presentation has ended, but // the mojo interface to call to XRCompositorCommon::RequestSession requires // a method and cannot take nullptr, so passing in base::DoNothing::Once() // for on_presentation_ended
diff --git a/device/vr/openxr/openxr_gamepad_helper.cc b/device/vr/openxr/openxr_gamepad_helper.cc new file mode 100644 index 0000000..14845cb6 --- /dev/null +++ b/device/vr/openxr/openxr_gamepad_helper.cc
@@ -0,0 +1,97 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "device/vr/openxr/openxr_gamepad_helper.h" + +#include "device/vr/openxr/openxr_util.h" + +namespace device { + +XrResult OpenXrGamepadHelper::GetOpenXrGamepadHelper( + XrInstance instance, + XrSession session, + XrSpace local_space, + std::unique_ptr<OpenXrGamepadHelper>* helper) { + XrResult xr_result; + // This map is used to store bindings for different kinds of interaction + // profiles. This allows the runtime to choose a different input sources based + // on availability. + std::map<XrPath, std::vector<XrActionSuggestedBinding>> bindings; + std::unique_ptr<OpenXrGamepadHelper> new_helper = + std::make_unique<OpenXrGamepadHelper>(session, local_space); + for (size_t i = 0; i < new_helper->controllers_.size(); i++) { + xr_result = new_helper->controllers_[i].Initialize( + static_cast<OpenXrControllerType>(i), instance, session, &bindings); + RETURN_IF_XR_FAILED(xr_result); + } + + for (auto it = bindings.begin(); it != bindings.end(); it++) { + XrInteractionProfileSuggestedBinding profile_suggested_bindings = { + XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING}; + profile_suggested_bindings.interactionProfile = it->first; + profile_suggested_bindings.suggestedBindings = it->second.data(); + profile_suggested_bindings.countSuggestedBindings = it->second.size(); + + xr_result = xrSetInteractionProfileSuggestedBindings( + session, &profile_suggested_bindings); + } + + RETURN_IF_XR_FAILED(xr_result); + + *helper = std::move(new_helper); + return xr_result; +} + +OpenXrGamepadHelper::OpenXrGamepadHelper(XrSession session, XrSpace local_space) + : session_(session), local_space_(local_space) {} + +OpenXrGamepadHelper::~OpenXrGamepadHelper() = default; + +mojom::XRGamepadDataPtr OpenXrGamepadHelper::GetGamepadData( + XrTime predicted_display_time) { + XrResult xr_result; + + std::array<XrActiveActionSet, 2> active_action_set_arr; + for (size_t i = 0; i < controllers_.size(); i++) { + active_action_set_arr[i] = {XR_TYPE_ACTIVE_ACTION_SET}; + active_action_set_arr[i].actionSet = controllers_[i].GetActionSet(); + active_action_set_arr[i].subactionPath = XR_NULL_PATH; + } + xr_result = xrSyncActionData(session_, controllers_.size(), + active_action_set_arr.data()); + if (XR_FAILED(xr_result)) + return nullptr; + + mojom::XRGamepadDataPtr gamepad_data_ptr = mojom::XRGamepadData::New(); + for (OpenXrController& controller : controllers_) { + mojom::XRGamepadPtr gamepad_ptr = mojom::XRGamepad::New(); + gamepad_ptr->controller_id = controller.GetID(); + gamepad_ptr->timestamp = base::TimeTicks::Now(); + gamepad_ptr->hand = controller.GetHandness(); + + // GetButtons, GetAxes and GetPose may return success codes >= 0, including + // XR_SUCCESS and XR_STATE_UNAVAILABLE. We should continue to populate the + // data only on XR_SUCCESS and ignore other success codes. + if (!XR_UNQUALIFIED_SUCCESS( + controller.GetWebVrButtons(&(gamepad_ptr->buttons)))) { + continue; + } + if (!XR_UNQUALIFIED_SUCCESS( + controller.GetAllWebVrAxes(&(gamepad_ptr->axes)))) { + continue; + } + if (!XR_UNQUALIFIED_SUCCESS(controller.GetPose( + predicted_display_time, local_space_, gamepad_ptr.get()))) { + continue; + } + + if (XR_UNQUALIFIED_SUCCESS(xr_result)) { + gamepad_data_ptr->gamepads.push_back(std::move(gamepad_ptr)); + } + } + + return gamepad_data_ptr; +} + +} // namespace device
diff --git a/device/vr/openxr/openxr_gamepad_helper.h b/device/vr/openxr/openxr_gamepad_helper.h new file mode 100644 index 0000000..dfcbce6 --- /dev/null +++ b/device/vr/openxr/openxr_gamepad_helper.h
@@ -0,0 +1,39 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEVICE_VR_OPENXR_OPENXR_GAMEPAD_HELPER_H_ +#define DEVICE_VR_OPENXR_OPENXR_GAMEPAD_HELPER_H_ + +#include "device/vr/openxr/openxr_controller.h" +#include "device/vr/public/mojom/isolated_xr_service.mojom.h" + +namespace device { + +class OpenXrGamepadHelper { + public: + static XrResult GetOpenXrGamepadHelper( + XrInstance instance, + XrSession session, + XrSpace local_space, + std::unique_ptr<OpenXrGamepadHelper>* helper); + + OpenXrGamepadHelper(XrSession session, XrSpace local_space); + + ~OpenXrGamepadHelper(); + + mojom::XRGamepadDataPtr GetGamepadData(XrTime predicted_display_time); + + private: + XrSession session_; + XrSpace local_space_; + + std::array<OpenXrController, static_cast<int>(OpenXrControllerType::kCount)> + controllers_; + + DISALLOW_COPY_AND_ASSIGN(OpenXrGamepadHelper); +}; + +} // namespace device + +#endif // DEVICE_VR_OPENXR_OPENXR_GAMEPAD_HELPER_H_
diff --git a/device/vr/openxr/openxr_render_loop.cc b/device/vr/openxr/openxr_render_loop.cc index af033cb..1c656b1 100644 --- a/device/vr/openxr/openxr_render_loop.cc +++ b/device/vr/openxr/openxr_render_loop.cc
@@ -5,6 +5,7 @@ #include "device/vr/openxr/openxr_render_loop.h" #include "device/vr/openxr/openxr_api_wrapper.h" +#include "device/vr/openxr/openxr_gamepad_helper.h" namespace device { @@ -45,11 +46,12 @@ } mojom::XRGamepadDataPtr OpenXrRenderLoop::GetNextGamepadData() { - return nullptr; + return gamepad_helper_->GetGamepadData(openxr_->GetPredictedDisplayTime()); } bool OpenXrRenderLoop::StartRuntime() { DCHECK(!openxr_); + DCHECK(!gamepad_helper_); // The new wrapper object is stored in a temporary variable instead of // openxr_ so that the local unique_ptr cleans up the object if starting @@ -64,7 +66,8 @@ if (XR_FAILED(openxr->GetLuid(&luid)) || !texture_helper_.SetAdapterLUID(luid) || !texture_helper_.EnsureInitialized() || - XR_FAILED(openxr->StartSession(texture_helper_.GetDevice()))) { + XR_FAILED(openxr->StartSession(texture_helper_.GetDevice(), + &gamepad_helper_))) { texture_helper_.Reset(); return false; } @@ -78,12 +81,15 @@ texture_helper_.SetDefaultSize(gfx::Size(width, height)); DCHECK(openxr_); + DCHECK(gamepad_helper_); + return true; } void OpenXrRenderLoop::StopRuntime() { openxr_ = nullptr; texture_helper_.Reset(); + gamepad_helper_.reset(); } void OpenXrRenderLoop::OnSessionStart() {
diff --git a/device/vr/openxr/openxr_render_loop.h b/device/vr/openxr/openxr_render_loop.h index adf069c8..8fc324f7 100644 --- a/device/vr/openxr/openxr_render_loop.h +++ b/device/vr/openxr/openxr_render_loop.h
@@ -14,6 +14,7 @@ namespace device { class OpenXrApiWrapper; +class OpenXrGamepadHelper; class OpenXrRenderLoop : public XRCompositorCommon { public: @@ -33,6 +34,7 @@ bool SubmitCompositedFrame() override; std::unique_ptr<OpenXrApiWrapper> openxr_; + std::unique_ptr<OpenXrGamepadHelper> gamepad_helper_; DISALLOW_COPY_AND_ASSIGN(OpenXrRenderLoop); };
diff --git a/device/vr/openxr/openxr_util.h b/device/vr/openxr/openxr_util.h index 6edcd31..663fb7d 100644 --- a/device/vr/openxr/openxr_util.h +++ b/device/vr/openxr/openxr_util.h
@@ -22,6 +22,14 @@ return xr_result; \ } while (false) +// If xrstate variable is not active, early return XR error code +// XR_STATE_UNAVAILABLE because its value won't be valid. +#define RETURN_IF_XR_STATE_IS_NOT_ACTIVE(xrstate) \ + do { \ + if (!xrstate.isActive) \ + return XR_STATE_UNAVAILABLE; \ + } while (false) + // Returns the identity pose, where the position is {0, 0, 0} and the // orientation is {0, 0, 0, 1}. XrPosef PoseIdentity();
diff --git a/docs/flag_expiry.md b/docs/flag_expiry.md index 460537c8..f739ccb 100644 --- a/docs/flag_expiry.md +++ b/docs/flag_expiry.md
@@ -110,7 +110,6 @@ * enable-native-google-assistant * enable-reopen-tab-in-product-help * enable-safe-browsing-ap-download-verdicts -* enable-vaapi-jpeg-image-decode-acceleration * enable-webrtc-hw-vp9-encoding * enable-webrtc-pipewire-capturer * enable-zero-state-suggestions
diff --git a/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc b/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc index 2163ddbb..f763c83 100644 --- a/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc +++ b/extensions/browser/api/feedback_private/feedback_private_api_chromeos_unittest.cc
@@ -207,7 +207,7 @@ EXPECT_TRUE( RunReadLogSourceFunction(params, &result_reader_id, &result_string)); EXPECT_EQ(*params.reader_id, result_reader_id); - EXPECT_EQ("11:22:33:00:00:01", result_string); + EXPECT_EQ("[MAC OUI=11:22:33 IFACE=1]", result_string); } TEST_F(FeedbackPrivateApiUnittest, ReadLogSourceMultipleSources) {
diff --git a/extensions/browser/content_verifier/test_utils.cc b/extensions/browser/content_verifier/test_utils.cc index c99fc00..0927ab8 100644 --- a/extensions/browser/content_verifier/test_utils.cc +++ b/extensions/browser/content_verifier/test_utils.cc
@@ -133,6 +133,10 @@ MockContentVerifierDelegate::MockContentVerifierDelegate() = default; MockContentVerifierDelegate::~MockContentVerifierDelegate() = default; +bool MockContentVerifierDelegate::ShouldBeChecked(const Extension& extension) { + return true; +} + bool MockContentVerifierDelegate::ShouldBeVerified(const Extension& extension) { return true; }
diff --git a/extensions/browser/content_verifier/test_utils.h b/extensions/browser/content_verifier/test_utils.h index f6fd587..9b72376 100644 --- a/extensions/browser/content_verifier/test_utils.h +++ b/extensions/browser/content_verifier/test_utils.h
@@ -111,6 +111,7 @@ ~MockContentVerifierDelegate() override; // ContentVerifierDelegate: + bool ShouldBeChecked(const Extension& extension) override; bool ShouldBeVerified(const Extension& extension) override; ContentVerifierKey GetPublicKey() override; GURL GetSignatureFetchUrl(const ExtensionId& extension_id,
diff --git a/extensions/browser/content_verifier_delegate.h b/extensions/browser/content_verifier_delegate.h index 8447423..6888fd1 100644 --- a/extensions/browser/content_verifier_delegate.h +++ b/extensions/browser/content_verifier_delegate.h
@@ -25,11 +25,18 @@ public: virtual ~ContentVerifierDelegate() {} - // Returns whether or not resources from |extension| should be verified. + // Returns true if resources from |extension| should be checked for some + // content mismatch at all. Note that differs from ShouldBeVerified, and does + // not consider whether |extension| has signed hashes (verified_contents.json) + // or not. + virtual bool ShouldBeChecked(const Extension& extension) = 0; + + // Returns whether or not resources from |extension| should be verified using + // signed hashes data (verified_contents.json). If yes, methods GetPublicKey + // and GetSignatureFetchUrl might be used. virtual bool ShouldBeVerified(const Extension& extension) = 0; - // Returns the public key to use for validating signatures via the two out - // parameters. + // Returns the public key to use for validating signatures. virtual ContentVerifierKey GetPublicKey() = 0; // Returns a URL that can be used to fetch the verified_contents.json
diff --git a/extensions/components/native_app_window/native_app_window_views.cc b/extensions/components/native_app_window/native_app_window_views.cc index f1b3c80..84099bde 100644 --- a/extensions/components/native_app_window/native_app_window_views.cc +++ b/extensions/components/native_app_window/native_app_window_views.cc
@@ -65,7 +65,7 @@ init_params.delegate = this; if (create_params.always_on_top) init_params.z_order = ui::ZOrderLevel::kFloatingWindow; - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->CenterWindow( create_params.GetInitialWindowBounds(gfx::Insets()).size()); }
diff --git a/fuchsia/base/message_port.cc b/fuchsia/base/message_port.cc index 55d3820e..9c1bba3 100644 --- a/fuchsia/base/message_port.cc +++ b/fuchsia/base/message_port.cc
@@ -19,7 +19,7 @@ #include "mojo/public/cpp/system/message_pipe.h" #include "third_party/blink/public/common/messaging/message_port_channel.h" #include "third_party/blink/public/common/messaging/string_message_codec.h" -#include "third_party/blink/public/common/messaging/transferable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" namespace cr_fuchsia {
diff --git a/fuchsia/runners/cast/touch_input_bindings.js b/fuchsia/runners/cast/touch_input_bindings.js index 6ab7c2d..9ecd9c9f 100644 --- a/fuchsia/runners/cast/touch_input_bindings.js +++ b/fuchsia/runners/cast/touch_input_bindings.js
@@ -4,70 +4,73 @@ 'use strict'; -cast.__platform__.__touchInput__ = new class { - constructor() { - this.port_ = cast.__platform__.PortConnector.bind( - 'cast.__platform__.__touchInput__'); +// Don't supercede an Agent-provided API function. +if (!cast.__platform__.setTouchInputSupport) { + cast.__platform__.__touchInput__ = new class { + constructor() { + this.port_ = cast.__platform__.PortConnector.bind( + 'cast.__platform__.__touchInput__'); - this.port_.onmessage = function(message) { - var responseParsed = JSON.parse(message.data); - if (responseParsed) { - this.onAck(responseParsed.requestId, - responseParsed.displayControls); - } - }.bind(this); - } - - // Receives an acknowledgement from the native bindings layer and relays the - // result to the Promise. - onAck(requestId, displayControls) { - if (!this.pendingRequests_.hasOwnProperty(requestId)) { - console.error('Received ack for unknown request ID: ' + requestId); - return; + this.port_.onmessage = function(message) { + var responseParsed = JSON.parse(message.data); + if (responseParsed) { + this.onAck(responseParsed.requestId, + responseParsed.displayControls); + } + }.bind(this); } - var request = this.pendingRequests_[requestId]; - delete this.pendingRequests_[requestId]; + // Receives an acknowledgement from the native bindings layer and relays the + // result to the Promise. + onAck(requestId, displayControls) { + if (!this.pendingRequests_.hasOwnProperty(requestId)) { + console.error('Received ack for unknown request ID: ' + requestId); + return; + } - if (displayControls === undefined) { - request.reject(); - } else { - request.resolve({'displayControls': displayControls}); + var request = this.pendingRequests_[requestId]; + delete this.pendingRequests_[requestId]; + + if (displayControls === undefined) { + request.reject(); + } else { + request.resolve({'displayControls': displayControls}); + } } - } - // Requests touch input support from the native bindings layer and returns a - // Promise with the result. - // If the request was successful, the Promise will be resolved with a - // dictionary indicating whether onscreen controls should be shown for the - // application. - // If the request was rejected, then the Promise will be rejected. - setTouchInputSupport(touchEnabled) { - return new Promise((resolve, reject) => { - var requestId = this.currentRequestId_++; - this.pendingRequests_[requestId] = { - 'resolve': resolve, - 'reject': reject, - }; - this.port_.postMessage(JSON.stringify({ - 'requestId': requestId, - 'touchEnabled': touchEnabled, - })); - }); - } + // Requests touch input support from the native bindings layer and returns a + // Promise with the result. + // If the request was successful, the Promise will be resolved with a + // dictionary indicating whether onscreen controls should be shown for the + // application. + // If the request was rejected, then the Promise will be rejected. + setTouchInputSupport(touchEnabled) { + return new Promise((resolve, reject) => { + var requestId = this.currentRequestId_++; + this.pendingRequests_[requestId] = { + 'resolve': resolve, + 'reject': reject, + }; + this.port_.postMessage(JSON.stringify({ + 'requestId': requestId, + 'touchEnabled': touchEnabled, + })); + }); + } - // Port for sending requests and receiving acknowledgements with the native - // bindings layer. - port_ = null; + // Port for sending requests and receiving acknowledgements with the native + // bindings layer. + port_ = null; - // A dictionary relating inflight request IDs to their Promise resolve/reject - // functions. - pendingRequests_ = {}; + // A dictionary relating inflight request IDs to their Promise + // resolve/reject functions. + pendingRequests_ = {}; - // Unique ID of the next request. - currentRequestId_ = 0; -}; + // Unique ID of the next request. + currentRequestId_ = 0; + }; -cast.__platform__.setTouchInputSupport = - cast.__platform__.__touchInput__.setTouchInputSupport.bind( - cast.__platform__.__touchInput__); + cast.__platform__.setTouchInputSupport = + cast.__platform__.__touchInput__.setTouchInputSupport.bind( + cast.__platform__.__touchInput__); +}
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc index 4c1169d..44d34ab 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc
@@ -1687,7 +1687,8 @@ bool can_bind_to_sampler) { scoped_refptr<TexturePassthrough> passthrough_texture = nullptr; if (!resources_->texture_object_map.GetServiceID(client_texture_id, - &passthrough_texture)) { + &passthrough_texture) || + passthrough_texture == nullptr) { return; } @@ -2522,7 +2523,8 @@ void GLES2DecoderPassthroughImpl::UpdateTextureSizeFromClientID( GLuint client_id) { scoped_refptr<TexturePassthrough> texture = nullptr; - if (resources_->texture_object_map.GetServiceID(client_id, &texture)) { + if (resources_->texture_object_map.GetServiceID(client_id, &texture) && + texture != nullptr) { UpdateTextureSizeFromTexturePassthrough(texture.get(), client_id); } }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc index 0e1006c..c061f69 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc
@@ -526,7 +526,8 @@ if (service_id != 0) { // Create a new texture object to track this texture if (!resources_->texture_object_map.GetServiceID(texture, - &texture_passthrough)) { + &texture_passthrough) || + texture_passthrough == nullptr) { texture_passthrough = new TexturePassthrough(service_id, target); resources_->texture_object_map.SetIDMapping(texture, texture_passthrough); } else { @@ -4667,8 +4668,8 @@ if (contents_texture_id) { scoped_refptr<TexturePassthrough> passthrough_texture; if (!resources_->texture_object_map.GetServiceID(contents_texture_id, - &passthrough_texture) && - passthrough_texture) { + &passthrough_texture) || + passthrough_texture == nullptr) { InsertError(GL_INVALID_VALUE, "unknown texture"); return error::kNoError; } @@ -4710,8 +4711,8 @@ if (texture_id) { scoped_refptr<TexturePassthrough> passthrough_texture; if (!resources_->texture_object_map.GetServiceID(texture_id, - &passthrough_texture) && - passthrough_texture) { + &passthrough_texture) || + passthrough_texture == nullptr) { InsertError(GL_INVALID_VALUE, "unknown texture"); return error::kNoError; } @@ -4769,7 +4770,8 @@ scoped_refptr<TexturePassthrough> passthrough_texture; if (!resources_->texture_object_map.GetServiceID(texture_id, - &passthrough_texture)) { + &passthrough_texture) || + passthrough_texture == nullptr) { InsertError(GL_INVALID_VALUE, "unknown texture"); return error::kNoError; }
diff --git a/ios/chrome/app/resources/Info.plist b/ios/chrome/app/resources/Info.plist index 5681cc8..5706968 100644 --- a/ios/chrome/app/resources/Info.plist +++ b/ios/chrome/app/resources/Info.plist
@@ -196,5 +196,7 @@ <string>IDS_IOS_BLUETOOTH_USAGE_DESCRIPTION</string> <key>NSFaceIDUsageDescription</key> <string>IDS_IOS_FACE_ID_USAGE_DESCRIPTION</string> + <key>FirebaseScreenReportingEnabled</key> + <false/> </dict> </plist>
diff --git a/ios/chrome/browser/autocomplete/shortcuts_backend_factory.mm b/ios/chrome/browser/autocomplete/shortcuts_backend_factory.mm index 04f697a1..ed916b48 100644 --- a/ios/chrome/browser/autocomplete/shortcuts_backend_factory.mm +++ b/ios/chrome/browser/autocomplete/shortcuts_backend_factory.mm
@@ -31,7 +31,7 @@ bool suppress_db) { scoped_refptr<ShortcutsBackend> shortcuts_backend(new ShortcutsBackend( ios::TemplateURLServiceFactory::GetForBrowserState(browser_state), - std::make_unique<ios::UIThreadSearchTermsData>(browser_state), + std::make_unique<ios::UIThreadSearchTermsData>(), ios::HistoryServiceFactory::GetForBrowserState( browser_state, ServiceAccessType::EXPLICIT_ACCESS), browser_state->GetStatePath().Append(kShortcutsDatabaseName),
diff --git a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm index 775b06ef..e63eb3f2 100644 --- a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm +++ b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm
@@ -22,7 +22,6 @@ #include "ios/chrome/browser/feature_engagement/tracker_factory.h" #include "ios/chrome/browser/gcm/ios_chrome_gcm_profile_service_factory.h" #include "ios/chrome/browser/google/google_logo_service_factory.h" -#include "ios/chrome/browser/google/google_url_tracker_factory.h" #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/history/top_sites_factory.h" #include "ios/chrome/browser/history/web_history_service_factory.h" @@ -85,7 +84,6 @@ ios::BookmarkUndoServiceFactory::GetInstance(); ios::CookieSettingsFactory::GetInstance(); ios::FaviconServiceFactory::GetInstance(); - ios::GoogleURLTrackerFactory::GetInstance(); ios::HistoryServiceFactory::GetInstance(); ios::InMemoryURLIndexFactory::GetInstance(); ios::ShortcutsBackendFactory::GetInstance();
diff --git a/ios/chrome/browser/geolocation/BUILD.gn b/ios/chrome/browser/geolocation/BUILD.gn index 548f299..4c4c5d1 100644 --- a/ios/chrome/browser/geolocation/BUILD.gn +++ b/ios/chrome/browser/geolocation/BUILD.gn
@@ -77,7 +77,7 @@ deps = [ ":geolocation", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/version_info", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/tabs",
diff --git a/ios/chrome/browser/google/BUILD.gn b/ios/chrome/browser/google/BUILD.gn index 9544c96..c6ccf96 100644 --- a/ios/chrome/browser/google/BUILD.gn +++ b/ios/chrome/browser/google/BUILD.gn
@@ -7,18 +7,9 @@ sources = [ "google_brand.h", "google_brand.mm", - "google_url_tracker_client_impl.cc", - "google_url_tracker_client_impl.h", - "google_url_tracker_factory.cc", - "google_url_tracker_factory.h", ] deps = [ "//base", - "//components/google/core/browser", - "//components/keyed_service/ios", - "//components/prefs", - "//ios/chrome/browser", - "//ios/chrome/browser/browser_state", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/distribution", ]
diff --git a/ios/chrome/browser/google/google_url_tracker_client_impl.cc b/ios/chrome/browser/google/google_url_tracker_client_impl.cc deleted file mode 100644 index 3e9d969..0000000 --- a/ios/chrome/browser/google/google_url_tracker_client_impl.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/google/google_url_tracker_client_impl.h" - -#include "base/logging.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" - -GoogleURLTrackerClientImpl::GoogleURLTrackerClientImpl( - ios::ChromeBrowserState* browser_state) - : browser_state_(browser_state) { - DCHECK(browser_state_); -} - -GoogleURLTrackerClientImpl::~GoogleURLTrackerClientImpl() { -} - -bool GoogleURLTrackerClientImpl::IsBackgroundNetworkingEnabled() { - return true; -} - -PrefService* GoogleURLTrackerClientImpl::GetPrefs() { - return browser_state_->GetPrefs(); -} - -network::mojom::URLLoaderFactory* -GoogleURLTrackerClientImpl::GetURLLoaderFactory() { - return browser_state_->GetURLLoaderFactory(); -}
diff --git a/ios/chrome/browser/google/google_url_tracker_client_impl.h b/ios/chrome/browser/google/google_url_tracker_client_impl.h deleted file mode 100644 index 11e0f9c3..0000000 --- a/ios/chrome/browser/google/google_url_tracker_client_impl.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_IMPL_H_ -#define IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_IMPL_H_ - -#include "base/macros.h" -#include "components/google/core/browser/google_url_tracker_client.h" - -class PrefService; - -namespace ios { -class ChromeBrowserState; -} - -class GoogleURLTrackerClientImpl : public GoogleURLTrackerClient { - public: - explicit GoogleURLTrackerClientImpl(ios::ChromeBrowserState* browser_state); - ~GoogleURLTrackerClientImpl() override; - - private: - // GoogleURLTrackerClient implementation. - bool IsBackgroundNetworkingEnabled() override; - PrefService* GetPrefs() override; - network::mojom::URLLoaderFactory* GetURLLoaderFactory() override; - - ios::ChromeBrowserState* browser_state_; - - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerClientImpl); -}; - -#endif // IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_CLIENT_IMPL_H_
diff --git a/ios/chrome/browser/google/google_url_tracker_factory.cc b/ios/chrome/browser/google/google_url_tracker_factory.cc deleted file mode 100644 index 10705a79..0000000 --- a/ios/chrome/browser/google/google_url_tracker_factory.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/google/google_url_tracker_factory.h" - -#include "base/memory/ptr_util.h" -#include "base/no_destructor.h" -#include "components/google/core/browser/google_pref_names.h" -#include "components/google/core/browser/google_url_tracker.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/prefs/pref_service.h" -#include "ios/chrome/browser/application_context.h" -#include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/google/google_url_tracker_client_impl.h" - -namespace ios { - -// static -GoogleURLTracker* GoogleURLTrackerFactory::GetForBrowserState( - ios::ChromeBrowserState* browser_state) { - return static_cast<GoogleURLTracker*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -GoogleURLTrackerFactory* GoogleURLTrackerFactory::GetInstance() { - static base::NoDestructor<GoogleURLTrackerFactory> instance; - return instance.get(); -} - -GoogleURLTrackerFactory::GoogleURLTrackerFactory() - : BrowserStateKeyedServiceFactory( - "GoogleURLTracker", - BrowserStateDependencyManager::GetInstance()) { -} - -GoogleURLTrackerFactory::~GoogleURLTrackerFactory() { -} - -std::unique_ptr<KeyedService> GoogleURLTrackerFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - ios::ChromeBrowserState* browser_state = - ios::ChromeBrowserState::FromBrowserState(context); - - // Delete this now-unused pref. - // At some point in the future, this code can be removed entirely. - browser_state->GetOriginalChromeBrowserState()->GetPrefs()->ClearPref( - prefs::kLastPromptedGoogleURL); - - return std::make_unique<GoogleURLTracker>( - base::WrapUnique(new GoogleURLTrackerClientImpl(browser_state)), - GoogleURLTracker::ALWAYS_DOT_COM_MODE, - GetApplicationContext()->GetNetworkConnectionTracker()); -} - -web::BrowserState* GoogleURLTrackerFactory::GetBrowserStateToUse( - web::BrowserState* context) const { - return GetBrowserStateRedirectedInIncognito(context); -} - -bool GoogleURLTrackerFactory::ServiceIsCreatedWithBrowserState() const { - return true; -} - -bool GoogleURLTrackerFactory::ServiceIsNULLWhileTesting() const { - return true; -} - -void GoogleURLTrackerFactory::RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) { - GoogleURLTracker::RegisterProfilePrefs(registry); -} - -} // namespace ios
diff --git a/ios/chrome/browser/google/google_url_tracker_factory.h b/ios/chrome/browser/google/google_url_tracker_factory.h deleted file mode 100644 index 37111c4..0000000 --- a/ios/chrome/browser/google/google_url_tracker_factory.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_ -#define IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class GoogleURLTracker; - -namespace ios { - -class ChromeBrowserState; - -// Singleton that owns all GoogleURLTrackers and associates them with -// ios::ChromeBrowserState. -class GoogleURLTrackerFactory : public BrowserStateKeyedServiceFactory { - public: - static GoogleURLTracker* GetForBrowserState( - ios::ChromeBrowserState* browser_state); - static GoogleURLTrackerFactory* GetInstance(); - - private: - friend class base::NoDestructor<GoogleURLTrackerFactory>; - - GoogleURLTrackerFactory(); - ~GoogleURLTrackerFactory() override; - - // BrowserStateKeyedServiceFactory implementation. - std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; - web::BrowserState* GetBrowserStateToUse( - web::BrowserState* context) const override; - bool ServiceIsCreatedWithBrowserState() const override; - bool ServiceIsNULLWhileTesting() const override; - void RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - - DISALLOW_COPY_AND_ASSIGN(GoogleURLTrackerFactory); -}; - -} // namespace ios - -#endif // IOS_CHROME_BROWSER_GOOGLE_GOOGLE_URL_TRACKER_FACTORY_H_
diff --git a/ios/chrome/browser/metrics/BUILD.gn b/ios/chrome/browser/metrics/BUILD.gn index 293fc7b..d39a57b5 100644 --- a/ios/chrome/browser/metrics/BUILD.gn +++ b/ios/chrome/browser/metrics/BUILD.gn
@@ -171,7 +171,7 @@ deps = [ ":metrics", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//ios/chrome/browser", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/prerender",
diff --git a/ios/chrome/browser/overlays/public/web_content_area/BUILD.gn b/ios/chrome/browser/overlays/public/web_content_area/BUILD.gn index 389d71c..989da65 100644 --- a/ios/chrome/browser/overlays/public/web_content_area/BUILD.gn +++ b/ios/chrome/browser/overlays/public/web_content_area/BUILD.gn
@@ -4,6 +4,8 @@ source_set("web_content_area") { sources = [ + "app_launcher_alert_overlay.h", + "app_launcher_alert_overlay.mm", "http_auth_overlay.h", "http_auth_overlay.mm", "java_script_alert_overlay.h",
diff --git a/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h new file mode 100644 index 0000000..035eab47 --- /dev/null +++ b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h
@@ -0,0 +1,43 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_APP_LAUNCHER_ALERT_OVERLAY_H_ +#define IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_APP_LAUNCHER_ALERT_OVERLAY_H_ + +#include "ios/chrome/browser/overlays/public/overlay_user_data.h" + +// Configuration object for OverlayRequests for alerts notifying the user that +// a navigation will open another app. +class AppLauncherAlertOverlayRequestConfig + : public OverlayUserData<AppLauncherAlertOverlayRequestConfig> { + public: + ~AppLauncherAlertOverlayRequestConfig() override; + + // Whether the current page has previously attempted to open another app. + bool is_repeated_request() const { return is_repeated_request_; } + + private: + OVERLAY_USER_DATA_SETUP(AppLauncherAlertOverlayRequestConfig); + AppLauncherAlertOverlayRequestConfig(bool is_repeated_request); + + const bool is_repeated_request_; +}; + +// User interaction info for OverlayResponses for app launcher alerts. +class AppLauncherAlertOverlayResponseInfo + : public OverlayUserData<AppLauncherAlertOverlayResponseInfo> { + public: + ~AppLauncherAlertOverlayResponseInfo() override; + + // Whether the user has chosen to allow navigation to another app. + bool allow_navigation() const { return allow_navigation_; } + + private: + OVERLAY_USER_DATA_SETUP(AppLauncherAlertOverlayResponseInfo); + AppLauncherAlertOverlayResponseInfo(bool allow_navigation); + + const bool allow_navigation_; +}; + +#endif // IOS_CHROME_BROWSER_OVERLAYS_PUBLIC_WEB_CONTENT_AREA_APP_LAUNCHER_ALERT_OVERLAY_H_
diff --git a/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.mm b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.mm new file mode 100644 index 0000000..baad597 --- /dev/null +++ b/ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.mm
@@ -0,0 +1,27 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +OVERLAY_USER_DATA_SETUP_IMPL(AppLauncherAlertOverlayRequestConfig); + +AppLauncherAlertOverlayRequestConfig::AppLauncherAlertOverlayRequestConfig( + bool is_repeated_request) + : is_repeated_request_(is_repeated_request) {} + +AppLauncherAlertOverlayRequestConfig::~AppLauncherAlertOverlayRequestConfig() = + default; + +OVERLAY_USER_DATA_SETUP_IMPL(AppLauncherAlertOverlayResponseInfo); + +AppLauncherAlertOverlayResponseInfo::AppLauncherAlertOverlayResponseInfo( + bool allow_navigation) + : allow_navigation_(allow_navigation) {} + +AppLauncherAlertOverlayResponseInfo::~AppLauncherAlertOverlayResponseInfo() = + default;
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 30b29552..5d8c106 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -70,6 +70,8 @@ namespace { const char kReverseAutologinEnabled[] = "reverse_autologin.enabled"; +const char kLastKnownGoogleURL[] = "browser.last_known_google_url"; +const char kLastPromptedGoogleURL[] = "browser.last_prompted_google_url"; } void RegisterLocalStatePrefs(PrefRegistrySimple* registry) { @@ -179,6 +181,8 @@ browsing_data::prefs::RegisterBrowserUserPrefs(registry); registry->RegisterBooleanPref(kReverseAutologinEnabled, true); + registry->RegisterStringPref(kLastKnownGoogleURL, std::string()); + registry->RegisterStringPref(kLastPromptedGoogleURL, std::string()); } // This method should be periodically pruned of year+ old migrations. @@ -205,4 +209,6 @@ syncer::ClearObsoleteAuthErrorPrefs(prefs); syncer::ClearObsoleteFirstSyncTime(prefs); syncer::ClearObsoleteSyncLongPollIntervalSeconds(prefs); + prefs->ClearPref(kLastKnownGoogleURL); + prefs->ClearPref(kLastPromptedGoogleURL); }
diff --git a/ios/chrome/browser/reading_list/BUILD.gn b/ios/chrome/browser/reading_list/BUILD.gn index 034b4fc..362bca99 100644 --- a/ios/chrome/browser/reading_list/BUILD.gn +++ b/ios/chrome/browser/reading_list/BUILD.gn
@@ -33,7 +33,7 @@ "//components/dom_distiller/ios", "//components/favicon/core", "//components/favicon/ios", - "//components/google/core/browser", + "//components/google/core/common", "//components/keyed_service/core", "//components/keyed_service/ios", "//components/pref_registry",
diff --git a/ios/chrome/browser/search_engines/BUILD.gn b/ios/chrome/browser/search_engines/BUILD.gn index fcb6f27..43f2bfc 100644 --- a/ios/chrome/browser/search_engines/BUILD.gn +++ b/ios/chrome/browser/search_engines/BUILD.gn
@@ -26,7 +26,7 @@ "//base", "//components/country_codes", "//components/favicon/ios", - "//components/google/core/browser", + "//components/google/core/common", "//components/history/core/browser", "//components/keyed_service/core", "//components/keyed_service/ios",
diff --git a/ios/chrome/browser/search_engines/template_url_service_factory.cc b/ios/chrome/browser/search_engines/template_url_service_factory.cc index 3ca6db4..b418403 100644 --- a/ios/chrome/browser/search_engines/template_url_service_factory.cc +++ b/ios/chrome/browser/search_engines/template_url_service_factory.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/callback.h" -#include "base/memory/ptr_util.h" #include "base/no_destructor.h" #include "components/keyed_service/core/service_access_type.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" @@ -15,7 +14,6 @@ #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/browser_state_otr_helper.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/google/google_url_tracker_factory.h" #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/search_engines/template_url_service_client_impl.h" #include "ios/chrome/browser/search_engines/ui_thread_search_terms_data.h" @@ -45,13 +43,12 @@ ios::ChromeBrowserState::FromBrowserState(context); return std::make_unique<TemplateURLService>( browser_state->GetPrefs(), - base::WrapUnique(new ios::UIThreadSearchTermsData(browser_state)), + std::make_unique<ios::UIThreadSearchTermsData>(), ios::WebDataServiceFactory::GetKeywordWebDataForBrowserState( browser_state, ServiceAccessType::EXPLICIT_ACCESS), - base::WrapUnique(new ios::TemplateURLServiceClientImpl( + std::make_unique<ios::TemplateURLServiceClientImpl>( ios::HistoryServiceFactory::GetForBrowserState( - browser_state, ServiceAccessType::EXPLICIT_ACCESS))), - ios::GoogleURLTrackerFactory::GetForBrowserState(browser_state), + browser_state, ServiceAccessType::EXPLICIT_ACCESS)), GetApplicationContext()->GetRapporServiceImpl(), GetDefaultSearchProviderChangedCallback()); } @@ -81,7 +78,6 @@ : BrowserStateKeyedServiceFactory( "TemplateURLService", BrowserStateDependencyManager::GetInstance()) { - DependsOn(ios::GoogleURLTrackerFactory::GetInstance()); DependsOn(ios::HistoryServiceFactory::GetInstance()); DependsOn(ios::WebDataServiceFactory::GetInstance()); }
diff --git a/ios/chrome/browser/search_engines/ui_thread_search_terms_data.cc b/ios/chrome/browser/search_engines/ui_thread_search_terms_data.cc index 539f065b..af4863d 100644 --- a/ios/chrome/browser/search_engines/ui_thread_search_terms_data.cc +++ b/ios/chrome/browser/search_engines/ui_thread_search_terms_data.cc
@@ -6,13 +6,11 @@ #include "base/logging.h" #include "base/strings/string16.h" -#include "components/google/core/browser/google_url_tracker.h" #include "components/google/core/common/google_util.h" #include "components/omnibox/browser/omnibox_field_trial.h" #include "components/version_info/version_info.h" #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/google/google_brand.h" -#include "ios/chrome/browser/google/google_url_tracker_factory.h" #include "ios/chrome/browser/system_flags.h" #include "ios/chrome/common/channel_info.h" #include "ios/web/public/thread/web_thread.h" @@ -26,9 +24,7 @@ namespace ios { -UIThreadSearchTermsData::UIThreadSearchTermsData( - ios::ChromeBrowserState* browser_state) - : browser_state_(browser_state) { +UIThreadSearchTermsData::UIThreadSearchTermsData() { DCHECK(!web::WebThread::IsThreadInitialized(web::WebThread::UI) || web::WebThread::CurrentlyOn(web::WebThread::UI)); } @@ -41,13 +37,7 @@ if (google_base_url.is_valid()) return google_base_url.spec(); - if (!browser_state_) - return SearchTermsData::GoogleBaseURLValue(); - - GoogleURLTracker* google_url_tracker = - ios::GoogleURLTrackerFactory::GetForBrowserState(browser_state_); - return google_url_tracker ? google_url_tracker->google_url().spec() - : GoogleURLTracker::kDefaultGoogleHomepage; + return SearchTermsData::GoogleBaseURLValue(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const {
diff --git a/ios/chrome/browser/search_engines/ui_thread_search_terms_data.h b/ios/chrome/browser/search_engines/ui_thread_search_terms_data.h index 71001cf..75cfcaa 100644 --- a/ios/chrome/browser/search_engines/ui_thread_search_terms_data.h +++ b/ios/chrome/browser/search_engines/ui_thread_search_terms_data.h
@@ -11,12 +11,10 @@ namespace ios { -class ChromeBrowserState; - // Implementation of SearchTermsData that is only usable on UI thread. class UIThreadSearchTermsData : public SearchTermsData { public: - explicit UIThreadSearchTermsData(ios::ChromeBrowserState* browser_state); + UIThreadSearchTermsData(); ~UIThreadSearchTermsData() override; // SearchTermsData implementation. @@ -30,7 +28,6 @@ private: base::ThreadChecker thread_checker_; - ios::ChromeBrowserState* browser_state_; DISALLOW_COPY_AND_ASSIGN(UIThreadSearchTermsData); };
diff --git a/ios/chrome/browser/u2f/BUILD.gn b/ios/chrome/browser/u2f/BUILD.gn index 2916fa9..fd09a0e 100644 --- a/ios/chrome/browser/u2f/BUILD.gn +++ b/ios/chrome/browser/u2f/BUILD.gn
@@ -26,7 +26,7 @@ ] deps = [ "//base", - "//components/google/core/browser", + "//components/google/core/common", "//crypto", "//ios/chrome/browser", "//ios/chrome/common",
diff --git a/ios/chrome/browser/ui/authentication/BUILD.gn b/ios/chrome/browser/ui/authentication/BUILD.gn index 27e9d8a9..6d4ee01 100644 --- a/ios/chrome/browser/ui/authentication/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/BUILD.gn
@@ -35,7 +35,7 @@ "unified_consent", "//base", "//components/consent_auditor", - "//components/google/core/browser", + "//components/google/core/common", "//components/infobars/core", "//components/prefs", "//components/signin/public/base",
diff --git a/ios/chrome/browser/ui/authentication/unified_consent/BUILD.gn b/ios/chrome/browser/ui/authentication/unified_consent/BUILD.gn index 8b05a5c..729e60234 100644 --- a/ios/chrome/browser/ui/authentication/unified_consent/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/unified_consent/BUILD.gn
@@ -35,7 +35,7 @@ "resources:identity_picker_view_arrow_down", "resources:unified_consent_header", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/ui/authentication:authentication_constants",
diff --git a/ios/chrome/browser/ui/authentication/unified_consent/identity_chooser/BUILD.gn b/ios/chrome/browser/ui/authentication/unified_consent/identity_chooser/BUILD.gn index 14769fb4..cde8ee88 100644 --- a/ios/chrome/browser/ui/authentication/unified_consent/identity_chooser/BUILD.gn +++ b/ios/chrome/browser/ui/authentication/unified_consent/identity_chooser/BUILD.gn
@@ -51,7 +51,7 @@ "resources:identity_chooser_add_account", "//base", "//base:i18n", - "//components/google/core/browser", + "//components/google/core/common", "//ios/chrome/app/strings", "//ios/chrome/browser", "//ios/chrome/browser/ui/colors",
diff --git a/ios/chrome/browser/ui/location_bar/BUILD.gn b/ios/chrome/browser/ui/location_bar/BUILD.gn index 2fd031e1..e6a3946c 100644 --- a/ios/chrome/browser/ui/location_bar/BUILD.gn +++ b/ios/chrome/browser/ui/location_bar/BUILD.gn
@@ -26,7 +26,7 @@ "resources:location_bar_share", "resources:location_bar_voice", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/omnibox/browser", "//components/open_from_clipboard:", "//components/search_engines",
diff --git a/ios/chrome/browser/ui/ntp/BUILD.gn b/ios/chrome/browser/ui/ntp/BUILD.gn index 00c8f2f6..17ab2cb 100644 --- a/ios/chrome/browser/ui/ntp/BUILD.gn +++ b/ios/chrome/browser/ui/ntp/BUILD.gn
@@ -78,7 +78,7 @@ "//base:i18n", "//components/favicon/core", "//components/favicon_base", - "//components/google/core/browser", + "//components/google/core/common", "//components/history/core/browser", "//components/keyed_service/core", "//components/metrics",
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/BUILD.gn b/ios/chrome/browser/ui/overlays/web_content_area/BUILD.gn index 8f1371d..31a18c63 100644 --- a/ios/chrome/browser/ui/overlays/web_content_area/BUILD.gn +++ b/ios/chrome/browser/ui/overlays/web_content_area/BUILD.gn
@@ -15,6 +15,7 @@ deps = [ "//base", "//ios/chrome/browser/ui/overlays:coordinators", + "//ios/chrome/browser/ui/overlays/web_content_area/app_launcher", "//ios/chrome/browser/ui/overlays/web_content_area/http_auth_dialogs", "//ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs:alerts", "//ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs:confirmations",
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/BUILD.gn b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/BUILD.gn new file mode 100644 index 0000000..feea2c6 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/BUILD.gn
@@ -0,0 +1,55 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +source_set("app_launcher") { + sources = [ + "app_launcher_alert_overlay_coordinator.h", + "app_launcher_alert_overlay_coordinator.mm", + "app_launcher_alert_overlay_mediator.h", + "app_launcher_alert_overlay_mediator.mm", + ] + + configs += [ "//build/config/compiler:enable_arc" ] + + deps = [ + "//base", + "//components/strings:components_strings_grit", + "//components/url_formatter", + "//ios/chrome/app/strings:ios_strings_grit", + "//ios/chrome/browser/overlays", + "//ios/chrome/browser/overlays/public/web_content_area", + "//ios/chrome/browser/ui/alert_view_controller", + "//ios/chrome/browser/ui/elements", + "//ios/chrome/browser/ui/overlays:coordinators", + "//ui/base", + ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "app_launcher_alert_overlay_mediator_unittest.mm", + ] + + configs += [ "//build/config/compiler:enable_arc" ] + + deps = [ + ":app_launcher", + "//base/test:test_support", + "//components/strings:components_strings_grit", + "//components/url_formatter", + "//ios/chrome/app/strings:ios_strings_grit", + "//ios/chrome/browser/overlays", + "//ios/chrome/browser/overlays/public/web_content_area", + "//ios/chrome/browser/overlays/test", + "//ios/chrome/browser/ui/alert_view_controller", + "//ios/chrome/browser/ui/alert_view_controller/test", + "//ios/chrome/browser/ui/dialogs", + "//ios/chrome/browser/ui/elements", + "//ios/chrome/browser/ui/overlays/test", + "//testing/gmock", + "//testing/gtest", + "//ui/base", + ] +}
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.h b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.h new file mode 100644 index 0000000..95e9785 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.h
@@ -0,0 +1,15 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_COORDINATOR_H_ +#define IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_COORDINATOR_H_ + +#import "ios/chrome/browser/ui/overlays/overlay_request_coordinator.h" + +// A coordinator that is used to display UI for HTTP authentication dialogs via +// OverlayPresenter. +@interface AppLauncherAlertOverlayCoordinator : OverlayRequestCoordinator +@end + +#endif // IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.mm b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.mm new file mode 100644 index 0000000..10f1587 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.mm
@@ -0,0 +1,89 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.h" + +#include "ios/chrome/browser/overlays/public/overlay_request.h" +#include "ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h" +#import "ios/chrome/browser/ui/alert_view_controller/alert_view_controller.h" +#import "ios/chrome/browser/ui/overlays/overlay_ui_dismissal_delegate.h" +#import "ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface AppLauncherAlertOverlayCoordinator () < + AppLauncherAlertOverlayMediatorDelegate> +// Whether the coordinator has been started. +@property(nonatomic, getter=isStarted) BOOL started; + +@property(nonatomic) AlertViewController* alertViewController; +@property(nonatomic) AppLauncherAlertOverlayMediator* mediator; +@end + +@implementation AppLauncherAlertOverlayCoordinator + +#pragma mark - Accessors + +- (void)setMediator:(AppLauncherAlertOverlayMediator*)mediator { + if (_mediator == mediator) + return; + _mediator.delegate = nil; + _mediator = mediator; + _mediator.delegate = self; +} + +#pragma mark - AppLauncherAlertOverlayMediatorDelegate + +- (void)stopDialogForMediator:(AppLauncherAlertOverlayMediator*)mediator { + DCHECK_EQ(self.mediator, mediator); + [self stopAnimated:YES]; +} + +#pragma mark - OverlayCoordinator + ++ (BOOL)supportsRequest:(OverlayRequest*)request { + return !!request->GetConfig<AppLauncherAlertOverlayRequestConfig>(); +} + +- (UIViewController*)viewController { + return self.alertViewController; +} + +- (void)startAnimated:(BOOL)animated { + if (self.started) + return; + self.alertViewController = [[AlertViewController alloc] init]; + self.alertViewController.modalPresentationStyle = + UIModalPresentationOverCurrentContext; + self.alertViewController.modalTransitionStyle = + UIModalTransitionStyleCrossDissolve; + self.mediator = + [[AppLauncherAlertOverlayMediator alloc] initWithRequest:self.request]; + self.mediator.consumer = self.alertViewController; + [self.baseViewController presentViewController:self.alertViewController + animated:animated + completion:nil]; + self.started = YES; +} + +- (void)stopAnimated:(BOOL)animated { + if (!self.started) + return; + __weak __typeof__(self) weakSelf = self; + [self.baseViewController + dismissViewControllerAnimated:animated + completion:^{ + __typeof__(self) strongSelf = weakSelf; + if (!strongSelf) + return; + strongSelf.alertViewController = nil; + strongSelf.dismissalDelegate + ->OverlayUIDidFinishDismissal(weakSelf.request); + }]; + self.started = NO; +} + +@end
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h new file mode 100644 index 0000000..cebd594 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h
@@ -0,0 +1,43 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_MEDIATOR_H_ +#define IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_MEDIATOR_H_ + +#import <Foundation/Foundation.h> + +class OverlayRequest; +@protocol AppLauncherAlertOverlayMediatorDelegate; +@protocol AppLauncherAlertOverlayMediatorDataSource; +@protocol AlertConsumer; + +// Mediator object that uses a AppLauncherAlertOverlayRequestConfig to set up +// the UI for an alert notifying the user that a navigation will open an +// external app. +@interface AppLauncherAlertOverlayMediator : NSObject + +// The consumer to be updated by this mediator. Setting to a new value uses the +// AppLauncherAlertOverlayRequestConfig to update the new consumer. +@property(nonatomic, weak) id<AlertConsumer> consumer; + +// The delegate that handles action button functionality set up by the mediator. +@property(nonatomic, weak) id<AppLauncherAlertOverlayMediatorDelegate> delegate; + +// Designated initializer for a mediator that uses |request|'s configuration to +// set up an AlertConsumer. +- (instancetype)initWithRequest:(OverlayRequest*)request; + +@end + +// Protocol used by the actions set up by the +// AppLauncherAlertOverlayMediator. +@protocol AppLauncherAlertOverlayMediatorDelegate <NSObject> + +// Called by |mediator| to dismiss the dialog overlay when +// an action is tapped. +- (void)stopDialogForMediator:(AppLauncherAlertOverlayMediator*)mediator; + +@end + +#endif // IOS_CHROME_BROWSER_UI_OVERLAYS_WEB_CONTENT_AREA_APP_LAUNCHER_APP_LAUNCHER_ALERT_OVERLAY_MEDIATOR_H_
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.mm b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.mm new file mode 100644 index 0000000..e1048d1 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.mm
@@ -0,0 +1,94 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h" + +#include "base/logging.h" +#include "components/strings/grit/components_strings.h" +#include "ios/chrome/browser/overlays/public/overlay_request.h" +#include "ios/chrome/browser/overlays/public/overlay_response.h" +#include "ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h" +#import "ios/chrome/browser/ui/alert_view_controller/alert_action.h" +#import "ios/chrome/browser/ui/alert_view_controller/alert_consumer.h" +#import "ios/chrome/browser/ui/elements/text_field_configuration.h" +#include "ios/chrome/grit/ios_strings.h" +#include "ui/base/l10n/l10n_util.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +@interface AppLauncherAlertOverlayMediator () +@property(nonatomic, readonly) OverlayRequest* request; +@property(nonatomic, readonly) AppLauncherAlertOverlayRequestConfig* config; +@end + +@implementation AppLauncherAlertOverlayMediator + +- (instancetype)initWithRequest:(OverlayRequest*)request { + if (self = [super init]) { + _request = request; + DCHECK(_request); + // Verify that the request is configured for app launcher alerts. + DCHECK(_request->GetConfig<AppLauncherAlertOverlayRequestConfig>()); + } + return self; +} + +#pragma mark - Accessors + +- (AppLauncherAlertOverlayRequestConfig*)config { + return self.request->GetConfig<AppLauncherAlertOverlayRequestConfig>(); +} + +- (void)setConsumer:(id<AlertConsumer>)consumer { + if (self.consumer == consumer) + return; + _consumer = consumer; + + NSString* message = nil; + NSString* allowActionTitle = nil; + NSString* rejectActionTitle = l10n_util::GetNSString(IDS_CANCEL); + if (self.config->is_repeated_request()) { + message = l10n_util::GetNSString(IDS_IOS_OPEN_REPEATEDLY_ANOTHER_APP); + allowActionTitle = + l10n_util::GetNSString(IDS_IOS_OPEN_REPEATEDLY_ANOTHER_APP_ALLOW); + } else { + message = l10n_util::GetNSString(IDS_IOS_OPEN_IN_ANOTHER_APP); + allowActionTitle = + l10n_util::GetNSString(IDS_IOS_APP_LAUNCHER_OPEN_APP_BUTTON_LABEL); + } + [self.consumer setMessage:message]; + __weak __typeof__(self) weakSelf = self; + [self.consumer setActions:@[ + [AlertAction actionWithTitle:allowActionTitle + style:UIAlertActionStyleDefault + handler:^(AlertAction* action) { + __typeof__(self) strongSelf = weakSelf; + [strongSelf updateResponseAllowingAppLaunch:YES]; + [strongSelf.delegate + stopDialogForMediator:strongSelf]; + }], + [AlertAction actionWithTitle:rejectActionTitle + style:UIAlertActionStyleCancel + handler:^(AlertAction* action) { + __typeof__(self) strongSelf = weakSelf; + [strongSelf updateResponseAllowingAppLaunch:NO]; + [strongSelf.delegate + stopDialogForMediator:strongSelf]; + }], + ]]; +} + +#pragma mark - Response helpers + +// Sets the OverlayResponse. |allowAppLaunch| indicates whether the alert's +// allow button was tapped to allow the navigation to open in another app. +- (void)updateResponseAllowingAppLaunch:(BOOL)allowAppLaunch { + self.request->set_response( + OverlayResponse::CreateWithInfo<AppLauncherAlertOverlayResponseInfo>( + allowAppLaunch)); +} + +@end
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator_unittest.mm b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator_unittest.mm new file mode 100644 index 0000000..0340f22 --- /dev/null +++ b/ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator_unittest.mm
@@ -0,0 +1,85 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_mediator.h" + +#include "components/strings/grit/components_strings.h" +#import "ios/chrome/browser/overlays/public/overlay_request.h" +#import "ios/chrome/browser/overlays/public/overlay_response.h" +#import "ios/chrome/browser/overlays/public/web_content_area/app_launcher_alert_overlay.h" +#import "ios/chrome/browser/ui/alert_view_controller/alert_action.h" +#import "ios/chrome/browser/ui/alert_view_controller/test/fake_alert_consumer.h" +#include "ios/chrome/grit/ios_strings.h" +#include "testing/gtest_mac.h" +#include "testing/platform_test.h" +#include "ui/base/l10n/l10n_util.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +class AppLauncherAlertOverlayMediatorTest : public PlatformTest { + protected: + AppLauncherAlertOverlayMediatorTest() + : consumer_([[FakeAlertConsumer alloc] init]) { + UpdateConsumer(); + } + + FakeAlertConsumer* consumer() const { return consumer_; } + + // Setter for whether the test is for a repeated app launch request. + void set_is_repeated_request(bool is_repeated_request) { + if (is_repeated_request_ == is_repeated_request) + return; + is_repeated_request_ = is_repeated_request; + UpdateConsumer(); + } + + private: + // Instantiates |request_| with an OverlayRequest configured with an + // AppLauncherAlertOverlayRequestConfig set up using |is_repeated_request_|. + // Resets |mediator_| to a new AppLauncherAlertOverlayMediator created with + // |request_| and sets its consumer to |consumer_|. + void UpdateConsumer() { + request_ = + OverlayRequest::CreateWithConfig<AppLauncherAlertOverlayRequestConfig>( + is_repeated_request_); + mediator_ = [[AppLauncherAlertOverlayMediator alloc] + initWithRequest:request_.get()]; + mediator_.consumer = consumer_; + } + + FakeAlertConsumer* consumer_; + bool is_repeated_request_ = false; + std::unique_ptr<OverlayRequest> request_; + AppLauncherAlertOverlayMediator* mediator_ = nil; +}; + +// Tests that the consumer values are set correctly for the first app launch +// request. +TEST_F(AppLauncherAlertOverlayMediatorTest, FirstRequestAlertSetup) { + EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_OPEN_IN_ANOTHER_APP), + consumer().message); + ASSERT_EQ(2U, consumer().actions.count); + EXPECT_EQ(UIAlertActionStyleDefault, consumer().actions[0].style); + EXPECT_NSEQ( + l10n_util::GetNSString(IDS_IOS_APP_LAUNCHER_OPEN_APP_BUTTON_LABEL), + consumer().actions[0].title); + EXPECT_EQ(UIAlertActionStyleCancel, consumer().actions[1].style); + EXPECT_NSEQ(l10n_util::GetNSString(IDS_CANCEL), consumer().actions[1].title); +} + +// Tests that the consumer values are set correctly for the repeated app launch +// requests. +TEST_F(AppLauncherAlertOverlayMediatorTest, RepeatedRequestAlertSetup) { + set_is_repeated_request(true); + EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_OPEN_REPEATEDLY_ANOTHER_APP), + consumer().message); + ASSERT_EQ(2U, consumer().actions.count); + EXPECT_EQ(UIAlertActionStyleDefault, consumer().actions[0].style); + EXPECT_NSEQ(l10n_util::GetNSString(IDS_IOS_OPEN_REPEATEDLY_ANOTHER_APP_ALLOW), + consumer().actions[0].title); + EXPECT_EQ(UIAlertActionStyleCancel, consumer().actions[1].style); + EXPECT_NSEQ(l10n_util::GetNSString(IDS_CANCEL), consumer().actions[1].title); +}
diff --git a/ios/chrome/browser/ui/overlays/web_content_area/web_content_area_supported_overlay_coordinator_classes.mm b/ios/chrome/browser/ui/overlays/web_content_area/web_content_area_supported_overlay_coordinator_classes.mm index 886735f5..eb2ae51 100644 --- a/ios/chrome/browser/ui/overlays/web_content_area/web_content_area_supported_overlay_coordinator_classes.mm +++ b/ios/chrome/browser/ui/overlays/web_content_area/web_content_area_supported_overlay_coordinator_classes.mm
@@ -4,6 +4,7 @@ #import "ios/chrome/browser/ui/overlays/web_content_area/web_content_area_supported_overlay_coordinator_classes.h" +#import "ios/chrome/browser/ui/overlays/web_content_area/app_launcher/app_launcher_alert_overlay_coordinator.h" #import "ios/chrome/browser/ui/overlays/web_content_area/http_auth_dialogs/http_auth_dialog_overlay_coordinator.h" #import "ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_alert_overlay_coordinator.h" #import "ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs/java_script_confirmation_overlay_coordinator.h" @@ -16,7 +17,8 @@ namespace web_content_area { NSArray<Class>* GetSupportedOverlayCoordinatorClasses() { - return @ [[HTTPAuthDialogOverlayCoordinator class], + return @ [[AppLauncherAlertOverlayCoordinator class], + [HTTPAuthDialogOverlayCoordinator class], [JavaScriptAlertOverlayCoordinator class], [JavaScriptConfirmationOverlayCoordinator class], [JavaScriptPromptOverlayCoordinator class]];
diff --git a/ios/chrome/browser/ui/settings/BUILD.gn b/ios/chrome/browser/ui/settings/BUILD.gn index 61ef5a6..7317c1a 100644 --- a/ios/chrome/browser/ui/settings/BUILD.gn +++ b/ios/chrome/browser/ui/settings/BUILD.gn
@@ -104,7 +104,7 @@ "//components/content_settings/core/browser", "//components/content_settings/core/common", "//components/feature_engagement", - "//components/google/core/browser", + "//components/google/core/common", "//components/handoff", "//components/history/core/browser", "//components/image_fetcher/ios", @@ -266,7 +266,7 @@ "//base/test:test_support", "//components/autofill/core/common", "//components/content_settings/core/browser", - "//components/google/core/browser", + "//components/google/core/common", "//components/handoff", "//components/language/core/browser", "//components/password_manager/core/browser:test_support",
diff --git a/ios/chrome/browser/ui/toolbar/BUILD.gn b/ios/chrome/browser/ui/toolbar/BUILD.gn index 0c5ccd59..1b44b811 100644 --- a/ios/chrome/browser/ui/toolbar/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/BUILD.gn
@@ -25,7 +25,7 @@ ":toolbar_ui", "//base", "//components/bookmarks/browser", - "//components/google/core/browser", + "//components/google/core/common", "//components/strings", "//ios/chrome/browser", "//ios/chrome/browser/autocomplete",
diff --git a/ios/chrome/browser/voice/BUILD.gn b/ios/chrome/browser/voice/BUILD.gn index d59fedf..83497674 100644 --- a/ios/chrome/browser/voice/BUILD.gn +++ b/ios/chrome/browser/voice/BUILD.gn
@@ -53,7 +53,7 @@ deps = [ ":voice", "//base", - "//components/google/core/browser", + "//components/google/core/common", "//components/prefs", "//ios/chrome/browser", "//ios/chrome/browser/browser_state",
diff --git a/ios/chrome/test/BUILD.gn b/ios/chrome/test/BUILD.gn index 3bbb8fc..78979fce 100644 --- a/ios/chrome/test/BUILD.gn +++ b/ios/chrome/test/BUILD.gn
@@ -226,6 +226,7 @@ "//ios/chrome/browser/ui/omnibox/popup:unit_tests", "//ios/chrome/browser/ui/open_in:unit_tests", "//ios/chrome/browser/ui/overlays:unit_tests", + "//ios/chrome/browser/ui/overlays/web_content_area/app_launcher:unit_tests", "//ios/chrome/browser/ui/overlays/web_content_area/http_auth_dialogs:unit_tests", "//ios/chrome/browser/ui/overlays/web_content_area/java_script_dialogs:unit_tests", "//ios/chrome/browser/ui/payments:unit_tests",
diff --git a/ios/net/OWNERS b/ios/net/OWNERS index 706c5f3..f8d9d3d 100644 --- a/ios/net/OWNERS +++ b/ios/net/OWNERS
@@ -4,3 +4,4 @@ # TEAM: ios-directory-owners@chromium.org # OS: iOS +# COMPONENT: Internals>Services>Network
diff --git a/ios/web/navigation/crw_pending_navigation_info.h b/ios/web/navigation/crw_pending_navigation_info.h index 86da1d4..e1a09b64 100644 --- a/ios/web/navigation/crw_pending_navigation_info.h +++ b/ios/web/navigation/crw_pending_navigation_info.h
@@ -8,6 +8,8 @@ #import <UIKit/UIKit.h> #import <WebKit/WebKit.h> +#include "net/http/http_response_headers.h" + // A container object for any navigation information that is only available // during pre-commit delegate callbacks, and thus must be held until the // navigation commits and the information can be used. @@ -21,6 +23,9 @@ @property(nonatomic, assign) WKNavigationType navigationType; // HTTP request method for the load. @property(nonatomic, copy) NSString* HTTPMethod; +// HTTP headers. +@property(nonatomic, assign) scoped_refptr<net::HttpResponseHeaders> + HTTPHeaders; // Whether the pending navigation has been directly cancelled before the // navigation is committed. // Cancelled navigations should be simply discarded without handling any
diff --git a/ios/web/navigation/crw_web_view_navigation_observer.mm b/ios/web/navigation/crw_web_view_navigation_observer.mm index 7fbd2d01..9d0b67f 100644 --- a/ios/web/navigation/crw_web_view_navigation_observer.mm +++ b/ios/web/navigation/crw_web_view_navigation_observer.mm
@@ -193,11 +193,9 @@ forSameDocumentNavigation:isSameDocumentNavigation]; } else { // Same document navigation does not contain response headers. - net::HttpResponseHeaders* headers = - isSameDocumentNavigation - ? nullptr - : self.webStateImpl->GetHttpResponseHeaders(); - existingContext->SetResponseHeaders(headers); + if (isSameDocumentNavigation) { + existingContext->SetResponseHeaders(nullptr); + } existingContext->SetIsSameDocument(isSameDocumentNavigation); existingContext->SetHasCommitted(!isSameDocumentNavigation); self.webStateImpl->OnNavigationStarted(existingContext);
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 34cd2956..a7fc7bbc 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -194,7 +194,7 @@ // The page will not be changed until this navigation is committed, so the // retrieved state will be pending until |didCommitNavigation| callback. - [self updatePendingNavigationInfoFromNavigationAction:action]; + [self createPendingNavigationInfoFromNavigationAction:action]; if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && action.targetFrame.mainFrame && @@ -448,15 +448,12 @@ if ([WKResponse.response isKindOfClass:[NSHTTPURLResponse class]]) { headers = net::CreateHeadersFromNSHTTPURLResponse( static_cast<NSHTTPURLResponse*>(WKResponse.response)); - // TODO(crbug.com/551677): remove |OnHttpResponseHeadersReceived| and attach - // headers to web::NavigationContext. - self.webStateImpl->OnHttpResponseHeadersReceived(headers.get(), - responseURL); } // The page will not be changed until this navigation is committed, so the // retrieved state will be pending until |didCommitNavigation| callback. - [self updatePendingNavigationInfoFromNavigationResponse:WKResponse]; + [self updatePendingNavigationInfoFromNavigationResponse:WKResponse + HTTPHeaders:headers]; BOOL shouldRenderResponse = [self shouldRenderResponse:WKResponse]; if (!shouldRenderResponse) { @@ -757,15 +754,14 @@ if (self.pendingNavigationInfo.MIMEType) context->SetMimeType(self.pendingNavigationInfo.MIMEType); + if (self.pendingNavigationInfo.HTTPHeaders) + context->SetResponseHeaders(self.pendingNavigationInfo.HTTPHeaders); // Don't show webview for placeholder navigation to avoid covering the native // content, which may have already been shown. if (!IsPlaceholderUrl(webViewURL)) [self.delegate navigationHandlerDisplayWebView:self]; - // Update HTTP response headers. - self.webStateImpl->UpdateHttpResponseHeaders(webViewURL); - if (@available(iOS 11.3, *)) { // On iOS 11.3 didReceiveServerRedirectForProvisionalNavigation: is not // always called. So if URL was unexpectedly changed then it's probably @@ -810,7 +806,6 @@ // crbug.com/676129) context->SetHasCommitted(true); } - context->SetResponseHeaders(self.webStateImpl->GetHttpResponseHeaders()); self.webStateImpl->SetContentsMimeType( base::SysNSStringToUTF8(context->GetMimeType())); } @@ -1180,7 +1175,7 @@ // Some pieces of navigation information are only known in // |decidePolicyForNavigationAction|, but must be in a pending state until // |didgo/Navigation| where it becames current. -- (void)updatePendingNavigationInfoFromNavigationAction: +- (void)createPendingNavigationInfoFromNavigationAction: (WKNavigationAction*)action { if (action.targetFrame.mainFrame) { self.pendingNavigationInfo = [[CRWPendingNavigationInfo alloc] init]; @@ -1194,6 +1189,26 @@ } } +// Extracts navigation info from WKNavigationResponse and sets it as a pending. +// Some pieces of navigation information are only known in +// |decidePolicyForNavigationResponse|, but must be in a pending state until +// |didCommitNavigation| where it becames current. +- (void) + updatePendingNavigationInfoFromNavigationResponse: + (WKNavigationResponse*)response + HTTPHeaders: + (const scoped_refptr< + net::HttpResponseHeaders>&) + headers { + if (response.isForMainFrame) { + if (!self.pendingNavigationInfo) { + self.pendingNavigationInfo = [[CRWPendingNavigationInfo alloc] init]; + } + self.pendingNavigationInfo.MIMEType = response.response.MIMEType; + self.pendingNavigationInfo.HTTPHeaders = headers; + } +} + // Returns YES if the navigation action is associated with a main frame request. - (BOOL)isMainFrameNavigationAction:(WKNavigationAction*)action { if (action.targetFrame) { @@ -1333,20 +1348,6 @@ return rendererInitiatedWithoutInteraction || noNavigationItems; } -// Extracts navigation info from WKNavigationResponse and sets it as a pending. -// Some pieces of navigation information are only known in -// |decidePolicyForNavigationResponse|, but must be in a pending state until -// |didCommitNavigation| where it becames current. -- (void)updatePendingNavigationInfoFromNavigationResponse: - (WKNavigationResponse*)response { - if (response.isForMainFrame) { - if (!self.pendingNavigationInfo) { - self.pendingNavigationInfo = [[CRWPendingNavigationInfo alloc] init]; - } - self.pendingNavigationInfo.MIMEType = response.response.MIMEType; - } -} - // Returns YES if response should be rendered in WKWebView. - (BOOL)shouldRenderResponse:(WKNavigationResponse*)WKResponse { if (!WKResponse.canShowMIMEType) {
diff --git a/ios/web/web_state/web_state_impl.h b/ios/web/web_state/web_state_impl.h index 33621e4a..7b9e2c9 100644 --- a/ios/web/web_state/web_state_impl.h +++ b/ios/web/web_state/web_state_impl.h
@@ -38,10 +38,6 @@ @protocol CRWWebViewNavigationProxy; @class UIViewController; -namespace net { -class HttpResponseHeaders; -} - namespace web { class BrowserState; @@ -133,19 +129,6 @@ // Returns true if there is a WebUI active. bool HasWebUI(); - // Gets the HTTP response headers associated with the current page. - // NOTE: For a WKWebView-based WebState, these headers are generated via - // net::CreateHeadersFromNSHTTPURLResponse(); see comments in - // http_response_headers_util.h for limitations. - net::HttpResponseHeaders* GetHttpResponseHeaders() const; - - // Called when HTTP response headers are received. - // |resource_url| is the URL associated with the headers. - // This function has no visible effects until UpdateHttpResponseHeaders() is - // called. - void OnHttpResponseHeadersReceived(net::HttpResponseHeaders* response_headers, - const GURL& resource_url); - // Explicitly sets the MIME type, overwriting any MIME type that was set by // headers. Note that this should be called after OnNavigationCommitted, as // that is the point where MIME type is set from HTTP headers. @@ -282,11 +265,6 @@ void OnNavigationItemsPruned(size_t pruned_item_count) override; void OnNavigationItemCommitted(NavigationItem* item) override; - // Updates the HTTP response headers for the main page using the headers - // passed to the OnHttpResponseHeadersReceived() function below. - // GetHttpResponseHeaders() can be used to get the headers. - void UpdateHttpResponseHeaders(const GURL& url); - WebState* GetWebState() override; id<CRWWebViewNavigationProxy> GetWebViewNavigationProxy() const override; void GoToBackForwardListItem(WKBackForwardListItem* wk_item, @@ -358,12 +336,6 @@ // code, hence the ObserverList. base::ObserverList<WebStatePolicyDecider, true>::Unchecked policy_deciders_; - // Map of all the HTTP response headers received, for each URL. - // This map is cleared after each page load, and only the headers of the main - // page are used. - std::map<GURL, scoped_refptr<net::HttpResponseHeaders> > - response_headers_map_; - scoped_refptr<net::HttpResponseHeaders> http_response_headers_; std::string mime_type_; // Weak pointer to the interstitial page being displayed, if any.
diff --git a/ios/web/web_state/web_state_impl.mm b/ios/web/web_state/web_state_impl.mm index 8b03539..6903a68 100644 --- a/ios/web/web_state/web_state_impl.mm +++ b/ios/web/web_state/web_state_impl.mm
@@ -339,42 +339,6 @@ return interstitial_; } -net::HttpResponseHeaders* WebStateImpl::GetHttpResponseHeaders() const { - return http_response_headers_.get(); -} - -void WebStateImpl::OnHttpResponseHeadersReceived( - net::HttpResponseHeaders* response_headers, - const GURL& resource_url) { - // Store the headers in a map until the page finishes loading, as we do not - // know which URL corresponds to the main page yet. - // Remove the hash (if any) as it is sometimes altered by in-page navigations. - // TODO(crbug/551677): Simplify all this logic once UIWebView is no longer - // supported. - const GURL& url = GURLByRemovingRefFromGURL(resource_url); - response_headers_map_[url] = response_headers; -} - -void WebStateImpl::UpdateHttpResponseHeaders(const GURL& url) { - // Reset the state. - http_response_headers_ = NULL; - mime_type_.clear(); - - // Discard all the response headers except the ones for |main_page_url|. - auto it = response_headers_map_.find(GURLByRemovingRefFromGURL(url)); - if (it != response_headers_map_.end()) - http_response_headers_ = it->second; - response_headers_map_.clear(); - - if (!http_response_headers_.get()) - return; - - // MIME type. - std::string mime_type; - http_response_headers_->GetMimeType(&mime_type); - mime_type_ = mime_type; -} - void WebStateImpl::ShowWebInterstitial(WebInterstitialImpl* interstitial) { DCHECK(Configured()); interstitial_ = interstitial;
diff --git a/ios/web/web_state/web_state_impl_unittest.mm b/ios/web/web_state/web_state_impl_unittest.mm index 96cc5cea..5c4dd8f5 100644 --- a/ios/web/web_state/web_state_impl_unittest.mm +++ b/ios/web/web_state/web_state_impl_unittest.mm
@@ -208,61 +208,6 @@ EXPECT_TRUE(web_state_->GetWebController().webUsageEnabled); } -TEST_P(WebStateImplTest, ResponseHeaders) { - GURL real_url("http://foo.com/bar"); - GURL frame_url("http://frames-r-us.com/"); - auto real_headers = base::MakeRefCounted<net::HttpResponseHeaders>( - net::HttpUtil::AssembleRawHeaders("HTTP/1.1 200 OK\r\n" - "Content-Type: text/html\r\n" - "X-Should-Be-Here: yep\r\n" - "\r\n")); - auto frame_headers = base::MakeRefCounted<net::HttpResponseHeaders>( - net::HttpUtil::AssembleRawHeaders("HTTP/1.1 200 OK\r\n" - "Content-Type: application/pdf\r\n" - "X-Should-Not-Be-Here: oops\r\n" - "\r\n")); - // Simulate a load of a page with a frame. - web_state_->OnHttpResponseHeadersReceived(real_headers.get(), real_url); - web_state_->OnHttpResponseHeadersReceived(frame_headers.get(), frame_url); - // Include a hash to be sure it's handled correctly. - web_state_->UpdateHttpResponseHeaders( - GURL(real_url.spec() + std::string("#baz"))); - - // Verify that the right header set was kept. - ASSERT_TRUE(web_state_->GetHttpResponseHeaders()); - EXPECT_TRUE( - web_state_->GetHttpResponseHeaders()->HasHeader("X-Should-Be-Here")); - EXPECT_FALSE( - web_state_->GetHttpResponseHeaders()->HasHeader("X-Should-Not-Be-Here")); - - // And that it was parsed correctly. - EXPECT_EQ("text/html", web_state_->GetContentsMimeType()); -} - -TEST_P(WebStateImplTest, ResponseHeaderClearing) { - GURL url("http://foo.com/"); - auto headers = base::MakeRefCounted<net::HttpResponseHeaders>( - net::HttpUtil::AssembleRawHeaders("HTTP/1.1 200 OK\r\n" - "Content-Type: text/html\r\n" - "\r\n")); - web_state_->OnHttpResponseHeadersReceived(headers.get(), url); - - // There should be no headers before loading. - EXPECT_EQ(NULL, web_state_->GetHttpResponseHeaders()); - - // There should be headers and parsed values after loading. - web_state_->UpdateHttpResponseHeaders(url); - ASSERT_TRUE(web_state_->GetHttpResponseHeaders()); - EXPECT_TRUE(web_state_->GetHttpResponseHeaders()->HasHeader("Content-Type")); - EXPECT_NE("", web_state_->GetContentsMimeType()); - - // ... but not after loading another page, nor should there be specific - // parsed values. - web_state_->UpdateHttpResponseHeaders(GURL("http://elsewhere.com/")); - EXPECT_EQ(NULL, web_state_->GetHttpResponseHeaders()); - EXPECT_EQ("", web_state_->GetContentsMimeType()); -} - // Tests forwarding to WebStateObserver callbacks. TEST_P(WebStateImplTest, ObserverTest) { std::unique_ptr<TestWebStateObserver> observer(
diff --git a/media/gpu/BUILD.gn b/media/gpu/BUILD.gn index a16a600..46b3b9b5 100644 --- a/media/gpu/BUILD.gn +++ b/media/gpu/BUILD.gn
@@ -103,6 +103,8 @@ "android/android_video_surface_chooser_impl.h", "android/codec_allocator.cc", "android/codec_allocator.h", + "android/codec_buffer_wait_coordinator.cc", + "android/codec_buffer_wait_coordinator.h", "android/codec_image.cc", "android/codec_image.h", "android/codec_image_group.cc",
diff --git a/media/gpu/android/codec_buffer_wait_coordinator.cc b/media/gpu/android/codec_buffer_wait_coordinator.cc new file mode 100644 index 0000000..097b03270 --- /dev/null +++ b/media/gpu/android/codec_buffer_wait_coordinator.cc
@@ -0,0 +1,84 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "media/gpu/android/codec_buffer_wait_coordinator.h" + +#include "base/android/scoped_hardware_buffer_fence_sync.h" +#include "base/metrics/histogram_macros.h" +#include "base/threading/thread_task_runner_handle.h" + +namespace media { + +// FrameAvailableEvent is a RefCounted wrapper for a WaitableEvent +// (it's not possible to put one in RefCountedData). +// This let's us safely signal an event on any thread. +struct FrameAvailableEvent + : public base::RefCountedThreadSafe<FrameAvailableEvent> { + FrameAvailableEvent() + : event(base::WaitableEvent::ResetPolicy::AUTOMATIC, + base::WaitableEvent::InitialState::NOT_SIGNALED) {} + void Signal() { event.Signal(); } + base::WaitableEvent event; + + private: + friend class RefCountedThreadSafe<FrameAvailableEvent>; + ~FrameAvailableEvent() = default; +}; + +CodecBufferWaitCoordinator::CodecBufferWaitCoordinator( + scoped_refptr<TextureOwner> texture_owner) + : texture_owner_(std::move(texture_owner)), + frame_available_event_(new FrameAvailableEvent()), + task_runner_(base::ThreadTaskRunnerHandle::Get()) { + DCHECK(texture_owner_); + texture_owner_->SetFrameAvailableCallback(base::BindRepeating( + &FrameAvailableEvent::Signal, frame_available_event_)); +} + +CodecBufferWaitCoordinator::~CodecBufferWaitCoordinator() = default; + +void CodecBufferWaitCoordinator::SetReleaseTimeToNow() { + release_time_ = base::TimeTicks::Now(); +} + +bool CodecBufferWaitCoordinator::IsExpectingFrameAvailable() { + return !release_time_.is_null(); +} + +void CodecBufferWaitCoordinator::WaitForFrameAvailable() { + DCHECK(!release_time_.is_null()); + + // 5msec covers >99.9% of cases, so just wait for up to that much before + // giving up. If an error occurs, we might not ever get a notification. + const base::TimeDelta max_wait = base::TimeDelta::FromMilliseconds(5); + const base::TimeTicks call_time = base::TimeTicks::Now(); + const base::TimeDelta elapsed = call_time - release_time_; + const base::TimeDelta remaining = max_wait - elapsed; + release_time_ = base::TimeTicks(); + bool timed_out = false; + + if (remaining <= base::TimeDelta()) { + if (!frame_available_event_->event.IsSignaled()) { + DVLOG(1) << "Deferred WaitForFrameAvailable() timed out, elapsed: " + << elapsed.InMillisecondsF() << "ms"; + timed_out = true; + } + } else { + DCHECK_LE(remaining, max_wait); + SCOPED_UMA_HISTOGRAM_TIMER( + "Media.CodecImage.CodecBufferWaitCoordinator.WaitTimeForFrame"); + if (!frame_available_event_->event.TimedWait(remaining)) { + DVLOG(1) << "WaitForFrameAvailable() timed out, elapsed: " + << elapsed.InMillisecondsF() + << "ms, additionally waited: " << remaining.InMillisecondsF() + << "ms, total: " << (elapsed + remaining).InMillisecondsF() + << "ms"; + timed_out = true; + } + } + UMA_HISTOGRAM_BOOLEAN( + "Media.CodecImage.CodecBufferWaitCoordinator.FrameTimedOut", timed_out); +} + +} // namespace media
diff --git a/media/gpu/android/codec_buffer_wait_coordinator.h b/media/gpu/android/codec_buffer_wait_coordinator.h new file mode 100644 index 0000000..2f758b4 --- /dev/null +++ b/media/gpu/android/codec_buffer_wait_coordinator.h
@@ -0,0 +1,63 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef MEDIA_GPU_ANDROID_CODEC_BUFFER_WAIT_COORDINATOR_H_ +#define MEDIA_GPU_ANDROID_CODEC_BUFFER_WAIT_COORDINATOR_H_ + +#include "base/memory/ref_counted.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/thread_checker.h" +#include "base/time/time.h" +#include "media/gpu/android/texture_owner.h" +#include "media/gpu/media_gpu_export.h" + +namespace media { + +struct FrameAvailableEvent; + +// This class supports waiting for codec buffers to be released/rendered before +// using them. This class is RefCountedThreadSafe to make sure it's safe to +// keep and drop refptrs to it on any thread. +class MEDIA_GPU_EXPORT CodecBufferWaitCoordinator + : public base::RefCountedThreadSafe<CodecBufferWaitCoordinator> { + public: + explicit CodecBufferWaitCoordinator( + scoped_refptr<TextureOwner> texture_owner); + + scoped_refptr<TextureOwner> texture_owner() { return texture_owner_; } + + // Codec buffer wait management apis. + // Sets the expectation of onFrameAVailable for a new frame because a buffer + // was just released to this surface. + virtual void SetReleaseTimeToNow(); + + // Whether we're expecting onFrameAvailable. True when SetReleaseTimeToNow() + // was called but WaitForFrameAvailable() have not been called since. + virtual bool IsExpectingFrameAvailable(); + + // Waits for onFrameAvailable until it's been 5ms since the buffer was + // released. This must only be called if IsExpectingFrameAvailable(). + virtual void WaitForFrameAvailable(); + + scoped_refptr<base::SingleThreadTaskRunner> task_runner() { + return task_runner_; + } + + protected: + virtual ~CodecBufferWaitCoordinator(); + + private: + friend class base::RefCountedThreadSafe<CodecBufferWaitCoordinator>; + + scoped_refptr<TextureOwner> texture_owner_; + base::TimeTicks release_time_; + scoped_refptr<FrameAvailableEvent> frame_available_event_; + scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + + DISALLOW_COPY_AND_ASSIGN(CodecBufferWaitCoordinator); +}; + +} // namespace media + +#endif // MEDIA_GPU_ANDROID_CODEC_BUFFER_WAIT_COORDINATOR_H_
diff --git a/media/gpu/android/codec_image.cc b/media/gpu/android/codec_image.cc index 257b0ad0..44ca2b3 100644 --- a/media/gpu/android/codec_image.cc +++ b/media/gpu/android/codec_image.cc
@@ -52,12 +52,12 @@ void CodecImage::Initialize( std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator, PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb) { DCHECK(output_buffer); phase_ = Phase::kInCodec; output_buffer_ = std::move(output_buffer); - texture_owner_ = std::move(texture_owner); + codec_buffer_wait_coordinator_ = std::move(codec_buffer_wait_coordinator); promotion_hint_cb_ = std::move(promotion_hint_cb); } @@ -83,7 +83,7 @@ CodecImage::BindOrCopy CodecImage::ShouldBindOrCopy() { // If we're using an overlay, then pretend it's bound. That way, we'll get // calls to ScheduleOverlayPlane. Otherwise, CopyTexImage needs to be called. - return !texture_owner_ ? BIND : COPY; + return !codec_buffer_wait_coordinator_ ? BIND : COPY; } bool CodecImage::BindTexImage(unsigned target) { @@ -103,7 +103,9 @@ GLint bound_service_id = 0; glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &bound_service_id); // The currently bound texture should be the texture owner's texture. - if (bound_service_id != static_cast<GLint>(texture_owner_->GetTextureId())) + if (bound_service_id != + static_cast<GLint>( + codec_buffer_wait_coordinator_->texture_owner()->GetTextureId())) return false; RenderToTextureOwnerFrontBuffer(BindingsMode::kEnsureTexImageBound); @@ -125,7 +127,7 @@ bool enable_blend, std::unique_ptr<gfx::GpuFence> gpu_fence) { TRACE_EVENT0("media", "CodecImage::ScheduleOverlayPlane"); - if (texture_owner_) { + if (codec_buffer_wait_coordinator_) { DVLOG(1) << "Invalid call to ScheduleOverlayPlane; this image is " "TextureOwner backed."; return false; @@ -159,14 +161,14 @@ 0, 1, 0, 1 // }; memcpy(matrix, kYInvertedIdentity, sizeof(kYInvertedIdentity)); - if (!texture_owner_) + if (!codec_buffer_wait_coordinator_) return; // The matrix is available after we render to the front buffer. If that fails // we'll return the matrix from the previous frame, which is more likely to be // correct than the identity matrix anyway. RenderToTextureOwnerFrontBuffer(BindingsMode::kDontRestoreIfBound); - texture_owner_->GetTransformMatrix(matrix); + codec_buffer_wait_coordinator_->texture_owner()->GetTransformMatrix(matrix); YInvertMatrix(matrix); } @@ -177,7 +179,7 @@ int display_height) { // If this is promotable, and we're using an overlay, then skip sending this // hint. ScheduleOverlayPlane will do it. - if (promotion_hint && !texture_owner_) + if (promotion_hint && !codec_buffer_wait_coordinator_) return; promotion_hint_cb_.Run(PromotionHintAggregator::Hint( @@ -188,13 +190,13 @@ bool CodecImage::RenderToFrontBuffer() { // This code is used to trigger early rendering of the image before it is used // for compositing, there is no need to bind the image. - return texture_owner_ + return codec_buffer_wait_coordinator_ ? RenderToTextureOwnerFrontBuffer(BindingsMode::kRestoreIfBound) : RenderToOverlay(); } bool CodecImage::RenderToTextureOwnerBackBuffer() { - DCHECK(texture_owner_); + DCHECK(codec_buffer_wait_coordinator_); DCHECK_NE(phase_, Phase::kInFrontBuffer); if (phase_ == Phase::kInBackBuffer) return true; @@ -203,19 +205,19 @@ // Wait for a previous frame available so we don't confuse it with the one // we're about to release. - if (texture_owner_->IsExpectingFrameAvailable()) - texture_owner_->WaitForFrameAvailable(); + if (codec_buffer_wait_coordinator_->IsExpectingFrameAvailable()) + codec_buffer_wait_coordinator_->WaitForFrameAvailable(); if (!output_buffer_->ReleaseToSurface()) { phase_ = Phase::kInvalidated; return false; } phase_ = Phase::kInBackBuffer; - texture_owner_->SetReleaseTimeToNow(); + codec_buffer_wait_coordinator_->SetReleaseTimeToNow(); return true; } bool CodecImage::RenderToTextureOwnerFrontBuffer(BindingsMode bindings_mode) { - DCHECK(texture_owner_); + DCHECK(codec_buffer_wait_coordinator_); if (phase_ == Phase::kInFrontBuffer) { EnsureBoundIfNeeded(bindings_mode); @@ -230,21 +232,23 @@ // The image is now in the back buffer, so promote it to the front buffer. phase_ = Phase::kInFrontBuffer; - if (texture_owner_->IsExpectingFrameAvailable()) - texture_owner_->WaitForFrameAvailable(); + if (codec_buffer_wait_coordinator_->IsExpectingFrameAvailable()) + codec_buffer_wait_coordinator_->WaitForFrameAvailable(); std::unique_ptr<ui::ScopedMakeCurrent> scoped_make_current = - MakeCurrentIfNeeded(texture_owner_.get()); + MakeCurrentIfNeeded( + codec_buffer_wait_coordinator_->texture_owner().get()); // If updating the image will implicitly update the texture bindings then // restore if requested or the update needed a context switch. bool should_restore_bindings = - texture_owner_->binds_texture_on_update() && + codec_buffer_wait_coordinator_->texture_owner() + ->binds_texture_on_update() && (bindings_mode == BindingsMode::kRestoreIfBound || !!scoped_make_current); GLint bound_service_id = 0; if (should_restore_bindings) glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &bound_service_id); - texture_owner_->UpdateTexImage(); + codec_buffer_wait_coordinator_->texture_owner()->UpdateTexImage(); EnsureBoundIfNeeded(bindings_mode); if (should_restore_bindings) glBindTexture(GL_TEXTURE_EXTERNAL_OES, bound_service_id); @@ -252,15 +256,16 @@ } void CodecImage::EnsureBoundIfNeeded(BindingsMode mode) { - DCHECK(texture_owner_); + DCHECK(codec_buffer_wait_coordinator_); - if (texture_owner_->binds_texture_on_update()) { + if (codec_buffer_wait_coordinator_->texture_owner() + ->binds_texture_on_update()) { was_tex_image_bound_ = true; return; } if (mode != BindingsMode::kEnsureTexImageBound) return; - texture_owner_->EnsureTexImageBound(); + codec_buffer_wait_coordinator_->texture_owner()->EnsureTexImageBound(); was_tex_image_bound_ = true; } @@ -285,10 +290,10 @@ std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> CodecImage::GetAHardwareBuffer() { - DCHECK(texture_owner_); + DCHECK(codec_buffer_wait_coordinator_); RenderToTextureOwnerFrontBuffer(BindingsMode::kDontRestoreIfBound); - return texture_owner_->GetAHardwareBuffer(); + return codec_buffer_wait_coordinator_->texture_owner()->GetAHardwareBuffer(); } CodecImageHolder::CodecImageHolder(
diff --git a/media/gpu/android/codec_image.h b/media/gpu/android/codec_image.h index 1525597..fdbfc31b 100644 --- a/media/gpu/android/codec_image.h +++ b/media/gpu/android/codec_image.h
@@ -13,9 +13,9 @@ #include "base/macros.h" #include "base/memory/ref_counted_delete_on_sequence.h" #include "gpu/command_buffer/service/gl_stream_texture_image.h" +#include "media/gpu/android/codec_buffer_wait_coordinator.h" #include "media/gpu/android/codec_wrapper.h" #include "media/gpu/android/promotion_hint_aggregator.h" -#include "media/gpu/android/surface_texture_gl_owner.h" #include "media/gpu/media_gpu_export.h" namespace base { @@ -52,7 +52,7 @@ // not in use. void Initialize( std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator, PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb); void SetNowUnusedCB(NowUnusedCB now_unused_cb); @@ -100,9 +100,13 @@ bool was_tex_image_bound() const { return was_tex_image_bound_; } // Whether this image is backed by a texture owner. - bool is_texture_owner_backed() const { return !!texture_owner_; } + bool is_texture_owner_backed() const { + return !!codec_buffer_wait_coordinator_->texture_owner(); + } - scoped_refptr<TextureOwner> texture_owner() const { return texture_owner_; } + scoped_refptr<TextureOwner> texture_owner() const { + return codec_buffer_wait_coordinator_->texture_owner(); + } // Renders this image to the front buffer of its backing surface. // Returns true if the buffer is in the front buffer. Returns false if the @@ -160,9 +164,9 @@ // The buffer backing this image. std::unique_ptr<CodecOutputBuffer> output_buffer_; - // The TextureOwner that |output_buffer_| will be rendered to. Or null, if - // this image is backed by an overlay. - scoped_refptr<TextureOwner> texture_owner_; + // The CodecBufferWaitCoordinator that |output_buffer_| will be rendered to. + // Or null, if this image is backed by an overlay. + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator_; // The bounds last sent to the overlay. gfx::Rect most_recent_bounds_;
diff --git a/media/gpu/android/codec_image_unittest.cc b/media/gpu/android/codec_image_unittest.cc index 7e3686e..2b7db53 100644 --- a/media/gpu/android/codec_image_unittest.cc +++ b/media/gpu/android/codec_image_unittest.cc
@@ -61,8 +61,11 @@ // The tests rely on this texture being bound. glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture_id_); - texture_owner_ = new NiceMock<MockTextureOwner>( + auto texture_owner = base::MakeRefCounted<NiceMock<MockTextureOwner>>( texture_id_, context_.get(), surface_.get(), BindsTextureOnUpdate()); + codec_buffer_wait_coordinator_ = + base::MakeRefCounted<NiceMock<MockCodecBufferWaitCoordinator>>( + std::move(texture_owner)); } void TearDown() override { @@ -83,7 +86,8 @@ wrapper_->DequeueOutputBuffer(nullptr, nullptr, &buffer); scoped_refptr<CodecImage> image = new CodecImage(); image->Initialize( - std::move(buffer), kind == kTextureOwner ? texture_owner_ : nullptr, + std::move(buffer), + kind == kTextureOwner ? codec_buffer_wait_coordinator_ : nullptr, base::BindRepeating(&PromotionHintReceiver::OnPromotionHint, base::Unretained(&promotion_hint_receiver_))); @@ -96,7 +100,8 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; NiceMock<MockMediaCodecBridge>* codec_; std::unique_ptr<CodecWrapper> wrapper_; - scoped_refptr<NiceMock<MockTextureOwner>> texture_owner_; + scoped_refptr<NiceMock<MockCodecBufferWaitCoordinator>> + codec_buffer_wait_coordinator_; scoped_refptr<gl::GLContext> context_; scoped_refptr<gl::GLShareGroup> share_group_; scoped_refptr<gl::GLSurface> surface_; @@ -170,8 +175,9 @@ // Verify that the release comes before the wait. InSequence s; EXPECT_CALL(*codec_, ReleaseOutputBuffer(_, true)); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); i->CopyTexImage(GL_TEXTURE_EXTERNAL_OES); ASSERT_TRUE(i->was_rendered_to_front_buffer()); } @@ -181,9 +187,11 @@ // Verify that the release comes before the wait. InSequence s; EXPECT_CALL(*codec_, ReleaseOutputBuffer(_, true)); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); - EXPECT_CALL(*texture_owner_, EnsureTexImageBound()); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + EnsureTexImageBound()); i->CopyTexImage(GL_TEXTURE_EXTERNAL_OES); ASSERT_TRUE(i->was_rendered_to_front_buffer()); } @@ -192,9 +200,11 @@ auto i = NewImage(kTextureOwner); InSequence s; EXPECT_CALL(*codec_, ReleaseOutputBuffer(_, true)); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); - EXPECT_CALL(*texture_owner_, GetTransformMatrix(_)); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + GetTransformMatrix(_)); float matrix[16]; i->GetTextureMatrix(matrix); ASSERT_TRUE(i->was_rendered_to_front_buffer()); @@ -203,14 +213,17 @@ TEST_F(CodecImageTestExplicitBind, GetTextureMatrixTriggersFrontBufferRendering) { // GetTextureMatrix should not bind the image. - texture_owner_->expect_update_tex_image = false; + codec_buffer_wait_coordinator_->texture_owner()->expect_update_tex_image = + false; auto i = NewImage(kTextureOwner); InSequence s; EXPECT_CALL(*codec_, ReleaseOutputBuffer(_, true)); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); - EXPECT_CALL(*texture_owner_, GetTransformMatrix(_)); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + GetTransformMatrix(_)); float matrix[16]; i->GetTextureMatrix(matrix); ASSERT_TRUE(i->was_rendered_to_front_buffer()); @@ -254,16 +267,17 @@ auto i = NewImage(kTextureOwner); InSequence s; EXPECT_CALL(*codec_, ReleaseOutputBuffer(_, true)); - EXPECT_CALL(*texture_owner_, SetReleaseTimeToNow()); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()).Times(0); + EXPECT_CALL(*codec_buffer_wait_coordinator_, SetReleaseTimeToNow()); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()) + .Times(0); ASSERT_TRUE(i->RenderToTextureOwnerBackBuffer()); } TEST_F(CodecImageTest, PromotingTheBackBufferWaits) { auto i = NewImage(kTextureOwner); - EXPECT_CALL(*texture_owner_, SetReleaseTimeToNow()).Times(1); + EXPECT_CALL(*codec_buffer_wait_coordinator_, SetReleaseTimeToNow()).Times(1); i->RenderToTextureOwnerBackBuffer(); - EXPECT_CALL(*texture_owner_, WaitForFrameAvailable()); + EXPECT_CALL(*codec_buffer_wait_coordinator_, WaitForFrameAvailable()); ASSERT_TRUE(i->RenderToFrontBuffer()); } @@ -288,7 +302,8 @@ glGenTextures(1, &pre_bound_texture); glBindTexture(GL_TEXTURE_EXTERNAL_OES, pre_bound_texture); auto i = NewImage(kTextureOwner); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); i->RenderToFrontBuffer(); GLint post_bound_texture = 0; glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &post_bound_texture); @@ -296,13 +311,15 @@ } TEST_F(CodecImageTestExplicitBind, RenderToFrontBufferDoesNotBindTexture) { - texture_owner_->expect_update_tex_image = false; + codec_buffer_wait_coordinator_->texture_owner()->expect_update_tex_image = + false; GLuint pre_bound_texture = 0; glGenTextures(1, &pre_bound_texture); glBindTexture(GL_TEXTURE_EXTERNAL_OES, pre_bound_texture); auto i = NewImage(kTextureOwner); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); i->RenderToFrontBuffer(); GLint post_bound_texture = 0; glGetIntegerv(GL_TEXTURE_BINDING_EXTERNAL_OES, &post_bound_texture); @@ -321,9 +338,10 @@ auto i = NewImage(kTextureOwner); // Our context should not be current when UpdateTexImage() is called. - EXPECT_CALL(*texture_owner_, UpdateTexImage()).WillOnce(Invoke([&]() { - ASSERT_FALSE(context->IsCurrent(surface.get())); - })); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()) + .WillOnce( + Invoke([&]() { ASSERT_FALSE(context->IsCurrent(surface.get())); })); i->RenderToFrontBuffer(); // Our context should have been restored. ASSERT_TRUE(context->IsCurrent(surface.get())); @@ -353,12 +371,17 @@ TEST_F(CodecImageTest, GetAHardwareBuffer) { auto i = NewImage(kTextureOwner); - EXPECT_EQ(texture_owner_->get_a_hardware_buffer_count, 0); + EXPECT_EQ(codec_buffer_wait_coordinator_->texture_owner() + ->get_a_hardware_buffer_count, + 0); EXPECT_FALSE(i->was_rendered_to_front_buffer()); - EXPECT_CALL(*texture_owner_, UpdateTexImage()); + EXPECT_CALL(*codec_buffer_wait_coordinator_->texture_owner(), + UpdateTexImage()); i->GetAHardwareBuffer(); - EXPECT_EQ(texture_owner_->get_a_hardware_buffer_count, 1); + EXPECT_EQ(codec_buffer_wait_coordinator_->texture_owner() + ->get_a_hardware_buffer_count, + 1); EXPECT_TRUE(i->was_rendered_to_front_buffer()); }
diff --git a/media/gpu/android/image_reader_gl_owner.cc b/media/gpu/android/image_reader_gl_owner.cc index e2d764f..c5c14d0 100644 --- a/media/gpu/android/image_reader_gl_owner.cc +++ b/media/gpu/android/image_reader_gl_owner.cc
@@ -44,29 +44,6 @@ } } // namespace -// FrameAvailableEvent_ImageReader is a RefCounted wrapper for a WaitableEvent -// (it's not possible to put one in RefCountedData). This lets us safely signal -// an event on any thread. -struct FrameAvailableEvent_ImageReader - : public base::RefCountedThreadSafe<FrameAvailableEvent_ImageReader> { - FrameAvailableEvent_ImageReader() - : event(base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - void Signal() { event.Signal(); } - base::WaitableEvent event; - - // This callback function will be called when there is a new image available - // for in the image reader's queue. - static void CallbackSignal(void* context, AImageReader* reader) { - (reinterpret_cast<FrameAvailableEvent_ImageReader*>(context))->Signal(); - } - - private: - friend class RefCountedThreadSafe<FrameAvailableEvent_ImageReader>; - - ~FrameAvailableEvent_ImageReader() = default; -}; - class ImageReaderGLOwner::ScopedHardwareBufferImpl : public base::android::ScopedHardwareBufferFenceSync { public: @@ -105,8 +82,7 @@ std::move(texture)), loader_(base::android::AndroidImageReader::GetInstance()), context_(gl::GLContext::GetCurrent()), - surface_(gl::GLSurface::GetCurrent()), - frame_available_event_(new FrameAvailableEvent_ImageReader()) { + surface_(gl::GLSurface::GetCurrent()) { DCHECK(context_); DCHECK(surface_); @@ -152,9 +128,11 @@ // Create a new Image Listner. listener_ = std::make_unique<AImageReader_ImageListener>(); - listener_->context = reinterpret_cast<void*>(frame_available_event_.get()); - listener_->onImageAvailable = - &FrameAvailableEvent_ImageReader::CallbackSignal; + + // Passing |this| is safe here since we stop listening to new images in the + // destructor and set the ImageListener to null. + listener_->context = reinterpret_cast<void*>(this); + listener_->onImageAvailable = &ImageReaderGLOwner::OnFrameAvailable; // Set the onImageAvailable listener of this image reader. if (loader_.AImageReader_setImageListener(image_reader_, listener_.get()) != @@ -203,6 +181,11 @@ current_image_ref_.reset(); } +void ImageReaderGLOwner::SetFrameAvailableCallback( + const base::RepeatingClosure& frame_available_cb) { + frame_available_cb_ = std::move(frame_available_cb); +} + gl::ScopedJavaSurface ImageReaderGLOwner::CreateJavaSurface() const { // If we've already lost the texture, then do nothing. if (!image_reader_) { @@ -382,55 +365,14 @@ return surface_.get(); } -void ImageReaderGLOwner::SetReleaseTimeToNow() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - release_time_ = base::TimeTicks::Now(); -} +// This callback function will be called when there is a new image available +// for in the image reader's queue. +void ImageReaderGLOwner::OnFrameAvailable(void* context, AImageReader* reader) { + ImageReaderGLOwner* image_reader_ptr = + reinterpret_cast<ImageReaderGLOwner*>(context); -void ImageReaderGLOwner::IgnorePendingRelease() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - release_time_ = base::TimeTicks(); -} - -bool ImageReaderGLOwner::IsExpectingFrameAvailable() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - return !release_time_.is_null(); -} - -void ImageReaderGLOwner::WaitForFrameAvailable() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!release_time_.is_null()); - - // 5msec covers >99.9% of cases, so just wait for up to that much before - // giving up. If an error occurs, we might not ever get a notification. - const base::TimeDelta max_wait = base::TimeDelta::FromMilliseconds(5); - const base::TimeTicks call_time = base::TimeTicks::Now(); - const base::TimeDelta elapsed = call_time - release_time_; - const base::TimeDelta remaining = max_wait - elapsed; - release_time_ = base::TimeTicks(); - bool timed_out = false; - - if (remaining <= base::TimeDelta()) { - if (!frame_available_event_->event.IsSignaled()) { - DVLOG(1) << "Deferred WaitForFrameAvailable() timed out, elapsed: " - << elapsed.InMillisecondsF() << "ms"; - timed_out = true; - } - } else { - DCHECK_LE(remaining, max_wait); - SCOPED_UMA_HISTOGRAM_TIMER( - "Media.CodecImage.ImageReaderGLOwner.WaitTimeForFrame"); - if (!frame_available_event_->event.TimedWait(remaining)) { - DVLOG(1) << "WaitForFrameAvailable() timed out, elapsed: " - << elapsed.InMillisecondsF() - << "ms, additionally waited: " << remaining.InMillisecondsF() - << "ms, total: " << (elapsed + remaining).InMillisecondsF() - << "ms"; - timed_out = true; - } - } - UMA_HISTOGRAM_BOOLEAN("Media.CodecImage.ImageReaderGLOwner.FrameTimedOut", - timed_out); + // It is safe to run this callback on any thread. + image_reader_ptr->frame_available_cb_.Run(); } ImageReaderGLOwner::ImageRef::ImageRef() = default;
diff --git a/media/gpu/android/image_reader_gl_owner.h b/media/gpu/android/image_reader_gl_owner.h index 8d9fd9c..397f45a 100644 --- a/media/gpu/android/image_reader_gl_owner.h +++ b/media/gpu/android/image_reader_gl_owner.h
@@ -21,8 +21,6 @@ namespace media { -struct FrameAvailableEvent_ImageReader; - // This class wraps the AImageReader usage and is used to create a GL texture // using the current platform GL context and returns a new ImageReaderGLOwner // attached to it. The surface handle of the AImageReader is attached to @@ -33,15 +31,13 @@ public: gl::GLContext* GetContext() const override; gl::GLSurface* GetSurface() const override; + void SetFrameAvailableCallback( + const base::RepeatingClosure& frame_available_cb) override; gl::ScopedJavaSurface CreateJavaSurface() const override; void UpdateTexImage() override; void EnsureTexImageBound() override; void GetTransformMatrix(float mtx[16]) override; void ReleaseBackBuffers() override; - void SetReleaseTimeToNow() override; - void IgnorePendingRelease() override; - bool IsExpectingFrameAvailable() override; - void WaitForFrameAvailable() override; std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> GetAHardwareBuffer() override; @@ -88,6 +84,8 @@ void RegisterRefOnImage(AImage* image); void ReleaseRefOnImage(AImage* image, base::ScopedFD fence_fd); + static void OnFrameAvailable(void* context, AImageReader* reader); + // AImageReader instance AImageReader* image_reader_; @@ -120,15 +118,15 @@ // The context and surface that were used to create |texture_id_|. scoped_refptr<gl::GLContext> context_; scoped_refptr<gl::GLSurface> surface_; - - // When SetReleaseTimeToNow() was last called. i.e., when the last - // codec buffer was released to this surface. Or null if - // IgnorePendingRelease() or WaitForFrameAvailable() have been called since. - base::TimeTicks release_time_; - scoped_refptr<FrameAvailableEvent_ImageReader> frame_available_event_; int32_t max_images_ = 0; + // Frame available callback handling. ImageListener registered with + // AImageReader is notified when there is a new frame available which + // in turns runs the callback function. + base::RepeatingClosure frame_available_cb_; + THREAD_CHECKER(thread_checker_); + DISALLOW_COPY_AND_ASSIGN(ImageReaderGLOwner); };
diff --git a/media/gpu/android/mock_texture_owner.cc b/media/gpu/android/mock_texture_owner.cc index 037ccd2..ff7a914 100644 --- a/media/gpu/android/mock_texture_owner.cc +++ b/media/gpu/android/mock_texture_owner.cc
@@ -19,21 +19,10 @@ std::make_unique<MockAbstractTexture>(fake_texture_id)), fake_context(fake_context), fake_surface(fake_surface), - expecting_frame_available(false), expect_update_tex_image(!binds_texture_on_update) { ON_CALL(*this, GetTextureId()).WillByDefault(Return(fake_texture_id)); ON_CALL(*this, GetContext()).WillByDefault(Return(fake_context)); ON_CALL(*this, GetSurface()).WillByDefault(Return(fake_surface)); - ON_CALL(*this, SetReleaseTimeToNow()) - .WillByDefault(Invoke(this, &MockTextureOwner::FakeSetReleaseTimeToNow)); - ON_CALL(*this, IgnorePendingRelease()) - .WillByDefault(Invoke(this, &MockTextureOwner::FakeIgnorePendingRelease)); - ON_CALL(*this, IsExpectingFrameAvailable()) - .WillByDefault( - Invoke(this, &MockTextureOwner::FakeIsExpectingFrameAvailable)); - ON_CALL(*this, WaitForFrameAvailable()) - .WillByDefault( - Invoke(this, &MockTextureOwner::FakeWaitForFrameAvailable)); ON_CALL(*this, EnsureTexImageBound()).WillByDefault(Invoke([this] { CHECK(expect_update_tex_image); })); @@ -44,4 +33,25 @@ ClearAbstractTexture(); } +MockCodecBufferWaitCoordinator::MockCodecBufferWaitCoordinator( + scoped_refptr<NiceMock<MockTextureOwner>> texture_owner) + : CodecBufferWaitCoordinator(texture_owner), + mock_texture_owner(std::move(texture_owner)), + expecting_frame_available(false) { + ON_CALL(*this, texture_owner()).WillByDefault(Return(mock_texture_owner)); + + ON_CALL(*this, SetReleaseTimeToNow()) + .WillByDefault(Invoke( + this, &MockCodecBufferWaitCoordinator::FakeSetReleaseTimeToNow)); + ON_CALL(*this, IsExpectingFrameAvailable()) + .WillByDefault(Invoke( + this, + &MockCodecBufferWaitCoordinator::FakeIsExpectingFrameAvailable)); + ON_CALL(*this, WaitForFrameAvailable()) + .WillByDefault(Invoke( + this, &MockCodecBufferWaitCoordinator::FakeWaitForFrameAvailable)); +} + +MockCodecBufferWaitCoordinator::~MockCodecBufferWaitCoordinator() = default; + } // namespace media
diff --git a/media/gpu/android/mock_texture_owner.h b/media/gpu/android/mock_texture_owner.h index c5f06c0b..26109c3 100644 --- a/media/gpu/android/mock_texture_owner.h +++ b/media/gpu/android/mock_texture_owner.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/android/scoped_hardware_buffer_fence_sync.h" +#include "media/gpu/android/codec_buffer_wait_coordinator.h" #include "media/gpu/android/texture_owner.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -15,6 +16,8 @@ #include "ui/gl/gl_context.h" #include "ui/gl/gl_surface.h" +using testing::NiceMock; + namespace media { // This is a mock with a small amount of fake functionality too. @@ -33,11 +36,8 @@ MOCK_METHOD0(EnsureTexImageBound, void()); MOCK_METHOD1(GetTransformMatrix, void(float mtx[16])); MOCK_METHOD0(ReleaseBackBuffers, void()); - MOCK_METHOD0(SetReleaseTimeToNow, void()); - MOCK_METHOD0(IgnorePendingRelease, void()); - MOCK_METHOD0(IsExpectingFrameAvailable, bool()); - MOCK_METHOD0(WaitForFrameAvailable, void()); MOCK_METHOD1(OnTextureDestroyed, void(gpu::gles2::AbstractTexture*)); + MOCK_METHOD1(SetFrameAvailableCallback, void(const base::RepeatingClosure&)); std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> GetAHardwareBuffer() override { @@ -45,15 +45,8 @@ return nullptr; } - // Fake implementations that the mocks will call by default. - void FakeSetReleaseTimeToNow() { expecting_frame_available = true; } - void FakeIgnorePendingRelease() { expecting_frame_available = false; } - bool FakeIsExpectingFrameAvailable() { return expecting_frame_available; } - void FakeWaitForFrameAvailable() { expecting_frame_available = false; } - gl::GLContext* fake_context; gl::GLSurface* fake_surface; - bool expecting_frame_available; int get_a_hardware_buffer_count = 0; bool expect_update_tex_image; @@ -61,6 +54,30 @@ ~MockTextureOwner(); }; +// Mock class with mostly fake functions. +class MockCodecBufferWaitCoordinator : public CodecBufferWaitCoordinator { + public: + MockCodecBufferWaitCoordinator( + scoped_refptr<NiceMock<MockTextureOwner>> texture_owner); + + MOCK_CONST_METHOD0(texture_owner, + scoped_refptr<NiceMock<MockTextureOwner>>()); + MOCK_METHOD0(SetReleaseTimeToNow, void()); + MOCK_METHOD0(IsExpectingFrameAvailable, bool()); + MOCK_METHOD0(WaitForFrameAvailable, void()); + + // Fake implementations that the mocks will call by default. + void FakeSetReleaseTimeToNow() { expecting_frame_available = true; } + bool FakeIsExpectingFrameAvailable() { return expecting_frame_available; } + void FakeWaitForFrameAvailable() { expecting_frame_available = false; } + + scoped_refptr<NiceMock<MockTextureOwner>> mock_texture_owner; + bool expecting_frame_available; + + protected: + ~MockCodecBufferWaitCoordinator(); +}; + } // namespace media #endif // MEDIA_GPU_ANDROID_MOCK_TEXTURE_OWNER_H_
diff --git a/media/gpu/android/surface_texture_gl_owner.cc b/media/gpu/android/surface_texture_gl_owner.cc index f19f2ad4..83daac2 100644 --- a/media/gpu/android/surface_texture_gl_owner.cc +++ b/media/gpu/android/surface_texture_gl_owner.cc
@@ -19,33 +19,14 @@ namespace media { -// FrameAvailableEvent is a RefCounted wrapper for a WaitableEvent -// (it's not possible to put one in RefCountedData). -// This lets us safely signal an event on any thread. -struct FrameAvailableEvent - : public base::RefCountedThreadSafe<FrameAvailableEvent> { - FrameAvailableEvent() - : event(base::WaitableEvent::ResetPolicy::AUTOMATIC, - base::WaitableEvent::InitialState::NOT_SIGNALED) {} - void Signal() { event.Signal(); } - base::WaitableEvent event; - - private: - friend class RefCountedThreadSafe<FrameAvailableEvent>; - ~FrameAvailableEvent() = default; -}; - SurfaceTextureGLOwner::SurfaceTextureGLOwner( std::unique_ptr<gpu::gles2::AbstractTexture> texture) : TextureOwner(true /*binds_texture_on_update */, std::move(texture)), surface_texture_(gl::SurfaceTexture::Create(GetTextureId())), context_(gl::GLContext::GetCurrent()), - surface_(gl::GLSurface::GetCurrent()), - frame_available_event_(new FrameAvailableEvent()) { + surface_(gl::GLSurface::GetCurrent()) { DCHECK(context_); DCHECK(surface_); - surface_texture_->SetFrameAvailableCallbackOnAnyThread(base::BindRepeating( - &FrameAvailableEvent::Signal, frame_available_event_)); } SurfaceTextureGLOwner::~SurfaceTextureGLOwner() { @@ -63,6 +44,13 @@ surface_texture_ = nullptr; } +void SurfaceTextureGLOwner::SetFrameAvailableCallback( + const base::RepeatingClosure& frame_available_cb) { + // Setting the callback to be run from any thread since |frame_available_cb| + // is thread safe. + surface_texture_->SetFrameAvailableCallbackOnAnyThread(frame_available_cb); +} + gl::ScopedJavaSurface SurfaceTextureGLOwner::CreateJavaSurface() const { // |surface_texture_| might be null, but that's okay. return gl::ScopedJavaSurface(surface_texture_.get()); @@ -104,57 +92,6 @@ return surface_.get(); } -void SurfaceTextureGLOwner::SetReleaseTimeToNow() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - release_time_ = base::TimeTicks::Now(); -} - -void SurfaceTextureGLOwner::IgnorePendingRelease() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - release_time_ = base::TimeTicks(); -} - -bool SurfaceTextureGLOwner::IsExpectingFrameAvailable() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - return !release_time_.is_null(); -} - -void SurfaceTextureGLOwner::WaitForFrameAvailable() { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(!release_time_.is_null()); - - // 5msec covers >99.9% of cases, so just wait for up to that much before - // giving up. If an error occurs, we might not ever get a notification. - const base::TimeDelta max_wait = base::TimeDelta::FromMilliseconds(5); - const base::TimeTicks call_time = base::TimeTicks::Now(); - const base::TimeDelta elapsed = call_time - release_time_; - const base::TimeDelta remaining = max_wait - elapsed; - release_time_ = base::TimeTicks(); - bool timed_out = false; - - if (remaining <= base::TimeDelta()) { - if (!frame_available_event_->event.IsSignaled()) { - DVLOG(1) << "Deferred WaitForFrameAvailable() timed out, elapsed: " - << elapsed.InMillisecondsF() << "ms"; - timed_out = true; - } - } else { - DCHECK_LE(remaining, max_wait); - SCOPED_UMA_HISTOGRAM_TIMER( - "Media.CodecImage.SurfaceTextureGLOwner.WaitTimeForFrame"); - if (!frame_available_event_->event.TimedWait(remaining)) { - DVLOG(1) << "WaitForFrameAvailable() timed out, elapsed: " - << elapsed.InMillisecondsF() - << "ms, additionally waited: " << remaining.InMillisecondsF() - << "ms, total: " << (elapsed + remaining).InMillisecondsF() - << "ms"; - timed_out = true; - } - } - UMA_HISTOGRAM_BOOLEAN("Media.CodecImage.SurfaceTextureGLOwner.FrameTimedOut", - timed_out); -} - std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> SurfaceTextureGLOwner::GetAHardwareBuffer() { NOTREACHED() << "Don't use AHardwareBuffers with SurfaceTextureGLOwner";
diff --git a/media/gpu/android/surface_texture_gl_owner.h b/media/gpu/android/surface_texture_gl_owner.h index f2634aaac..b3f5b716 100644 --- a/media/gpu/android/surface_texture_gl_owner.h +++ b/media/gpu/android/surface_texture_gl_owner.h
@@ -20,8 +20,6 @@ namespace media { -struct FrameAvailableEvent; - // This class wraps the Surface Texture usage. It is used to create a surface // texture attached to a new texture of the current platform GL context. The // surface handle of the SurfaceTexture is attached to the decoded media @@ -32,15 +30,13 @@ public: gl::GLContext* GetContext() const override; gl::GLSurface* GetSurface() const override; + void SetFrameAvailableCallback( + const base::RepeatingClosure& frame_available_cb) override; gl::ScopedJavaSurface CreateJavaSurface() const override; void UpdateTexImage() override; void EnsureTexImageBound() override; void GetTransformMatrix(float mtx[16]) override; void ReleaseBackBuffers() override; - void SetReleaseTimeToNow() override; - void IgnorePendingRelease() override; - bool IsExpectingFrameAvailable() override; - void WaitForFrameAvailable() override; std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> GetAHardwareBuffer() override; @@ -57,11 +53,6 @@ // The context and surface that were used to create |surface_texture_|. scoped_refptr<gl::GLContext> context_; scoped_refptr<gl::GLSurface> surface_; - // When SetReleaseTimeToNow() was last called. i.e., when the last - // codec buffer was released to this surface. Or null if - // IgnorePendingRelease() or WaitForFrameAvailable() have been called since. - base::TimeTicks release_time_; - scoped_refptr<FrameAvailableEvent> frame_available_event_; THREAD_CHECKER(thread_checker_); DISALLOW_COPY_AND_ASSIGN(SurfaceTextureGLOwner);
diff --git a/media/gpu/android/texture_owner.h b/media/gpu/android/texture_owner.h index af807f0..f9c4a52 100644 --- a/media/gpu/android/texture_owner.h +++ b/media/gpu/android/texture_owner.h
@@ -36,9 +36,10 @@ // A Texture wrapper interface that creates and maintains ownership of the // attached GL or Vulkan texture. The texture is destroyed with the object. // It should only be accessed on the thread it was created on, with the -// exception of CreateJavaSurface(), which can be called on any thread. It's -// safe to keep and drop refptrs to it on any thread; it will be automatically -// destructed on the thread it was constructed on. +// exception of CreateJavaSurface() and SetFrameAvailableCallback(), which can +// be called on any thread. It's safe to keep and drop refptrs to it on any +// thread; it will be automatically destructed on the thread it was constructed +// on. class MEDIA_GPU_EXPORT TextureOwner : public base::RefCountedDeleteOnSequence<TextureOwner> { public: @@ -88,25 +89,6 @@ virtual void GetTransformMatrix(float mtx[16]) = 0; virtual void ReleaseBackBuffers() = 0; - // Sets the expectation of onFrameAVailable for a new frame because a buffer - // was just released to this surface. - virtual void SetReleaseTimeToNow() = 0; - - // Ignores a pending release that was previously indicated with - // SetReleaseTimeToNow(). TODO(watk): This doesn't seem necessary. It - // actually may be detrimental because the next time we release a buffer we - // may confuse its onFrameAvailable with the one we're ignoring. - virtual void IgnorePendingRelease() = 0; - - // Whether we're expecting onFrameAvailable. True when SetReleaseTimeToNow() - // was called but neither IgnorePendingRelease() nor WaitForFrameAvailable() - // have been called since. - virtual bool IsExpectingFrameAvailable() = 0; - - // Waits for onFrameAvailable until it's been 5ms since the buffer was - // released. This must only be called if IsExpectingFrameAvailable(). - virtual void WaitForFrameAvailable() = 0; - // Retrieves the AHardwareBuffer from the latest available image data. // Note that the object must be used and destroyed on the same thread the // TextureOwner is bound to. @@ -118,12 +100,18 @@ protected: friend class base::RefCountedDeleteOnSequence<TextureOwner>; friend class base::DeleteHelper<TextureOwner>; + friend class CodecBufferWaitCoordinator; // |texture| is the texture that we'll own. TextureOwner(bool binds_texture_on_update, std::unique_ptr<gpu::gles2::AbstractTexture> texture); virtual ~TextureOwner(); + // Set the callback function to run when a new frame is available. + // |frame_available_cb| is thread safe and can be called on any thread. + virtual void SetFrameAvailableCallback( + const base::RepeatingClosure& frame_available_cb) = 0; + // Drop |texture_| immediately. Will call OnTextureDestroyed immediately if // it hasn't been called before (e.g., due to lost context). // Subclasses must call this before they complete destruction, else
diff --git a/media/gpu/android/video_frame_factory.h b/media/gpu/android/video_frame_factory.h index ee5e80a..46c3dbd 100644 --- a/media/gpu/android/video_frame_factory.h +++ b/media/gpu/android/video_frame_factory.h
@@ -19,7 +19,6 @@ class CodecOutputBuffer; class CodecSurfaceBundle; -class TextureOwner; class VideoFrame; // VideoFrameFactory creates CodecOutputBuffer backed VideoFrames. Not thread
diff --git a/media/gpu/android/video_frame_factory_impl.cc b/media/gpu/android/video_frame_factory_impl.cc index ca472ea..079ffbab 100644 --- a/media/gpu/android/video_frame_factory_impl.cc +++ b/media/gpu/android/video_frame_factory_impl.cc
@@ -109,15 +109,18 @@ scoped_refptr<CodecImageGroup> image_group; if (!surface_bundle) { // Clear everything, just so we're not holding a reference. - texture_owner_ = nullptr; + codec_buffer_wait_coordinator_ = nullptr; } else { // If |surface_bundle| is using a TextureOwner, then get it. Note that the // only reason we need this is for legacy mailbox support; we send it to // the SharedImageVideoProvider so that (eventually) it can get the service // id from the owner for the legacy mailbox texture. Otherwise, this would // be a lot simpler. - texture_owner_ = - surface_bundle->overlay() ? nullptr : surface_bundle->texture_owner(); + codec_buffer_wait_coordinator_ = + surface_bundle->overlay() + ? nullptr + : base::MakeRefCounted<CodecBufferWaitCoordinator>( + surface_bundle->texture_owner()); // TODO(liberato): When we enable pooling, do we need to clear the pool // here because the CodecImageGroup has changed? It's unclear, since the @@ -155,12 +158,13 @@ auto image_ready_cb = base::BindOnce( &VideoFrameFactoryImpl::OnImageReady, weak_factory_.GetWeakPtr(), std::move(output_cb), timestamp, coded_size, natural_size, - std::move(output_buffer), texture_owner_, std::move(promotion_hint_cb), - pixel_format, overlay_mode_, enable_threaded_texture_mailboxes_, - gpu_task_runner_); + std::move(output_buffer), codec_buffer_wait_coordinator_, + std::move(promotion_hint_cb), pixel_format, overlay_mode_, + enable_threaded_texture_mailboxes_, gpu_task_runner_); - image_provider_->RequestImage(std::move(image_ready_cb), spec, - texture_owner_); + image_provider_->RequestImage( + std::move(image_ready_cb), spec, + codec_buffer_wait_coordinator_->texture_owner()); } // static @@ -171,7 +175,7 @@ gfx::Size coded_size, gfx::Size natural_size, std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator, PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb, VideoPixelFormat pixel_format, OverlayMode overlay_mode, @@ -188,7 +192,8 @@ // used at this point. Alternatively, we could post it, or hand it off to the // MaybeRenderEarlyManager to save a post. record.codec_image_holder->codec_image_raw()->Initialize( - std::move(output_buffer), texture_owner, std::move(promotion_hint_cb)); + std::move(output_buffer), codec_buffer_wait_coordinator, + std::move(promotion_hint_cb)); // Send the CodecImage (via holder, since we can't touch the refcount here) to // the MaybeRenderEarlyManager. @@ -236,17 +241,17 @@ const bool wants_promotion_hints = overlay_mode == OverlayMode::kRequestPromotionHints; - // Remember that we can't access |texture_owner|, but we can check if we have - // one here. + // Remember that we can't access |codec_buffer_wait_coordinator|, but we can + // check if we have one here. bool allow_overlay = false; if (is_surface_control) { - DCHECK(texture_owner); + DCHECK(codec_buffer_wait_coordinator); allow_overlay = true; } else { // We unconditionally mark the picture as overlayable, even if - // |!texture_owner|, if we want to get hints. It's required, else we won't - // get hints. - allow_overlay = !texture_owner || wants_promotion_hints; + // |!codec_buffer_wait_coordinator|, if we want to get hints. It's + // required, else we won't get hints. + allow_overlay = !codec_buffer_wait_coordinator || wants_promotion_hints; } frame->metadata()->SetBoolean(VideoFrameMetadata::ALLOW_OVERLAY, @@ -254,7 +259,7 @@ frame->metadata()->SetBoolean(VideoFrameMetadata::WANTS_PROMOTION_HINT, wants_promotion_hints); frame->metadata()->SetBoolean(VideoFrameMetadata::TEXTURE_OWNER, - !!texture_owner); + !!codec_buffer_wait_coordinator); frame->SetReleaseMailboxCB(std::move(record.release_cb));
diff --git a/media/gpu/android/video_frame_factory_impl.h b/media/gpu/android/video_frame_factory_impl.h index 21a04ba..e7845e6 100644 --- a/media/gpu/android/video_frame_factory_impl.h +++ b/media/gpu/android/video_frame_factory_impl.h
@@ -12,11 +12,11 @@ #include "base/single_thread_task_runner.h" #include "gpu/config/gpu_preferences.h" #include "media/base/video_frame.h" +#include "media/gpu/android/codec_buffer_wait_coordinator.h" #include "media/gpu/android/codec_image.h" #include "media/gpu/android/codec_wrapper.h" #include "media/gpu/android/maybe_render_early_manager.h" #include "media/gpu/android/shared_image_video_provider.h" -#include "media/gpu/android/surface_texture_gl_owner.h" #include "media/gpu/android/video_frame_factory.h" #include "media/gpu/media_gpu_export.h" #include "ui/gl/gl_bindings.h" @@ -58,6 +58,12 @@ OnceOutputCb output_cb) override; void RunAfterPendingVideoFrames(base::OnceClosure closure) override; + // This should be only used for testing. + void SetCodecBufferWaitCorrdinatorForTesting( + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator) { + codec_buffer_wait_coordinator_ = std::move(codec_buffer_wait_coordinator); + } + private: // ImageReadyCB that will construct a VideoFrame, and forward it to // |output_cb| if construction succeeds. This is static for two reasons. @@ -77,7 +83,7 @@ gfx::Size coded_size, gfx::Size natural_size, std::unique_ptr<CodecOutputBuffer> output_buffer, - scoped_refptr<TextureOwner> texture_owner, + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator, PromotionHintAggregator::NotifyPromotionHintCB promotion_hint_cb, VideoPixelFormat pixel_format, OverlayMode overlay_mode, @@ -90,8 +96,8 @@ std::unique_ptr<SharedImageVideoProvider> image_provider_; scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_; - // The texture owner that video frames should use, or nullptr. - scoped_refptr<TextureOwner> texture_owner_; + // The CodecBufferWaitCoordintor that video frames should use, or nullptr. + scoped_refptr<CodecBufferWaitCoordinator> codec_buffer_wait_coordinator_; OverlayMode overlay_mode_ = OverlayMode::kDontRequestPromotionHints;
diff --git a/media/gpu/android/video_frame_factory_impl_unittest.cc b/media/gpu/android/video_frame_factory_impl_unittest.cc index 9805d20..322d310c 100644 --- a/media/gpu/android/video_frame_factory_impl_unittest.cc +++ b/media/gpu/android/video_frame_factory_impl_unittest.cc
@@ -15,6 +15,7 @@ #include "media/base/limits.h" #include "media/gpu/android/maybe_render_early_manager.h" #include "media/gpu/android/mock_codec_image.h" +#include "media/gpu/android/mock_texture_owner.h" #include "media/gpu/android/shared_image_video_provider.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -78,6 +79,15 @@ impl_ = std::make_unique<VideoFrameFactoryImpl>( task_runner_, gpu_preferences_, std::move(image_provider), std::move(mre_manager)); + auto texture_owner = base::MakeRefCounted<NiceMock<MockTextureOwner>>( + 0, nullptr, nullptr, true); + auto codec_buffer_wait_coordinator = + base::MakeRefCounted<CodecBufferWaitCoordinator>( + std::move(texture_owner)); + + // Provide a non-null |codec_buffer_wait_coordinator| to |impl_|. + impl_->SetCodecBufferWaitCorrdinatorForTesting( + std::move(codec_buffer_wait_coordinator)); } ~VideoFrameFactoryImplTest() override = default; @@ -140,8 +150,11 @@ TEST_F(VideoFrameFactoryImplTest, SetSurfaceBundleForwardsToMaybeRenderEarlyManager) { // Sending a non-null CodecSurfaceBundle should forward it to |mre_manager|. + // Also provide a non-null TextureOwner to it. scoped_refptr<CodecSurfaceBundle> surface_bundle = - base::MakeRefCounted<CodecSurfaceBundle>(); + base::MakeRefCounted<CodecSurfaceBundle>( + base::MakeRefCounted<NiceMock<MockTextureOwner>>(0, nullptr, nullptr, + true)); EXPECT_CALL(*mre_manager_raw_, SetSurfaceBundle(surface_bundle)); impl_->SetSurfaceBundle(surface_bundle); base::RunLoop().RunUntilIdle();
diff --git a/mojo/core/platform_handle_utils.cc b/mojo/core/platform_handle_utils.cc index edd0cff..f265dedc 100644 --- a/mojo/core/platform_handle_utils.cc +++ b/mojo/core/platform_handle_utils.cc
@@ -54,7 +54,7 @@ return zx::vmo(handle.TakeHandle()); #elif defined(OS_MACOSX) && !defined(OS_IOS) DCHECK(!readonly_handle.is_valid()); - return handle.TakeMachPort(); + return handle.TakeMachSendRight(); #elif defined(OS_ANDROID) DCHECK(!readonly_handle.is_valid()); return handle.TakeFD();
diff --git a/mojo/public/cpp/platform/platform_handle.h b/mojo/public/cpp/platform/platform_handle.h index a6ac190..07a49f4a 100644 --- a/mojo/public/cpp/platform/platform_handle.h +++ b/mojo/public/cpp/platform/platform_handle.h
@@ -46,8 +46,7 @@ #if defined(OS_WIN) || defined(OS_FUCHSIA) kHandle, #elif defined(OS_MACOSX) && !defined(OS_IOS) - kMachPort, - kMachSend = kMachPort, + kMachSend, kMachReceive, #endif #if defined(OS_POSIX) || defined(OS_FUCHSIA) @@ -163,17 +162,6 @@ mach_port_t ReleaseMachReceiveRight() WARN_UNUSED_RESULT { return TakeMachReceiveRight().release(); } - - // The following Mach port methods are deprecated. Use the ones above - // instead. - bool is_mach_port() const { return type_ == Type::kMachPort; } - const base::mac::ScopedMachSendRight& GetMachPort() const { - return GetMachSendRight(); - } - base::mac::ScopedMachSendRight TakeMachPort() { return TakeMachSendRight(); } - mach_port_t ReleaseMachPort() WARN_UNUSED_RESULT { - return ReleaseMachSendRight(); - } #elif defined(OS_POSIX) bool is_valid() const { return is_valid_fd(); } #else
diff --git a/mojo/public/cpp/platform/tests/platform_handle_unittest.cc b/mojo/public/cpp/platform/tests/platform_handle_unittest.cc index c3232e2..8ddd9d89c 100644 --- a/mojo/public/cpp/platform/tests/platform_handle_unittest.cc +++ b/mojo/public/cpp/platform/tests/platform_handle_unittest.cc
@@ -164,7 +164,7 @@ #if defined(OS_FUCHSIA) handle.GetHandle().get() #elif defined(OS_MACOSX) && !defined(OS_IOS) - handle.GetMachPort().get() + handle.GetMachSendRight().get() #endif ); auto generic_region = base::subtle::PlatformSharedMemoryRegion::Take(
diff --git a/net/cert/cert_verify_proc_builtin.cc b/net/cert/cert_verify_proc_builtin.cc index b5ef8e7..3c9519d 100644 --- a/net/cert/cert_verify_proc_builtin.cc +++ b/net/cert/cert_verify_proc_builtin.cc
@@ -439,7 +439,7 @@ if (!der::EncodeTimeAsGeneralizedTime(verification_time, &der_verification_time)) { // This shouldn't be possible. - result->Clear(); + *result = CertPathBuilder::Result(); return; }
diff --git a/net/cert/internal/path_builder.cc b/net/cert/internal/path_builder.cc index c39f67c..fbb6f99 100644 --- a/net/cert/internal/path_builder.cc +++ b/net/cert/internal/path_builder.cc
@@ -507,7 +507,9 @@ } CertPathBuilder::Result::Result() = default; +CertPathBuilder::Result::Result(Result&&) = default; CertPathBuilder::Result::~Result() = default; +CertPathBuilder::Result& CertPathBuilder::Result::operator=(Result&&) = default; bool CertPathBuilder::Result::HasValidPath() const { return GetBestValidPath() != nullptr; @@ -534,11 +536,6 @@ return paths[best_result_index].get(); } -void CertPathBuilder::Result::Clear() { - paths.clear(); - best_result_index = 0; -} - CertPathBuilder::CertPathBuilder( scoped_refptr<ParsedCertificate> cert, TrustStore* trust_store, @@ -560,7 +557,7 @@ initial_any_policy_inhibit_(initial_any_policy_inhibit), out_result_(result) { DCHECK(delegate); - result->Clear(); + *result = Result(); // The TrustStore also implements the CertIssuerSource interface. AddCertIssuerSource(trust_store); }
diff --git a/net/cert/internal/path_builder.h b/net/cert/internal/path_builder.h index 5562c4e..a48058e5 100644 --- a/net/cert/internal/path_builder.h +++ b/net/cert/internal/path_builder.h
@@ -106,7 +106,9 @@ // were attempted. struct NET_EXPORT Result { Result(); + Result(Result&&); ~Result(); + Result& operator=(Result&&); // Returns true if there was a valid path. bool HasValidPath() const; @@ -118,9 +120,6 @@ // Returns the best CertPathBuilderResultPath or nullptr if there was none. const CertPathBuilderResultPath* GetBestPathPossiblyInvalid() const; - // Resets to the initial value. - void Clear(); - // List of paths that were attempted and the result for each. std::vector<std::unique_ptr<CertPathBuilderResultPath>> paths;
diff --git a/pdf/BUILD.gn b/pdf/BUILD.gn index 7908815..c6989b1 100644 --- a/pdf/BUILD.gn +++ b/pdf/BUILD.gn
@@ -107,6 +107,8 @@ "pdfium/pdfium_mem_buffer_file_write.h", "pdfium/pdfium_page.cc", "pdfium/pdfium_page.h", + "pdfium/pdfium_permissions.cc", + "pdfium/pdfium_permissions.h", "pdfium/pdfium_print.cc", "pdfium/pdfium_print.h", "pdfium/pdfium_range.cc",
diff --git a/pdf/pdfium/pdfium_engine.cc b/pdf/pdfium/pdfium_engine.cc index 93329a1..a6c5874 100644 --- a/pdf/pdfium/pdfium_engine.cc +++ b/pdf/pdfium/pdfium_engine.cc
@@ -34,6 +34,7 @@ #include "pdf/pdfium/pdfium_document.h" #include "pdf/pdfium/pdfium_mem_buffer_file_read.h" #include "pdf/pdfium/pdfium_mem_buffer_file_write.h" +#include "pdf/pdfium/pdfium_permissions.h" #include "pdf/pdfium/pdfium_unsupported_features.h" #include "pdf/url_loader_wrapper_impl.h" #include "ppapi/cpp/instance.h" @@ -110,13 +111,6 @@ constexpr bool kViewerImplementedPanning = true; #endif -// See Table 3.20 in -// http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf -constexpr uint32_t kPDFPermissionPrintLowQualityMask = 1 << 2; -constexpr uint32_t kPDFPermissionPrintHighQualityMask = 1 << 11; -constexpr uint32_t kPDFPermissionCopyMask = 1 << 4; -constexpr uint32_t kPDFPermissionCopyAccessibleMask = 1 << 9; - constexpr int32_t kLoadingTextVerticalOffset = 50; // The maximum amount of time we'll spend doing a paint before we give back @@ -1998,35 +1992,10 @@ } bool PDFiumEngine::HasPermission(DocumentPermission permission) const { - // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater, - // the operations to which user access can be controlled are as follows: ..." - // - // Thus for revision numbers less than 2, permissions are ignored and this - // always returns true. - if (permissions_handler_revision_ < 2) + // No |permissions_| means no restrictions. + if (!permissions_) return true; - - // Handle high quality printing permission separately for security handler - // revision 3+. See table 3.20 in the PDF 1.7 spec. - if (permission == PERMISSION_PRINT_HIGH_QUALITY && - permissions_handler_revision_ >= 3) { - return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0 && - (permissions_ & kPDFPermissionPrintHighQualityMask) != 0; - } - - switch (permission) { - case PERMISSION_COPY: - return (permissions_ & kPDFPermissionCopyMask) != 0; - case PERMISSION_COPY_ACCESSIBLE: - return (permissions_ & kPDFPermissionCopyAccessibleMask) != 0; - case PERMISSION_PRINT_LOW_QUALITY: - case PERMISSION_PRINT_HIGH_QUALITY: - // With security handler revision 2 rules, check the same bit for high - // and low quality. See table 3.20 in the PDF 1.7 spec. - return (permissions_ & kPDFPermissionPrintLowQualityMask) != 0; - default: - return true; - } + return permissions_->HasPermission(permission); } void PDFiumEngine::SelectAll() { @@ -2396,8 +2365,7 @@ if (FPDFDoc_GetPageMode(doc()) == PAGEMODE_USEOUTLINES) client_->DocumentHasUnsupportedFeature("Bookmarks"); - permissions_ = FPDF_GetDocPermissions(doc()); - permissions_handler_revision_ = FPDF_GetSecurityHandlerRevision(doc()); + permissions_ = std::make_unique<PDFiumPermissions>(doc()); LoadBody(); @@ -2424,6 +2392,16 @@ } } +void PDFiumEngine::LoadPagesInSingleView(std::vector<pp::Rect> page_rects, + bool reload) { + for (size_t i = 0; i < page_rects.size(); ++i) { + // Center pages relative to the entire document. + page_rects[i].set_x((layout_.size().width() - page_rects[i].width()) / 2); + InsetPage(i, page_rects.size(), /*multiplier=*/1, &page_rects[i]); + AppendPageRectToPages(page_rects[i], i, reload); + } +} + void PDFiumEngine::LoadPageInfo(bool reload) { if (!doc_loader_) return; @@ -2469,12 +2447,7 @@ layout_.AppendPageRect(size); } - for (size_t i = 0; i < new_page_count; ++i) { - // Center pages relative to the entire document. - page_rects[i].set_x((layout_.size().width() - page_rects[i].width()) / 2); - InsetPage(i, new_page_count, /*multiplier=*/1, &page_rects[i]); - AppendPageRectToPages(page_rects[i], i, reload); - } + LoadPagesInSingleView(std::move(page_rects), reload); // Remove pages that do not exist anymore. if (pages_.size() > new_page_count) { @@ -2811,23 +2784,25 @@ // If in two-up view, only need to draw the left empty space for left pages // since the gap between the left and right page will be drawn by the left // page. - pp::Rect left = - draw_utils::GetLeftFillRect(page_rect, inset_sizes, kBottomSeparator); - left = GetScreenRect(left).Intersect(dirty_in_screen); + pp::Rect left_in_screen = GetScreenRect( + draw_utils::GetLeftFillRect(page_rect, inset_sizes, kBottomSeparator)); + left_in_screen = left_in_screen.Intersect(dirty_in_screen); - FPDFBitmap_FillRect(bitmap, left.x() - dirty_in_screen.x(), - left.y() - dirty_in_screen.y(), left.width(), - left.height(), client_->GetBackgroundColor()); + FPDFBitmap_FillRect(bitmap, left_in_screen.x() - dirty_in_screen.x(), + left_in_screen.y() - dirty_in_screen.y(), + left_in_screen.width(), left_in_screen.height(), + client_->GetBackgroundColor()); } if (page_rect.right() < layout_.size().width()) { - pp::Rect right = draw_utils::GetRightFillRect( - page_rect, inset_sizes, layout_.size().width(), kBottomSeparator); - right = GetScreenRect(right).Intersect(dirty_in_screen); + pp::Rect right_in_screen = GetScreenRect(draw_utils::GetRightFillRect( + page_rect, inset_sizes, layout_.size().width(), kBottomSeparator)); + right_in_screen = right_in_screen.Intersect(dirty_in_screen); - FPDFBitmap_FillRect(bitmap, right.x() - dirty_in_screen.x(), - right.y() - dirty_in_screen.y(), right.width(), - right.height(), client_->GetBackgroundColor()); + FPDFBitmap_FillRect(bitmap, right_in_screen.x() - dirty_in_screen.x(), + right_in_screen.y() - dirty_in_screen.y(), + right_in_screen.width(), right_in_screen.height(), + client_->GetBackgroundColor()); } pp::Rect bottom_in_screen;
diff --git a/pdf/pdfium/pdfium_engine.h b/pdf/pdfium/pdfium_engine.h index fbeda00..ee8c7e0d 100644 --- a/pdf/pdfium/pdfium_engine.h +++ b/pdf/pdfium/pdfium_engine.h
@@ -39,6 +39,7 @@ namespace chrome_pdf { class PDFiumDocument; +class PDFiumPermissions; namespace draw_utils { class ShadowMatrix; @@ -238,6 +239,10 @@ size_t page_index, bool reload); + // Formats the pages of |page_rects| for single-view and appends them to + // |pages_|. + void LoadPagesInSingleView(std::vector<pp::Rect> page_rects, bool reload); + // Loads information about the pages in the document and calculate the // document size. void LoadPageInfo(bool reload); @@ -608,11 +613,7 @@ // Where to resume searching. (0-based) base::Optional<size_t> resume_find_index_; - // Permissions bitfield. - unsigned long permissions_ = 0; - - // Permissions security handler revision number. -1 for unknown. - int permissions_handler_revision_ = -1; + std::unique_ptr<PDFiumPermissions> permissions_; pp::Size default_page_size_;
diff --git a/pdf/pdfium/pdfium_page.cc b/pdf/pdfium/pdfium_page.cc index 8557f903..e7f10cf 100644 --- a/pdf/pdfium/pdfium_page.cc +++ b/pdf/pdfium/pdfium_page.cc
@@ -423,29 +423,6 @@ return -1; } -std::vector<int> PDFiumPage::GetLinks(pp::Rect text_area, - std::vector<LinkTarget>* targets) { - std::vector<int> links; - if (!available_) - return links; - - CalculateLinks(); - - for (size_t i = 0; i < links_.size(); ++i) { - for (const auto& rect : links_[i].rects) { - if (rect.Intersects(text_area)) { - if (targets) { - LinkTarget target; - target.url = links_[i].url; - targets->push_back(target); - } - links.push_back(i); - } - } - } - return links; -} - void PDFiumPage::CalculateLinks() { if (calculated_links_) return;
diff --git a/pdf/pdfium/pdfium_page.h b/pdf/pdfium/pdfium_page.h index 1020db75..8a68b73 100644 --- a/pdf/pdfium/pdfium_page.h +++ b/pdf/pdfium/pdfium_page.h
@@ -133,10 +133,6 @@ // Returns a link index if the given character index is over a link, or -1 // otherwise. int GetLink(int char_index, LinkTarget* target); - // Returns the link indices if the given rect intersects a link rect, or an - // empty vector otherwise. - std::vector<int> GetLinks(pp::Rect text_area, - std::vector<LinkTarget>* targets); // Calculate the locations of any links on the page. void CalculateLinks(); // Returns link type and fills target associated with a link. Returns
diff --git a/pdf/pdfium/pdfium_permissions.cc b/pdf/pdfium/pdfium_permissions.cc new file mode 100644 index 0000000..08dba8a --- /dev/null +++ b/pdf/pdfium/pdfium_permissions.cc
@@ -0,0 +1,57 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "pdf/pdfium/pdfium_permissions.h" + +namespace chrome_pdf { + +namespace { + +// See Table 3.20 in +// http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf +constexpr uint32_t kPDFPermissionPrintLowQualityMask = 1 << 2; +constexpr uint32_t kPDFPermissionPrintHighQualityMask = 1 << 11; +constexpr uint32_t kPDFPermissionCopyMask = 1 << 4; +constexpr uint32_t kPDFPermissionCopyAccessibleMask = 1 << 9; + +} // namespace + +PDFiumPermissions::PDFiumPermissions(FPDF_DOCUMENT doc) + : permissions_handler_revision_(FPDF_GetSecurityHandlerRevision(doc)), + permission_bits_(FPDF_GetDocPermissions(doc)) {} + +bool PDFiumPermissions::HasPermission( + PDFEngine::DocumentPermission permission) const { + // PDF 1.7 spec, section 3.5.2 says: "If the revision number is 2 or greater, + // the operations to which user access can be controlled are as follows: ..." + // + // Thus for revision numbers less than 2, permissions are ignored and this + // always returns true. + if (permissions_handler_revision_ < 2) + return true; + + // Handle high quality printing permission separately for security handler + // revision 3+. See table 3.20 in the PDF 1.7 spec. + if (permission == PDFEngine::PERMISSION_PRINT_HIGH_QUALITY && + permissions_handler_revision_ >= 3) { + return (permission_bits_ & kPDFPermissionPrintLowQualityMask) != 0 && + (permission_bits_ & kPDFPermissionPrintHighQualityMask) != 0; + } + + switch (permission) { + case PDFEngine::PERMISSION_COPY: + return (permission_bits_ & kPDFPermissionCopyMask) != 0; + case PDFEngine::PERMISSION_COPY_ACCESSIBLE: + return (permission_bits_ & kPDFPermissionCopyAccessibleMask) != 0; + case PDFEngine::PERMISSION_PRINT_LOW_QUALITY: + case PDFEngine::PERMISSION_PRINT_HIGH_QUALITY: + // With security handler revision 2 rules, check the same bit for high + // and low quality. See table 3.20 in the PDF 1.7 spec. + return (permission_bits_ & kPDFPermissionPrintLowQualityMask) != 0; + default: + return true; + } +} + +} // namespace chrome_pdf
diff --git a/pdf/pdfium/pdfium_permissions.h b/pdf/pdfium/pdfium_permissions.h new file mode 100644 index 0000000..19523ee4 --- /dev/null +++ b/pdf/pdfium/pdfium_permissions.h
@@ -0,0 +1,30 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PDF_PDFIUM_PDFIUM_PERMISSIONS_H_ +#define PDF_PDFIUM_PDFIUM_PERMISSIONS_H_ + +#include "pdf/pdf_engine.h" +#include "third_party/pdfium/public/fpdfview.h" + +namespace chrome_pdf { + +// The permissions for a given FPDF_DOCUMENT. +class PDFiumPermissions final { + public: + explicit PDFiumPermissions(FPDF_DOCUMENT doc); + + bool HasPermission(PDFEngine::DocumentPermission permission) const; + + private: + // Permissions security handler revision number. -1 for unknown. + const int permissions_handler_revision_; + + // Permissions bitfield. + const unsigned long permission_bits_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PDFIUM_PDFIUM_PERMISSIONS_H_
diff --git a/ppapi/host/resource_message_filter.h b/ppapi/host/resource_message_filter.h index 0b50cb04..b9c4b74 100644 --- a/ppapi/host/resource_message_filter.h +++ b/ppapi/host/resource_message_filter.h
@@ -52,7 +52,7 @@ // scoped_refptr<base::TaskRunner> OverrideTaskRunnerForMessage( // const IPC::Message& message) override { // if (message.type() == MyMessage::ID) { -// return base::CreateSingleThreadTaskRunnerWithTraits( +// return base::CreateSingleThreadTaskRunner( // {BrowserThread::UI}); // } // return NULL;
diff --git a/printing/printed_document.cc b/printing/printed_document.cc index 2f695880a..1f3c0c0 100644 --- a/printing/printed_document.cc +++ b/printing/printed_document.cc
@@ -94,8 +94,9 @@ job_settings, base::JSONWriter::OPTIONS_PRETTY_PRINT, &settings_str); scoped_refptr<base::RefCountedMemory> data = base::RefCountedString::TakeString(&settings_str); - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&DebugDumpDataTask, doc_name, FILE_PATH_LITERAL(".json"), base::RetainedRef(data))); } @@ -138,8 +139,9 @@ } if (HasDebugDumpPath()) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&DebugDumpPageTask, name(), base::RetainedRef(page))); } } @@ -169,8 +171,9 @@ } if (HasDebugDumpPath()) { - base::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, base::BindOnce(&DebugDumpTask, name(), mutable_.metafile_.get())); } } @@ -268,10 +271,11 @@ const base::RefCountedMemory* data, const base::FilePath::StringType& extension) { DCHECK(HasDebugDumpPath()); - base::PostTaskWithTraits(FROM_HERE, - {base::TaskPriority::BEST_EFFORT, base::MayBlock()}, - base::BindOnce(&DebugDumpDataTask, name(), extension, - base::RetainedRef(data))); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::TaskPriority::BEST_EFFORT, base::MayBlock()}, + base::BindOnce(&DebugDumpDataTask, name(), extension, + base::RetainedRef(data))); } #if defined(OS_WIN) || defined(OS_MACOSX)
diff --git a/remoting/host/clipboard_win.cc b/remoting/host/clipboard_win.cc index bcad284..4134afe 100644 --- a/remoting/host/clipboard_win.cc +++ b/remoting/host/clipboard_win.cc
@@ -97,9 +97,6 @@ bool opened_; }; -typedef BOOL (WINAPI AddClipboardFormatListenerFn)(HWND); -typedef BOOL (WINAPI RemoveClipboardFormatListenerFn)(HWND); - } // namespace namespace remoting { @@ -124,51 +121,25 @@ LRESULT* result); std::unique_ptr<protocol::ClipboardStub> client_clipboard_; - AddClipboardFormatListenerFn* add_clipboard_format_listener_; - RemoveClipboardFormatListenerFn* remove_clipboard_format_listener_; - // Used to subscribe to WM_CLIPBOARDUPDATE messages. std::unique_ptr<base::win::MessageWindow> window_; DISALLOW_COPY_AND_ASSIGN(ClipboardWin); }; -ClipboardWin::ClipboardWin() - : add_clipboard_format_listener_(nullptr), - remove_clipboard_format_listener_(nullptr) { -} +ClipboardWin::ClipboardWin() {} ClipboardWin::~ClipboardWin() { - if (window_ && remove_clipboard_format_listener_) - (*remove_clipboard_format_listener_)(window_->hwnd()); + if (window_) + ::RemoveClipboardFormatListener(window_->hwnd()); } void ClipboardWin::Start( std::unique_ptr<protocol::ClipboardStub> client_clipboard) { - DCHECK(!add_clipboard_format_listener_); - DCHECK(!remove_clipboard_format_listener_); DCHECK(!window_); client_clipboard_.swap(client_clipboard); - // user32.dll is statically linked. - HMODULE user32 = GetModuleHandle(L"user32.dll"); - CHECK(user32); - - add_clipboard_format_listener_ = - reinterpret_cast<AddClipboardFormatListenerFn*>( - GetProcAddress(user32, "AddClipboardFormatListener")); - if (add_clipboard_format_listener_) { - remove_clipboard_format_listener_ = - reinterpret_cast<RemoveClipboardFormatListenerFn*>( - GetProcAddress(user32, "RemoveClipboardFormatListener")); - // If AddClipboardFormatListener() present, RemoveClipboardFormatListener() - // should be available too. - CHECK(remove_clipboard_format_listener_); - } else { - LOG(WARNING) << "AddClipboardFormatListener() is not available."; - } - window_.reset(new base::win::MessageWindow()); if (!window_->Create(base::Bind(&ClipboardWin::HandleMessage, base::Unretained(this)))) { @@ -177,10 +148,8 @@ return; } - if (add_clipboard_format_listener_) { - if (!(*add_clipboard_format_listener_)(window_->hwnd())) { - LOG(WARNING) << "AddClipboardFormatListener() failed: " << GetLastError(); - } + if (!::AddClipboardFormatListener(window_->hwnd())) { + LOG(WARNING) << "AddClipboardFormatListener() failed: " << GetLastError(); } }
diff --git a/sandbox/win/sandbox_poc/main_ui_window.cc b/sandbox/win/sandbox_poc/main_ui_window.cc index 89c1be7..6bdc171 100644 --- a/sandbox/win/sandbox_poc/main_ui_window.cc +++ b/sandbox/win/sandbox_poc/main_ui_window.cc
@@ -626,6 +626,7 @@ text[kMaxDebugBuffSize] = L'\0'; InsertLineInListView(text); + va_end(arg_list); }
diff --git a/sandbox/win/sandbox_poc/sandbox.cc b/sandbox/win/sandbox_poc/sandbox.cc index 88757ef..6d49a80 100644 --- a/sandbox/win/sandbox_poc/sandbox.cc +++ b/sandbox/win/sandbox_poc/sandbox.cc
@@ -154,6 +154,7 @@ HMODULE dll_module = ::LoadLibraryA(dll_name.c_str()); if (dll_module == NULL) { // TODO(finnur): write the failure to the log file + CloseHandle(pipe); return -5; }
diff --git a/services/network/network_context.cc b/services/network/network_context.cc index b1108bb..3622ba17 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc
@@ -542,36 +542,6 @@ InitializeCorsParams(); } -// TODO(mmenke): Share URLRequestContextBulder configuration between two -// constructors. Can only share them once consumer code is ready for its -// corresponding options to be overwritten. -NetworkContext::NetworkContext( - NetworkService* network_service, - mojom::NetworkContextRequest request, - mojom::NetworkContextParamsPtr params, - std::unique_ptr<URLRequestContextBuilderMojo> builder) - : network_service_(network_service), - url_request_context_(nullptr), - params_(std::move(params)), -#if defined(OS_ANDROID) - app_status_listener_( - std::make_unique<NetworkContextApplicationStatusListener>()), -#endif - binding_(this, std::move(request)) { - url_request_context_owner_ = ApplyContextParamsToBuilder(builder.get()); - url_request_context_ = url_request_context_owner_.url_request_context.get(); - - network_service_->RegisterNetworkContext(this); - socket_factory_ = std::make_unique<SocketFactory>( - url_request_context_->net_log(), url_request_context_); - resource_scheduler_ = - std::make_unique<ResourceScheduler>(enable_resource_scheduler_); - - origin_policy_manager_ = std::make_unique<OriginPolicyManager>(this); - - InitializeCorsParams(); -} - NetworkContext::NetworkContext( NetworkService* network_service, mojom::NetworkContextRequest request, @@ -1042,15 +1012,15 @@ } void NetworkContext::SetAcceptLanguage(const std::string& new_accept_language) { - // This may only be called on NetworkContexts created with a constructor that - // calls ApplyContextParamsToBuilder. + // This may only be called on NetworkContexts created with the constructor + // that calls MakeURLRequestContext(). DCHECK(user_agent_settings_); user_agent_settings_->set_accept_language(new_accept_language); } void NetworkContext::SetEnableReferrers(bool enable_referrers) { - // This may only be called on NetworkContexts created with a constructor that - // calls ApplyContextParamsToBuilder. + // This may only be called on NetworkContexts created with the constructor + // that calls MakeURLRequestContext(). DCHECK(context_network_delegate_); context_network_delegate_->set_enable_referrers(enable_referrers); } @@ -1702,26 +1672,88 @@ std::move(callback).Run(base::nullopt); } -// ApplyContextParamsToBuilder represents the core configuration for -// translating |network_context_params| into a set of configuration that can -// be used to build a request context. All new initialization should be done -// within this method. If objects need to be created that would not be owned -// by |builder| - that is, objects that would be stored and owned in the -// NetworkContext if this method was not static - should be added as -// (optional) out-params. -URLRequestContextOwner NetworkContext::ApplyContextParamsToBuilder( - URLRequestContextBuilderMojo* builder) { +URLRequestContextOwner NetworkContext::MakeURLRequestContext() { + URLRequestContextBuilderMojo builder; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + std::unique_ptr<net::CertVerifier> cert_verifier; + if (g_cert_verifier_for_testing) { + cert_verifier = std::make_unique<WrappedTestingCertVerifier>(); + } else { +#if defined(OS_ANDROID) || defined(OS_FUCHSIA) || defined(OS_CHROMEOS) || \ + BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) + cert_net_fetcher_ = base::MakeRefCounted<net::CertNetFetcherImpl>(); +#endif +#if defined(OS_CHROMEOS) + if (params_->username_hash.empty()) { + cert_verifier = std::make_unique<net::CachingCertVerifier>( + std::make_unique<net::MultiThreadedCertVerifier>( + CreateCertVerifyProcWithoutUserSlots(cert_net_fetcher_))); + } else { + // Make sure NSS is initialized for the user. + crypto::InitializeNSSForChromeOSUser(params_->username_hash, + params_->nss_path.value()); + + crypto::ScopedPK11Slot public_slot = + crypto::GetPublicSlotForChromeOSUser(params_->username_hash); + scoped_refptr<net::CertVerifyProc> verify_proc = + CreateCertVerifyProcForUser(cert_net_fetcher_, + std::move(public_slot)); + + cert_verifier_with_trust_anchors_ = new CertVerifierWithTrustAnchors( + base::Bind(&NetworkContext::TrustAnchorUsed, base::Unretained(this))); + UpdateAdditionalCertificates( + std::move(params_->initial_additional_certificates)); + cert_verifier_with_trust_anchors_->InitializeOnIOThread(verify_proc); + cert_verifier = base::WrapUnique(cert_verifier_with_trust_anchors_); + } +#elif BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) + if (params_->trial_comparison_cert_verifier_params) { + cert_verifier = std::make_unique<net::CachingCertVerifier>( + std::make_unique<TrialComparisonCertVerifierMojo>( + params_->trial_comparison_cert_verifier_params->initial_allowed, + std::move(params_->trial_comparison_cert_verifier_params + ->config_client_request), + std::move(params_->trial_comparison_cert_verifier_params + ->report_client), + net::CertVerifyProc::CreateDefault(cert_net_fetcher_), + net::CreateCertVerifyProcBuiltin( + cert_net_fetcher_, /*system_trust_store_provider=*/nullptr))); + } +#endif + if (!cert_verifier) + cert_verifier = net::CertVerifier::CreateDefault(cert_net_fetcher_); + } + + builder.SetCertVerifier(IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( + *command_line, nullptr, std::move(cert_verifier))); + + std::unique_ptr<net::NetworkDelegate> network_delegate = + std::make_unique<NetworkServiceNetworkDelegate>(this); + builder.set_network_delegate(std::move(network_delegate)); + + if (params_->initial_custom_proxy_config || + params_->custom_proxy_config_client_request) { + std::unique_ptr<NetworkServiceProxyDelegate> proxy_delegate = + std::make_unique<NetworkServiceProxyDelegate>( + std::move(params_->initial_custom_proxy_config), + std::move(params_->custom_proxy_config_client_request)); + proxy_delegate_ = proxy_delegate.get(); + builder.set_proxy_delegate(std::move(proxy_delegate)); + } + net::NetLog* net_log = nullptr; if (network_service_) { net_log = network_service_->net_log(); - builder->set_net_log(net_log); - builder->set_host_resolver_manager( + builder.set_net_log(net_log); + builder.set_host_resolver_manager( network_service_->host_resolver_manager()); - builder->set_host_resolver_factory( + builder.set_host_resolver_factory( network_service_->host_resolver_factory()); - builder->set_shared_http_auth_handler_factory( + builder.set_shared_http_auth_handler_factory( network_service_->GetHttpAuthHandlerFactory()); - builder->set_network_quality_estimator( + builder.set_network_quality_estimator( network_service_->network_quality_estimator()); } @@ -1759,7 +1791,7 @@ if (params_->persist_session_cookies) cookie_store->SetPersistSessionCookies(true); - builder->SetCookieStore(std::move(cookie_store)); + builder.SetCookieStore(std::move(cookie_store)); } else { DCHECK(!params_->restore_old_session_cookies); DCHECK(!params_->persist_session_cookies); @@ -1770,20 +1802,20 @@ params_->accept_language, params_->user_agent); // Borrow an alias for future use before giving the builder ownership. user_agent_settings_ = user_agent_settings.get(); - builder->set_http_user_agent_settings(std::move(user_agent_settings)); + builder.set_http_user_agent_settings(std::move(user_agent_settings)); - builder->set_enable_brotli(params_->enable_brotli); + builder.set_enable_brotli(params_->enable_brotli); if (params_->context_name) - builder->set_name(*params_->context_name); + builder.set_name(*params_->context_name); if (params_->proxy_resolver_factory) { - builder->SetMojoProxyResolverFactory( + builder.SetMojoProxyResolverFactory( proxy_resolver::mojom::ProxyResolverFactoryPtr( std::move(params_->proxy_resolver_factory))); } if (!params_->http_cache_enabled) { - builder->DisableHttpCache(); + builder.DisableHttpCache(); } else { net::URLRequestContextBuilder::HttpCacheParams cache_params; cache_params.max_size = params_->http_cache_max_size; @@ -1798,7 +1830,7 @@ #if defined(OS_ANDROID) cache_params.app_status_listener = app_status_listener(); #endif - builder->EnableHttpCache(cache_params); + builder.EnableHttpCache(cache_params); } std::unique_ptr<SSLConfigServiceMojo> ssl_config_service = @@ -1807,18 +1839,18 @@ std::move(params_->ssl_config_client_request), network_service_->crl_set_distributor()); SSLConfigServiceMojo* ssl_config_service_raw = ssl_config_service.get(); - builder->set_ssl_config_service(std::move(ssl_config_service)); + builder.set_ssl_config_service(std::move(ssl_config_service)); if (!params_->initial_proxy_config && !params_->proxy_config_client_request.is_pending()) { params_->initial_proxy_config = net::ProxyConfigWithAnnotation::CreateDirect(); } - builder->set_proxy_config_service(std::make_unique<ProxyConfigServiceMojo>( + builder.set_proxy_config_service(std::make_unique<ProxyConfigServiceMojo>( std::move(params_->proxy_config_client_request), std::move(params_->initial_proxy_config), std::move(params_->proxy_config_poller_client))); - builder->set_pac_quick_check_enabled(params_->pac_quick_check_enabled); + builder.set_pac_quick_check_enabled(params_->pac_quick_check_enabled); std::unique_ptr<PrefService> pref_service; if (params_->http_server_properties_path) { @@ -1836,7 +1868,7 @@ NetworkQualitiesPrefDelegate::RegisterPrefs(pref_registry.get()); pref_service = pref_service_factory.Create(pref_registry.get()); - builder->SetHttpServerProperties( + builder.SetHttpServerProperties( std::make_unique<net::HttpServerPropertiesManager>( std::make_unique<HttpServerPropertiesPrefDelegate>( pref_service.get()), @@ -1848,16 +1880,16 @@ } if (params_->transport_security_persister_path) { - builder->set_transport_security_persister_path( + builder.set_transport_security_persister_path( *params_->transport_security_persister_path); } // With the network service data URLs are handled by clients directly. if (!base::FeatureList::IsEnabled(features::kNetworkService)) - builder->set_data_enabled(true); + builder.set_data_enabled(true); #if !BUILDFLAG(DISABLE_FTP_SUPPORT) - builder->set_ftp_enabled(params_->enable_ftp_url_support); + builder.set_ftp_enabled(params_->enable_ftp_url_support); #else // BUILDFLAG(DISABLE_FTP_SUPPORT) DCHECK(!params_->enable_ftp_url_support); #endif @@ -1869,18 +1901,18 @@ reporting_policy->delivery_interval = *params_->reporting_delivery_interval; } - builder->set_reporting_policy(std::move(reporting_policy)); + builder.set_reporting_policy(std::move(reporting_policy)); } else { - builder->set_reporting_policy(nullptr); + builder.set_reporting_policy(nullptr); } - builder->set_network_error_logging_enabled( + builder.set_network_error_logging_enabled( base::FeatureList::IsEnabled(features::kNetworkErrorLogging)); #endif // BUILDFLAG(ENABLE_REPORTING) #if BUILDFLAG(IS_CT_SUPPORTED) if (params_->enforce_chrome_ct_policy) { - builder->set_ct_policy_enforcer( + builder.set_ct_policy_enforcer( std::make_unique<certificate_transparency::ChromeCTPolicyEnforcer>( base::GetBuildTime(), certificate_transparency::GetDisqualifiedLogs(), @@ -1902,9 +1934,9 @@ session_params.disable_idle_sockets_close_on_memory_pressure = params_->disable_idle_sockets_close_on_memory_pressure; - builder->set_http_network_session_params(session_params); + builder.set_http_network_session_params(session_params); - builder->SetCreateHttpTransactionFactoryCallback( + builder.SetCreateHttpTransactionFactoryCallback( base::BindOnce([](net::HttpNetworkSession* session) -> std::unique_ptr<net::HttpTransactionFactory> { return std::make_unique<ThrottlingNetworkTransactionFactory>(session); @@ -1915,7 +1947,7 @@ // TODO(mmenke): Clean this up, once NetworkContext no longer needs to // support taking a URLRequestContextBuilder with a pre-configured // NetworkContext. - builder->SetCreateLayeredNetworkDelegateCallback(base::BindOnce( + builder.SetCreateLayeredNetworkDelegateCallback(base::BindOnce( [](mojom::NetworkContextParams* network_context_params, ContextNetworkDelegate** out_context_network_delegate, NetworkContext* network_context, @@ -1949,22 +1981,20 @@ } auto ct_verifier = std::make_unique<net::MultiLogCTVerifier>(); ct_verifier->AddLogs(ct_logs); - builder->set_ct_verifier(std::move(ct_verifier)); + builder.set_ct_verifier(std::move(ct_verifier)); } #endif // BUILDFLAG(IS_CT_SUPPORTED) - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - builder->set_host_mapping_rules( + builder.set_host_mapping_rules( command_line->GetSwitchValueASCII(switches::kHostResolverRules)); // Allow legacy context CopyFrom() functionality only if network service is // disabled. The new service-enabled world should never do such copying. if (!base::FeatureList::IsEnabled(features::kNetworkService)) - builder->set_allow_copy(); + builder.set_allow_copy(); auto result = - URLRequestContextOwner(std::move(pref_service), builder->Build()); + URLRequestContextOwner(std::move(pref_service), builder.Build()); // Subscribe the CertVerifier to configuration changes that are exposed via // the mojom::SSLConfig, but which are not part of the @@ -2063,6 +2093,9 @@ std::move(session_cleanup_cookie_store), std::move(params_->cookie_manager_params)); + if (cert_net_fetcher_) + cert_net_fetcher_->SetURLRequestContext(result.url_request_context.get()); + return result; } @@ -2102,86 +2135,6 @@ std::move(on_connection_close_callback_).Run(this); } -URLRequestContextOwner NetworkContext::MakeURLRequestContext() { - URLRequestContextBuilderMojo builder; - const base::CommandLine* command_line = - base::CommandLine::ForCurrentProcess(); - - std::unique_ptr<net::CertVerifier> cert_verifier; - if (g_cert_verifier_for_testing) { - cert_verifier = std::make_unique<WrappedTestingCertVerifier>(); - } else { -#if defined(OS_ANDROID) || defined(OS_FUCHSIA) || defined(OS_CHROMEOS) || \ - BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) - cert_net_fetcher_ = base::MakeRefCounted<net::CertNetFetcherImpl>(); -#endif -#if defined(OS_CHROMEOS) - if (params_->username_hash.empty()) { - cert_verifier = std::make_unique<net::CachingCertVerifier>( - std::make_unique<net::MultiThreadedCertVerifier>( - CreateCertVerifyProcWithoutUserSlots(cert_net_fetcher_))); - } else { - // Make sure NSS is initialized for the user. - crypto::InitializeNSSForChromeOSUser(params_->username_hash, - params_->nss_path.value()); - - crypto::ScopedPK11Slot public_slot = - crypto::GetPublicSlotForChromeOSUser(params_->username_hash); - scoped_refptr<net::CertVerifyProc> verify_proc = - CreateCertVerifyProcForUser(cert_net_fetcher_, - std::move(public_slot)); - - cert_verifier_with_trust_anchors_ = new CertVerifierWithTrustAnchors( - base::Bind(&NetworkContext::TrustAnchorUsed, base::Unretained(this))); - UpdateAdditionalCertificates( - std::move(params_->initial_additional_certificates)); - cert_verifier_with_trust_anchors_->InitializeOnIOThread(verify_proc); - cert_verifier = base::WrapUnique(cert_verifier_with_trust_anchors_); - } -#elif BUILDFLAG(TRIAL_COMPARISON_CERT_VERIFIER_SUPPORTED) - if (params_->trial_comparison_cert_verifier_params) { - cert_verifier = std::make_unique<net::CachingCertVerifier>( - std::make_unique<TrialComparisonCertVerifierMojo>( - params_->trial_comparison_cert_verifier_params->initial_allowed, - std::move(params_->trial_comparison_cert_verifier_params - ->config_client_request), - std::move(params_->trial_comparison_cert_verifier_params - ->report_client), - net::CertVerifyProc::CreateDefault(cert_net_fetcher_), - net::CreateCertVerifyProcBuiltin( - cert_net_fetcher_, /*system_trust_store_provider=*/nullptr))); - } -#endif - if (!cert_verifier) - cert_verifier = net::CertVerifier::CreateDefault(cert_net_fetcher_); - } - - builder.SetCertVerifier(IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( - *command_line, nullptr, std::move(cert_verifier))); - - std::unique_ptr<net::NetworkDelegate> network_delegate = - std::make_unique<NetworkServiceNetworkDelegate>(this); - builder.set_network_delegate(std::move(network_delegate)); - - if (params_->initial_custom_proxy_config || - params_->custom_proxy_config_client_request) { - std::unique_ptr<NetworkServiceProxyDelegate> proxy_delegate = - std::make_unique<NetworkServiceProxyDelegate>( - std::move(params_->initial_custom_proxy_config), - std::move(params_->custom_proxy_config_client_request)); - proxy_delegate_ = proxy_delegate.get(); - builder.set_proxy_delegate(std::move(proxy_delegate)); - } - - // |network_service_| may be nullptr in tests. - auto result = ApplyContextParamsToBuilder(&builder); - - if (cert_net_fetcher_) - cert_net_fetcher_->SetURLRequestContext(result.url_request_context.get()); - - return result; -} - GURL NetworkContext::GetHSTSRedirect(const GURL& original_url) { // TODO(lilyhoughton) This needs to be gotten rid of once explicit // construction with a URLRequestContext is no longer supported.
diff --git a/services/network/network_context.h b/services/network/network_context.h index 29728931..d2a93d3b 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h
@@ -91,7 +91,6 @@ class ProxyLookupRequest; class ResourceScheduler; class ResourceSchedulerClient; -class URLRequestContextBuilderMojo; class WebSocketFactory; namespace cors { @@ -104,13 +103,6 @@ // NetworkService's mojo interface and are owned jointly by the NetworkService // and the NetworkContextPtr used to talk to them, and the NetworkContext is // destroyed when either one is torn down. -// -// When the network service is disabled, NetworkContexts may be created through -// NetworkService::CreateNetworkContextWithBuilder, and take in a -// URLRequestContextBuilderMojo to seed construction of the NetworkContext's -// URLRequestContext. When that happens, the consumer takes ownership of the -// NetworkContext directly, has direct access to its URLRequestContext, and is -// responsible for destroying it before the NetworkService. class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext : public mojom::NetworkContext { public: @@ -123,15 +115,6 @@ OnConnectionCloseCallback on_connection_close_callback = OnConnectionCloseCallback()); - // DEPRECATED: Creates an in-process NetworkContext with a partially - // pre-populated URLRequestContextBuilderMojo. This API should not be used - // in new code, as some |params| configuration may be ignored, in favor of - // the pre-configured URLRequestContextBuilderMojo configuration. - NetworkContext(NetworkService* network_service, - mojom::NetworkContextRequest request, - mojom::NetworkContextParamsPtr params, - std::unique_ptr<URLRequestContextBuilderMojo> builder); - // DEPRECATED: Creates a NetworkContext that simply wraps a consumer-provided // URLRequestContext that is not owned by the NetworkContext. // TODO(mmenke): Remove this constructor when the network service ships. @@ -422,10 +405,7 @@ private: class ContextNetworkDelegate; - // Applies the values in |params_| to |builder|, and builds the - // URLRequestContext. - URLRequestContextOwner ApplyContextParamsToBuilder( - URLRequestContextBuilderMojo* builder); + URLRequestContextOwner MakeURLRequestContext(); // Invoked when the HTTP cache was cleared. Invokes |callback|. void OnHttpCacheCleared(ClearHttpCacheCallback callback, @@ -443,8 +423,6 @@ // On connection errors the NetworkContext destroys itself. void OnConnectionError(); - URLRequestContextOwner MakeURLRequestContext(); - GURL GetHSTSRedirect(const GURL& original_url); void DestroySocketManager(P2PSocketManager* socket_manager);
diff --git a/services/network/network_service.cc b/services/network/network_service.cc index 225abad..40500cf 100644 --- a/services/network/network_service.cc +++ b/services/network/network_service.cc
@@ -43,7 +43,6 @@ #include "net/socket/client_socket_pool_manager.h" #include "net/ssl/ssl_key_logger_impl.h" #include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_builder.h" #include "services/network/crl_set_distributor.h" #include "services/network/cross_origin_read_blocking.h" #include "services/network/dns_config_change_manager.h" @@ -55,7 +54,6 @@ #include "services/network/public/cpp/load_info_util.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/url_loader.h" -#include "services/network/url_request_context_builder_mojo.h" #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL) #include "crypto/openssl_util.h" @@ -215,9 +213,7 @@ service_binding_.Bind(std::move(service_request)); // |registry_| is nullptr when an in-process NetworkService is - // created directly. The latter is done in concert with using - // CreateNetworkContextWithBuilder to ease the transition to using the - // network service. + // created directly, like in most unit tests. if (registry_) { mojo::core::SetDefaultProcessErrorCallback( base::BindRepeating(&HandleBadMessage)); @@ -330,20 +326,6 @@ std::move(service_request)); } -std::unique_ptr<mojom::NetworkContext> -NetworkService::CreateNetworkContextWithBuilder( - mojom::NetworkContextRequest request, - mojom::NetworkContextParamsPtr params, - std::unique_ptr<URLRequestContextBuilderMojo> builder, - net::URLRequestContext** url_request_context) { - DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService)); - std::unique_ptr<NetworkContext> network_context = - std::make_unique<NetworkContext>(this, std::move(request), - std::move(params), std::move(builder)); - *url_request_context = network_context->url_request_context(); - return network_context; -} - std::unique_ptr<NetworkService> NetworkService::CreateForTesting() { return CreateForTesting(nullptr); }
diff --git a/services/network/network_service.h b/services/network/network_service.h index 633cebdd..1a87e22 100644 --- a/services/network/network_service.h +++ b/services/network/network_service.h
@@ -57,7 +57,6 @@ class HttpAuthCacheCopier; class NetworkContext; class NetworkUsageAccumulator; -class URLRequestContextBuilderMojo; class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkService : public service_manager::Service, @@ -76,22 +75,6 @@ // encrypted storage can be used. void set_os_crypt_is_configured(); - // Can be used to seed a NetworkContext with a consumer-configured - // URLRequestContextBuilder, which |params| will then be applied to. The - // results URLRequestContext will be written to |url_request_context|, which - // is owned by the NetworkContext, and can be further modified before first - // use. The returned NetworkContext must be destroyed before the - // NetworkService. - // - // This method is intended to ease the transition to an out-of-process - // NetworkService, and will be removed once that ships. It should only be - // called if the network service is disabled. - std::unique_ptr<mojom::NetworkContext> CreateNetworkContextWithBuilder( - mojom::NetworkContextRequest request, - mojom::NetworkContextParamsPtr params, - std::unique_ptr<URLRequestContextBuilderMojo> builder, - net::URLRequestContext** url_request_context); - // Allows late binding if the mojo request wasn't specified in the // constructor. void Bind(mojom::NetworkServiceRequest request);
diff --git a/services/tracing/OWNERS b/services/tracing/OWNERS index 72f35f4..4eb41f25 100644 --- a/services/tracing/OWNERS +++ b/services/tracing/OWNERS
@@ -5,3 +5,4 @@ per-file manifest.cc=file://ipc/SECURITY_OWNERS per-file manifest.h=set noparent per-file manifest.h=file://ipc/SECURITY_OWNERS +# COMPONENT: Speed>Tracing
diff --git a/services/tracing/perfetto/track_event_json_exporter.cc b/services/tracing/perfetto/track_event_json_exporter.cc index efd0fdd..12259cb 100644 --- a/services/tracing/perfetto/track_event_json_exporter.cc +++ b/services/tracing/perfetto/track_event_json_exporter.cc
@@ -639,15 +639,22 @@ void TrackEventJSONExporter::HandleProfiledFrameSymbols( const perfetto::protos::ProfiledFrameSymbols& frame_symbols) { - auto iter = - unordered_state_data_[current_state_->trusted_packet_sequence_id] - .interned_profiled_frame_.insert(std::make_pair( - frame_symbols.frame_iid(), frame_symbols.function_name_id())); + int64_t function_name_id = 0; + // Chrome never has more than one function for an address, so we can just + // take the first one. + if (!frame_symbols.function_name_id().empty()) { + DCHECK(frame_symbols.function_name_id().size() == 1); + function_name_id = frame_symbols.function_name_id()[0]; + } + + auto iter = unordered_state_data_[current_state_->trusted_packet_sequence_id] + .interned_profiled_frame_.insert(std::make_pair( + frame_symbols.frame_iid(), function_name_id)); auto& frame_names = unordered_state_data_[current_state_->trusted_packet_sequence_id] .interned_frame_names_; - DCHECK(iter.second || frame_names[iter.first->second] == - frame_names[frame_symbols.function_name_id()]); + DCHECK(iter.second || + frame_names[iter.first->second] == frame_names[function_name_id]); } void TrackEventJSONExporter::HandleDebugAnnotation(
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 6247311b..2654c8b 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -36338,7 +36338,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36353,7 +36353,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36368,7 +36368,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36383,7 +36383,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36398,7 +36398,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36413,7 +36413,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36428,7 +36428,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36443,7 +36443,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36458,7 +36458,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36473,7 +36473,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36489,7 +36489,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36504,7 +36504,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36519,7 +36519,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36534,7 +36534,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "shards": 10 @@ -36555,7 +36555,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36570,7 +36570,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36588,7 +36588,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36603,7 +36603,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36618,7 +36618,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36633,7 +36633,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36648,7 +36648,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36663,7 +36663,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36678,7 +36678,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36693,7 +36693,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36708,7 +36708,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "shards": 6 @@ -36729,7 +36729,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36749,7 +36749,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36764,7 +36764,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36779,7 +36779,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36794,7 +36794,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36809,7 +36809,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36824,7 +36824,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36839,7 +36839,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36854,7 +36854,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36869,7 +36869,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36884,7 +36884,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36899,7 +36899,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36914,7 +36914,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36929,7 +36929,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36944,7 +36944,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36959,7 +36959,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36974,7 +36974,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -36989,7 +36989,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37004,7 +37004,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37019,7 +37019,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37034,7 +37034,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37049,7 +37049,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "shards": 3 @@ -37070,7 +37070,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37085,7 +37085,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37100,7 +37100,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37115,7 +37115,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37130,7 +37130,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37145,7 +37145,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37160,7 +37160,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37175,7 +37175,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37190,7 +37190,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37205,7 +37205,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37220,7 +37220,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37235,7 +37235,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37250,7 +37250,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37265,7 +37265,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37280,7 +37280,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37295,7 +37295,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37310,7 +37310,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37325,7 +37325,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37340,7 +37340,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37355,7 +37355,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37370,7 +37370,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37385,7 +37385,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37400,7 +37400,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37415,7 +37415,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37430,7 +37430,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37445,7 +37445,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37460,7 +37460,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37475,7 +37475,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37490,7 +37490,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37505,7 +37505,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37520,7 +37520,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37535,7 +37535,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37550,7 +37550,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37565,7 +37565,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37580,7 +37580,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37595,7 +37595,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37610,7 +37610,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37625,7 +37625,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37640,7 +37640,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37655,7 +37655,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37670,7 +37670,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37685,7 +37685,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] }, @@ -37701,7 +37701,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ] },
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index a237b48..9aa3ec6 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -14047,7 +14047,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "expiration": 36000,
diff --git a/testing/buildbot/chromium.webkit.json b/testing/buildbot/chromium.webkit.json index 0afe05f..0b11b65d 100644 --- a/testing/buildbot/chromium.webkit.json +++ b/testing/buildbot/chromium.webkit.json
@@ -89,7 +89,7 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "os": "Ubuntu-14.04" + "os": "Ubuntu-16.04" } ], "expiration": 36000,
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 8b2843d..c1ce02a 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -1953,7 +1953,7 @@ 'swarming': { 'dimension_sets': [ { - 'os': 'Ubuntu-14.04', + 'os': 'Ubuntu-16.04', }, ], 'expiration': 36000,
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index b07ec8b..66ad7a4f 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -974,7 +974,7 @@ }, 'UBSanVptr Linux': { 'mixins': [ - 'linux-trusty', + 'linux-xenial', ], 'test_suites': { # no "_and_gl":gl_unittests doesn't pass yet,
diff --git a/testing/scripts/run_wpt_tests.py b/testing/scripts/run_wpt_tests.py index e350229..d2a4687 100755 --- a/testing/scripts/run_wpt_tests.py +++ b/testing/scripts/run_wpt_tests.py
@@ -81,6 +81,8 @@ self.options.old_json_output_file_path, '--new-json-output-dir', self.options.new_json_output_dir, '--new-json-output-filename', self.options.new_json_output_filename, + '--additional-expectations', + '../../third_party/blink/web_tests/WPTOverrideExpectations', ])
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 152d3eebf..5c4d3d3 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -4986,29 +4986,6 @@ ] } ], - "SkipPassthroughTouchEventQueueFilter": [ - { - "platforms": [ - "linux", - "windows", - "mac", - "android", - "chromeos" - ], - "experiments": [ - { - "name": "EnabledDiscreteEventsRendererProcess_20190507", - "params": { - "skip_filtering_process": "browser_and_renderer", - "type": "discrete" - }, - "enable_features": [ - "SkipTouchEventFilter" - ] - } - ] - } - ], "SpellingServiceRestEndpoint": [ { "platforms": [
diff --git a/third_party/blink/common/BUILD.gn b/third_party/blink/common/BUILD.gn index 2a5b7b8..4bb74d1c 100644 --- a/third_party/blink/common/BUILD.gn +++ b/third_party/blink/common/BUILD.gn
@@ -26,7 +26,7 @@ "blob/blob_utils.cc", "bluetooth/web_bluetooth_device_id.cc", "bluetooth/web_bluetooth_device_id.h", - "bluetooth/web_bluetooth_device_id_struct_traits.h", + "bluetooth/web_bluetooth_device_id_mojom_traits.h", "browser_interface_broker_proxy.cc", "cache_storage/cache_storage_utils.cc", "client_hints/client_hints.cc", @@ -59,14 +59,14 @@ "mediastream/media_stream_mojom_traits.cc", "mediastream/media_stream_request.cc", "messaging/cloneable_message.cc", - "messaging/cloneable_message_struct_traits.cc", + "messaging/cloneable_message_mojom_traits.cc", "messaging/message_port_channel.cc", "messaging/string_message_codec.cc", "messaging/transferable_message.cc", - "messaging/transferable_message_struct_traits.cc", + "messaging/transferable_message_mojom_traits.cc", "mime_util/mime_util.cc", "notifications/notification_resources.cc", - "notifications/notification_struct_traits.cc", + "notifications/notification_mojom_traits.cc", "notifications/platform_notification_data.cc", "origin_policy/origin_policy.cc", "origin_policy/origin_policy_parser.cc", @@ -154,7 +154,7 @@ "manifest/manifest_util_unittest.cc", "mediastream/media_devices_unittest.cc", "mime_util/mime_util_unittest.cc", - "notifications/notification_struct_traits_unittest.cc", + "notifications/notification_mojom_traits_unittest.cc", "origin_policy/origin_policy_unittest.cc", "origin_trials/trial_token_unittest.cc", "origin_trials/trial_token_validator_unittest.cc",
diff --git a/third_party/blink/common/bluetooth/OWNERS b/third_party/blink/common/bluetooth/OWNERS index e41d91a..b69b593b 100644 --- a/third_party/blink/common/bluetooth/OWNERS +++ b/third_party/blink/common/bluetooth/OWNERS
@@ -2,8 +2,8 @@ # Changes to IPC serialization require a security review to avoid introducing # new sandbox escapes. -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap b/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap index 46559fad..f20629b 100644 --- a/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap +++ b/third_party/blink/common/bluetooth/web_bluetooth_device_id.typemap
@@ -5,6 +5,6 @@ mojom = "//third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom" public_headers = [ "//third_party/blink/public/common/bluetooth/web_bluetooth_device_id.h" ] -traits_headers = [ "//third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h" ] +traits_headers = [ "//third_party/blink/public/common/bluetooth/web_bluetooth_device_id_mojom_traits.h" ] type_mappings = [ "blink.mojom.WebBluetoothDeviceId=blink::WebBluetoothDeviceId" ]
diff --git a/third_party/blink/common/messaging/OWNERS b/third_party/blink/common/messaging/OWNERS index 74991d3..ec3a481 100644 --- a/third_party/blink/common/messaging/OWNERS +++ b/third_party/blink/common/messaging/OWNERS
@@ -3,8 +3,8 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/common/messaging/cloneable_message.typemap b/third_party/blink/common/messaging/cloneable_message.typemap index d84f202..c39e915b 100644 --- a/third_party/blink/common/messaging/cloneable_message.typemap +++ b/third_party/blink/common/messaging/cloneable_message.typemap
@@ -5,7 +5,7 @@ mojom = "//third_party/blink/public/mojom/messaging/cloneable_message.mojom" public_headers = [ "//third_party/blink/public/common/messaging/cloneable_message.h" ] -traits_headers = [ "//third_party/blink/public/common/messaging/cloneable_message_struct_traits.h" ] +traits_headers = [ "//third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h" ] type_mappings = [ "blink.mojom.CloneableMessage=::blink::CloneableMessage[move_only]" ]
diff --git a/third_party/blink/common/messaging/cloneable_message_struct_traits.cc b/third_party/blink/common/messaging/cloneable_message_mojom_traits.cc similarity index 98% rename from third_party/blink/common/messaging/cloneable_message_struct_traits.cc rename to third_party/blink/common/messaging/cloneable_message_mojom_traits.cc index f854aa9..b920c9e 100644 --- a/third_party/blink/common/messaging/cloneable_message_struct_traits.cc +++ b/third_party/blink/common/messaging/cloneable_message_mojom_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 "third_party/blink/public/common/messaging/cloneable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h" #include "base/containers/span.h" #include "mojo/public/cpp/base/big_buffer_mojom_traits.h"
diff --git a/third_party/blink/common/messaging/transferable_message.typemap b/third_party/blink/common/messaging/transferable_message.typemap index b111d11..11954ee 100644 --- a/third_party/blink/common/messaging/transferable_message.typemap +++ b/third_party/blink/common/messaging/transferable_message.typemap
@@ -7,7 +7,7 @@ "//third_party/blink/public/common/messaging/transferable_message.h", "//third_party/blink/public/common/messaging/message_port_channel.h", ] -traits_headers = [ "//third_party/blink/public/common/messaging/transferable_message_struct_traits.h" ] +traits_headers = [ "//third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" ] deps = [ "//skia/public/mojom",
diff --git a/third_party/blink/common/messaging/transferable_message_struct_traits.cc b/third_party/blink/common/messaging/transferable_message_mojom_traits.cc similarity index 96% rename from third_party/blink/common/messaging/transferable_message_struct_traits.cc rename to third_party/blink/common/messaging/transferable_message_mojom_traits.cc index 51e4283b..263f2b81b 100644 --- a/third_party/blink/common/messaging/transferable_message_struct_traits.cc +++ b/third_party/blink/common/messaging/transferable_message_mojom_traits.cc
@@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "third_party/blink/public/common/messaging/transferable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "base/containers/span.h" -#include "third_party/blink/public/common/messaging/cloneable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h" namespace mojo {
diff --git a/third_party/blink/common/notifications/OWNERS b/third_party/blink/common/notifications/OWNERS index cb33c42..46df373 100644 --- a/third_party/blink/common/notifications/OWNERS +++ b/third_party/blink/common/notifications/OWNERS
@@ -1,7 +1,7 @@ file://content/browser/notifications/OWNERS -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/common/notifications/notification_struct_traits.cc b/third_party/blink/common/notifications/notification_mojom_traits.cc similarity index 99% rename from third_party/blink/common/notifications/notification_struct_traits.cc rename to third_party/blink/common/notifications/notification_mojom_traits.cc index 917d87c2..67d0c4b7 100644 --- a/third_party/blink/common/notifications/notification_struct_traits.cc +++ b/third_party/blink/common/notifications/notification_mojom_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 "third_party/blink/public/common/notifications/notification_struct_traits.h" +#include "third_party/blink/public/common/notifications/notification_mojom_traits.h" namespace {
diff --git a/third_party/blink/common/notifications/notification_struct_traits_unittest.cc b/third_party/blink/common/notifications/notification_mojom_traits_unittest.cc similarity index 99% rename from third_party/blink/common/notifications/notification_struct_traits_unittest.cc rename to third_party/blink/common/notifications/notification_mojom_traits_unittest.cc index 07dfed29..59320fe 100644 --- a/third_party/blink/common/notifications/notification_struct_traits_unittest.cc +++ b/third_party/blink/common/notifications/notification_mojom_traits_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 "third_party/blink/public/common/notifications/notification_struct_traits.h" +#include "third_party/blink/public/common/notifications/notification_mojom_traits.h" #include "base/macros.h" #include "base/stl_util.h"
diff --git a/third_party/blink/public/common/BUILD.gn b/third_party/blink/public/common/BUILD.gn index 36c90aa9..edfba94 100644 --- a/third_party/blink/public/common/BUILD.gn +++ b/third_party/blink/public/common/BUILD.gn
@@ -38,7 +38,7 @@ "associated_interfaces/associated_interface_registry.h", "blob/blob_utils.h", "bluetooth/web_bluetooth_device_id.h", - "bluetooth/web_bluetooth_device_id_struct_traits.h", + "bluetooth/web_bluetooth_device_id_mojom_traits.h", "cache_storage/cache_storage_utils.h", "client_hints/client_hints.h", "common_export.h", @@ -83,15 +83,15 @@ "mediastream/media_stream_mojom_traits.h", "mediastream/media_stream_request.h", "messaging/cloneable_message.h", - "messaging/cloneable_message_struct_traits.h", + "messaging/cloneable_message_mojom_traits.h", "messaging/message_port_channel.h", "messaging/string_message_codec.h", "messaging/transferable_message.h", - "messaging/transferable_message_struct_traits.h", + "messaging/transferable_message_mojom_traits.h", "mime_util/mime_util.h", "notifications/notification_constants.h", "notifications/notification_resources.h", - "notifications/notification_struct_traits.h", + "notifications/notification_mojom_traits.h", "notifications/platform_notification_data.h", "oom_intervention/oom_intervention_types.h", "origin_policy/origin_policy.h",
diff --git a/third_party/blink/public/common/bluetooth/OWNERS b/third_party/blink/public/common/bluetooth/OWNERS index e41d91a..b69b593b 100644 --- a/third_party/blink/public/common/bluetooth/OWNERS +++ b/third_party/blink/public/common/bluetooth/OWNERS
@@ -2,8 +2,8 @@ # Changes to IPC serialization require a security review to avoid introducing # new sandbox escapes. -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_mojom_traits.h similarity index 93% rename from third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h rename to third_party/blink/public/common/bluetooth/web_bluetooth_device_id_mojom_traits.h index 838e263..745265a 100644 --- a/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_struct_traits.h +++ b/third_party/blink/public/common/bluetooth/web_bluetooth_device_id_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_MOJOM_TRAITS_H_ #include <string> @@ -36,4 +36,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_BLUETOOTH_WEB_BLUETOOTH_DEVICE_ID_MOJOM_TRAITS_H_
diff --git a/third_party/blink/public/common/feature_policy/OWNERS b/third_party/blink/public/common/feature_policy/OWNERS index 41960f51..de3e10f 100644 --- a/third_party/blink/public/common/feature_policy/OWNERS +++ b/third_party/blink/public/common/feature_policy/OWNERS
@@ -6,7 +6,7 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/common/messaging/OWNERS b/third_party/blink/public/common/messaging/OWNERS index 74991d3..ec3a481 100644 --- a/third_party/blink/public/common/messaging/OWNERS +++ b/third_party/blink/public/common/messaging/OWNERS
@@ -3,8 +3,8 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/common/messaging/cloneable_message_struct_traits.h b/third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h similarity index 95% rename from third_party/blink/public/common/messaging/cloneable_message_struct_traits.h rename to third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h index d1bb1787..5ecec03 100644 --- a/third_party/blink/public/common/messaging/cloneable_message_struct_traits.h +++ b/third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_ #include "mojo/public/cpp/base/big_buffer.h" #include "mojo/public/cpp/base/unguessable_token_mojom_traits.h" @@ -49,4 +49,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_
diff --git a/third_party/blink/public/common/messaging/transferable_message_struct_traits.h b/third_party/blink/public/common/messaging/transferable_message_mojom_traits.h similarity index 95% rename from third_party/blink/public/common/messaging/transferable_message_struct_traits.h rename to third_party/blink/public/common/messaging/transferable_message_mojom_traits.h index 41cb43e4..444b756f 100644 --- a/third_party/blink/public/common/messaging/transferable_message_struct_traits.h +++ b/third_party/blink/public/common/messaging/transferable_message_mojom_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 THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_ #include "skia/public/mojom/bitmap_skbitmap_mojom_traits.h" -#include "third_party/blink/public/common/messaging/cloneable_message_struct_traits.h" +#include "third_party/blink/public/common/messaging/cloneable_message_mojom_traits.h" #include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -60,4 +60,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_MESSAGING_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_
diff --git a/third_party/blink/public/common/notifications/OWNERS b/third_party/blink/public/common/notifications/OWNERS index cb33c42..46df373 100644 --- a/third_party/blink/public/common/notifications/OWNERS +++ b/third_party/blink/public/common/notifications/OWNERS
@@ -1,7 +1,7 @@ file://content/browser/notifications/OWNERS -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/common/notifications/notification_struct_traits.h b/third_party/blink/public/common/notifications/notification_mojom_traits.h similarity index 98% rename from third_party/blink/public/common/notifications/notification_struct_traits.h rename to third_party/blink/public/common/notifications/notification_mojom_traits.h index c9a2701..0cb169d 100644 --- a/third_party/blink/public/common/notifications/notification_struct_traits.h +++ b/third_party/blink/public/common/notifications/notification_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_MOJOM_TRAITS_H_ #include "base/containers/span.h" #include "base/strings/string16.h" @@ -172,4 +172,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_NOTIFICATIONS_NOTIFICATION_MOJOM_TRAITS_H_
diff --git a/third_party/blink/public/common/notifications/notification_types.typemap b/third_party/blink/public/common/notifications/notification_types.typemap index 9adfb765..051d850a0 100644 --- a/third_party/blink/public/common/notifications/notification_types.typemap +++ b/third_party/blink/public/common/notifications/notification_types.typemap
@@ -7,7 +7,7 @@ "//third_party/blink/public/common/notifications/notification_resources.h", "//third_party/blink/public/common/notifications/platform_notification_data.h", ] -traits_headers = [ "//third_party/blink/public/common/notifications/notification_struct_traits.h" ] +traits_headers = [ "//third_party/blink/public/common/notifications/notification_mojom_traits.h" ] deps = [ "//mojo/public/cpp/bindings", ]
diff --git a/third_party/blink/public/mojom/array_buffer/OWNERS b/third_party/blink/public/mojom/array_buffer/OWNERS index 74991d3..ec3a481 100644 --- a/third_party/blink/public/mojom/array_buffer/OWNERS +++ b/third_party/blink/public/mojom/array_buffer/OWNERS
@@ -3,8 +3,8 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/mojom/bluetooth/bluetooth.typemap b/third_party/blink/public/mojom/bluetooth/bluetooth.typemap index 60955713..40582db 100644 --- a/third_party/blink/public/mojom/bluetooth/bluetooth.typemap +++ b/third_party/blink/public/mojom/bluetooth/bluetooth.typemap
@@ -6,7 +6,7 @@ public_headers = [ "//third_party/blink/renderer/platform/wtf/text/wtf_string.h" ] traits_headers = - [ "//third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.h" ] + [ "//third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.h" ] deps = [ "//device/bluetooth", ]
diff --git a/third_party/blink/public/mojom/frame_sinks/embedded_frame_sink.mojom b/third_party/blink/public/mojom/frame_sinks/embedded_frame_sink.mojom index fdb5f1ae..586d1fe 100644 --- a/third_party/blink/public/mojom/frame_sinks/embedded_frame_sink.mojom +++ b/third_party/blink/public/mojom/frame_sinks/embedded_frame_sink.mojom
@@ -15,11 +15,9 @@ SetLocalSurfaceId(viz.mojom.LocalSurfaceId local_surface_id); }; -// Interface from browser to the embedder so it can be notified about surface -// activations. Closing this interface will destroy the corresponding -// CompositorFrameSink if one exists. +// Interface from browser to the embedder. Closing this interface will destroy +// the corresponding CompositorFrameSink if one exists. interface EmbeddedFrameSinkClient { - OnFirstSurfaceActivation(viz.mojom.SurfaceInfo surface_info); // Called when a CompositorFrameSink is created for this frame sink. // Establishes a direct connection from the embedee to the embedder. BindSurfaceEmbedder(SurfaceEmbedder& embedder);
diff --git a/third_party/blink/public/mojom/messaging/OWNERS b/third_party/blink/public/mojom/messaging/OWNERS index 74991d3..ec3a481 100644 --- a/third_party/blink/public/mojom/messaging/OWNERS +++ b/third_party/blink/public/mojom/messaging/OWNERS
@@ -3,8 +3,8 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/platform/OWNERS b/third_party/blink/public/platform/OWNERS index 323b888..e35ef74 100644 --- a/third_party/blink/public/platform/OWNERS +++ b/third_party/blink/public/platform/OWNERS
@@ -1,10 +1,8 @@ per-file *.mojom=set noparent per-file *.mojom=file://ipc/SECURITY_OWNERS -per-file *_enum_traits*.*=set noparent -per-file *_enum_traits*.*=file://ipc/SECURITY_OWNERS -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/public/web/OWNERS b/third_party/blink/public/web/OWNERS index 219e340a..f492772 100644 --- a/third_party/blink/public/web/OWNERS +++ b/third_party/blink/public/web/OWNERS
@@ -9,5 +9,5 @@ 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 *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index 50ca81a..db9a37d 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -1208,6 +1208,7 @@ "frame/mhtml_loading_test.cc", "frame/origins_using_features_test.cc", "frame/performance_monitor_test.cc", + "frame/reporting_context_test.cc", "frame/root_frame_viewport_test.cc", "frame/rotation_viewport_anchor_test.cc", "frame/use_counter_helper_test.cc", @@ -1428,7 +1429,7 @@ "loader/threadable_loader_test.cc", "loader/threaded_icon_loader_test.cc", "loader/web_associated_url_loader_impl_test.cc", - "messaging/blink_transferable_message_struct_traits_test.cc", + "messaging/blink_transferable_message_mojom_traits_test.cc", "origin_trials/origin_trial_context_test.cc", "page/autoscroll_controller_test.cc", "page/chrome_client_impl_test.cc",
diff --git a/third_party/blink/renderer/core/DEPS b/third_party/blink/renderer/core/DEPS index 98634ef..7432503 100644 --- a/third_party/blink/renderer/core/DEPS +++ b/third_party/blink/renderer/core/DEPS
@@ -117,4 +117,7 @@ "html_media_element_test.cc": [ "+base/test/gtest_util.h", ], + "element_test.cc": [ + "+third_party/blink/renderer/core/exported/web_plugin_container_impl.h" + ] }
diff --git a/third_party/blink/renderer/core/css/css.dict b/third_party/blink/renderer/core/css/css.dict index dbab53c..c4f07d3 100644 --- a/third_party/blink/renderer/core/css/css.dict +++ b/third_party/blink/renderer/core/css/css.dict
@@ -912,6 +912,8 @@ "light" "dark" "active" +"linktext" +"visitedtext" # at-rules "@charset"
diff --git a/third_party/blink/renderer/core/css/css_value_keywords.json5 b/third_party/blink/renderer/core/css/css_value_keywords.json5 index 4e1c5c6..bb1dd5a9 100644 --- a/third_party/blink/renderer/core/css/css_value_keywords.json5 +++ b/third_party/blink/renderer/core/css/css_value_keywords.json5
@@ -197,6 +197,7 @@ "inactivecaptiontext", "infobackground", "infotext", + "linktext", "menutext", "scrollbar", "threeddarkshadow", @@ -204,6 +205,7 @@ "threedhighlight", "threedlightshadow", "threedshadow", + "visitedtext", "window", "windowframe", "windowtext",
diff --git a/third_party/blink/renderer/core/css/parser/css.proto b/third_party/blink/renderer/core/css/parser/css.proto index ff6a0a5b..5df03cc 100644 --- a/third_party/blink/renderer/core/css/parser/css.proto +++ b/third_party/blink/renderer/core/css/parser/css.proto
@@ -2296,7 +2296,9 @@ INSET = 723; MEDIUMAQUAMARINE = 724; SCROLL = 725; - INVALID_VALUE = 726; + LINKTEXT = 726; + VISITEDTEXT = 727; + INVALID_VALUE = 728; }; optional ValueId value_id = 4;
diff --git a/third_party/blink/renderer/core/css/parser/css_parser.cc b/third_party/blink/renderer/core/css/parser/css_parser.cc index 659c213..5c25803 100644 --- a/third_party/blink/renderer/core/css/parser/css_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_parser.cc
@@ -258,6 +258,10 @@ if (!StyleColor::IsSystemColor(id)) return false; + if (!RuntimeEnabledFeatures::LinkSystemColorsEnabled() && + (id == CSSValueID::kLinktext || id == CSSValueID::kVisitedtext)) { + return false; + } color = LayoutTheme::GetTheme().SystemColor(id); return true; }
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc b/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc index bdb30541..30c6493 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc
@@ -824,7 +824,13 @@ if (StyleColor::IsColorKeyword(id)) { if (!isValueAllowedInMode(id, css_parser_mode)) return nullptr; - return ConsumeIdent(range); + CSSIdentifierValue* color = ConsumeIdent(range); + if (!RuntimeEnabledFeatures::LinkSystemColorsEnabled() && + (color->GetValueID() == CSSValueID::kLinktext || + color->GetValueID() == CSSValueID::kVisitedtext)) { + return nullptr; + } + return color; } RGBA32 color = Color::kTransparent; if (!ParseHexColor(range, color, accept_quirky_colors) &&
diff --git a/third_party/blink/renderer/core/css/style_color.cc b/third_party/blink/renderer/core/css/style_color.cc index 6b7bb401..8bf8203e 100644 --- a/third_party/blink/renderer/core/css/style_color.cc +++ b/third_party/blink/renderer/core/css/style_color.cc
@@ -48,7 +48,8 @@ bool StyleColor::IsSystemColor(CSSValueID id) { return (id >= CSSValueID::kActiveborder && id <= CSSValueID::kWindowtext) || - id == CSSValueID::kMenu; + id == CSSValueID::kMenu || id == CSSValueID::kLinktext || + id == CSSValueID::kVisitedtext; } } // namespace blink
diff --git a/third_party/blink/renderer/core/dom/OWNERS b/third_party/blink/renderer/core/dom/OWNERS index 0c86b53..5f9506d 100644 --- a/third_party/blink/renderer/core/dom/OWNERS +++ b/third_party/blink/renderer/core/dom/OWNERS
@@ -1,7 +1,7 @@ masonfreed@chromium.org -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index deb02bcf..1086d29 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -8222,8 +8222,8 @@ (disposition == mojom::FeaturePolicyDisposition::kReport ? "report" : "enforce")); - Report* report = MakeGarbageCollected<Report>("feature-policy-violation", - Url().GetString(), body); + Report* report = MakeGarbageCollected<Report>( + ReportType::kFeaturePolicyViolation, Url().GetString(), body); // Send the feature policy violation report to any ReportingObservers. auto* reporting_context = ReportingContext::From(this);
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 505df0d..5d93cc5d 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -2799,6 +2799,7 @@ NestingLevelIncrementer slot_assignment_recalc_forbidden_scope( GetDocument().SlotAssignmentRecalcForbiddenRecursionDepth()); #endif + HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose; EventDispatchForbiddenScope assert_no_event_dispatch; ScriptForbiddenScope forbid_script;
diff --git a/third_party/blink/renderer/core/dom/element_test.cc b/third_party/blink/renderer/core/dom/element_test.cc index 000db0c..c3215cb 100644 --- a/third_party/blink/renderer/core/dom/element_test.cc +++ b/third_party/blink/renderer/core/dom/element_test.cc
@@ -5,17 +5,22 @@ #include "third_party/blink/renderer/core/dom/element.h" #include <memory> + #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/web/web_plugin.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_token_list.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/editing/testing/editing_test_base.h" +#include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/geometry/dom_rect.h" #include "third_party/blink/renderer/core/html/html_html_element.h" +#include "third_party/blink/renderer/core/html/html_plugin_element.h" #include "third_party/blink/renderer/core/layout/layout_box_model_object.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" +#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h" namespace blink { @@ -464,4 +469,75 @@ EXPECT_FALSE(document.getElementById("inner-option")->GetComputedStyle()); } +template <> +struct DowncastTraits<HTMLPlugInElement> { + static bool AllowFrom(const Node& n) { return IsHTMLPlugInElement(n); } +}; + +// A fake plugin which will assert that script is allowed in Destroy. +class ScriptOnDestroyPlugin : public GarbageCollected<ScriptOnDestroyPlugin>, + public WebPlugin { + public: + bool Initialize(WebPluginContainer* container) override { + container_ = container; + return true; + } + void Destroy() override { + destroy_called_ = true; + ASSERT_FALSE(ScriptForbiddenScope::IsScriptForbidden()); + } + WebPluginContainer* Container() const override { return container_; } + + void UpdateAllLifecyclePhases(WebWidget::LifecycleUpdateReason) override {} + void Paint(cc::PaintCanvas*, const WebRect&) override {} + void UpdateGeometry(const WebRect&, + const WebRect&, + const WebRect&, + bool) override {} + void UpdateFocus(bool, WebFocusType) override {} + void UpdateVisibility(bool) override {} + WebInputEventResult HandleInputEvent(const WebCoalescedInputEvent&, + WebCursorInfo&) override { + return {}; + } + void DidReceiveResponse(const WebURLResponse&) override {} + void DidReceiveData(const char* data, size_t data_length) override {} + void DidFinishLoading() override {} + void DidFailLoading(const WebURLError&) override {} + + void Trace(blink::Visitor*) {} + + bool DestroyCalled() const { return destroy_called_; } + + private: + WebPluginContainer* container_; + bool destroy_called_ = false; +}; + +TEST_F(ElementTest, CreateAndAttachShadowRootSuspendsPluginDisposal) { + Document& document = GetDocument(); + SetBodyContent(R"HTML( + <div id=target> + <embed id=plugin type=application/x-blink-text-plugin></embed> + </div> + )HTML"); + + // Set the plugin element up to have the ScriptOnDestroy plugin. + auto* plugin_element = + DynamicTo<HTMLPlugInElement>(document.getElementById("plugin")); + ASSERT_TRUE(plugin_element); + + auto* plugin = MakeGarbageCollected<ScriptOnDestroyPlugin>(); + auto* plugin_container = + MakeGarbageCollected<WebPluginContainerImpl>(*plugin_element, plugin); + plugin->Initialize(plugin_container); + plugin_element->SetEmbeddedContentView(plugin_container); + + // Now create a shadow root on target, which should cause the plugin to be + // destroyed. Test passes if we pass the script forbidden check in the plugin. + auto* target = document.getElementById("target"); + target->CreateUserAgentShadowRoot(); + ASSERT_TRUE(plugin->DestroyCalled()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/BUILD.gn b/third_party/blink/renderer/core/frame/BUILD.gn index cd9e30c..c9e2dac 100644 --- a/third_party/blink/renderer/core/frame/BUILD.gn +++ b/third_party/blink/renderer/core/frame/BUILD.gn
@@ -144,6 +144,7 @@ "remote_frame_owner.h", "remote_frame_view.cc", "remote_frame_view.h", + "report.cc", "report.h", "report_body.h", "reporting_context.cc",
diff --git a/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc b/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc index 2521361..cff5ce3 100644 --- a/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc +++ b/third_party/blink/renderer/core/frame/csp/execution_context_csp_delegate.cc
@@ -173,8 +173,8 @@ // Construct and route the report to the ReportingContext, to be observed // by any ReportingObservers. auto* body = MakeGarbageCollected<CSPViolationReportBody>(violation_data); - Report* observed_report = - MakeGarbageCollected<Report>("csp-violation", Url().GetString(), body); + Report* observed_report = MakeGarbageCollected<Report>( + ReportType::kCSPViolation, Url().GetString(), body); ReportingContext::From(document)->QueueReport( observed_report, use_reporting_api ? report_endpoints : Vector<String>());
diff --git a/third_party/blink/renderer/core/frame/deprecation.cc b/third_party/blink/renderer/core/frame/deprecation.cc index 323bd90..4704e51 100644 --- a/third_party/blink/renderer/core/frame/deprecation.cc +++ b/third_party/blink/renderer/core/frame/deprecation.cc
@@ -812,7 +812,7 @@ DeprecationReportBody* body = MakeGarbageCollected<DeprecationReportBody>( info.id, removal_date, info.message); Report* report = MakeGarbageCollected<Report>( - "deprecation", document->Url().GetString(), body); + ReportType::kDeprecation, document->Url().GetString(), body); // Send the deprecation report to the Reporting API and any // ReportingObservers.
diff --git a/third_party/blink/renderer/core/frame/intervention.cc b/third_party/blink/renderer/core/frame/intervention.cc index dd2aedea..42e36f1 100644 --- a/third_party/blink/renderer/core/frame/intervention.cc +++ b/third_party/blink/renderer/core/frame/intervention.cc
@@ -37,7 +37,7 @@ InterventionReportBody* body = MakeGarbageCollected<InterventionReportBody>(id, message); Report* report = MakeGarbageCollected<Report>( - "intervention", document->Url().GetString(), body); + ReportType::kIntervention, document->Url().GetString(), body); // Send the intervention report to the Reporting API and any // ReportingObservers.
diff --git a/third_party/blink/renderer/core/frame/report.cc b/third_party/blink/renderer/core/frame/report.cc new file mode 100644 index 0000000..38b7c5e0 --- /dev/null +++ b/third_party/blink/renderer/core/frame/report.cc
@@ -0,0 +1,14 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/frame/report.h" + +namespace blink { + +constexpr const char ReportType::kDeprecation[]; +constexpr const char ReportType::kFeaturePolicyViolation[]; +constexpr const char ReportType::kIntervention[]; +constexpr const char ReportType::kCSPViolation[]; + +} // namespace blink
diff --git a/third_party/blink/renderer/core/frame/report.h b/third_party/blink/renderer/core/frame/report.h index 5163422..3aba915a 100644 --- a/third_party/blink/renderer/core/frame/report.h +++ b/third_party/blink/renderer/core/frame/report.h
@@ -5,11 +5,22 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REPORT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REPORT_H_ +#include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/frame/report_body.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { +// The constants are implemented as static members of a class to have an unique +// address and not violate ODR. +struct CORE_EXPORT ReportType { + static constexpr const char kDeprecation[] = "deprecation"; + static constexpr const char kFeaturePolicyViolation[] = + "feature-policy-violation"; + static constexpr const char kIntervention[] = "intervention"; + static constexpr const char kCSPViolation[] = "csp-violation"; +}; + class CORE_EXPORT Report : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO();
diff --git a/third_party/blink/renderer/core/frame/reporting_context.cc b/third_party/blink/renderer/core/frame/reporting_context.cc index 08124e6..b5b640c 100644 --- a/third_party/blink/renderer/core/frame/reporting_context.cc +++ b/third_party/blink/renderer/core/frame/reporting_context.cc
@@ -90,11 +90,11 @@ const String& type = report->type(); WebFeature feature; - if (type == "deprecation") { + if (type == ReportType::kDeprecation) { feature = WebFeature::kDeprecationReport; - } else if (type == "feature-policy") { + } else if (type == ReportType::kFeaturePolicyViolation) { feature = WebFeature::kFeaturePolicyReport; - } else if (type == "intervention") { + } else if (type == ReportType::kIntervention) { feature = WebFeature::kInterventionReport; } else { return; @@ -115,10 +115,9 @@ void ReportingContext::SendToReportingAPI(Report* report, const String& endpoint) const { const String& type = report->type(); - if (!(type == "csp-violation" || - type == "deprecation" || - type == "feature-policy-violation" || - type == "intervention")) { + if (!(type == ReportType::kCSPViolation || type == ReportType::kDeprecation || + type == ReportType::kFeaturePolicyViolation || + type == ReportType::kIntervention)) { return; } @@ -133,7 +132,7 @@ column_number = 0; KURL url = KURL(report->url()); - if (type == "csp-violation") { + if (type == ReportType::kCSPViolation) { // Send the CSP violation report. const CSPViolationReportBody* body = static_cast<CSPViolationReportBody*>(report->body()); @@ -151,7 +150,7 @@ body->statusCode(), line_number, column_number); - } else if (type == "deprecation") { + } else if (type == ReportType::kDeprecation) { // Send the deprecation report. const DeprecationReportBody* body = static_cast<DeprecationReportBody*>(report->body()); @@ -162,14 +161,14 @@ GetReportingService()->QueueDeprecationReport( url, body->id(), anticipated_removal, body->message(), body->sourceFile(), line_number, column_number); - } else if (type == "feature-policy-violation") { + } else if (type == ReportType::kFeaturePolicyViolation) { // Send the feature policy violation report. const FeaturePolicyViolationReportBody* body = static_cast<FeaturePolicyViolationReportBody*>(report->body()); GetReportingService()->QueueFeaturePolicyViolationReport( url, body->featureId(), body->disposition(), "Feature policy violation", body->sourceFile(), line_number, column_number); - } else if (type == "intervention") { + } else if (type == ReportType::kIntervention) { // Send the intervention report. const InterventionReportBody* body = static_cast<InterventionReportBody*>(report->body());
diff --git a/third_party/blink/renderer/core/frame/reporting_context_test.cc b/third_party/blink/renderer/core/frame/reporting_context_test.cc new file mode 100644 index 0000000..eef2e76 --- /dev/null +++ b/third_party/blink/renderer/core/frame/reporting_context_test.cc
@@ -0,0 +1,45 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/frame/reporting_context.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/core/frame/deprecation_report_body.h" +#include "third_party/blink/renderer/core/frame/report.h" +#include "third_party/blink/renderer/core/testing/page_test_base.h" +#include "third_party/blink/renderer/platform/testing/histogram_tester.h" + +namespace blink { + +class ReportingContextTest : public testing::Test { + protected: + ReportingContextTest() = default; + + ~ReportingContextTest() override = default; + + private: + DISALLOW_COPY_AND_ASSIGN(ReportingContextTest); +}; + +TEST_F(ReportingContextTest, CountQueuedReports) { + HistogramTester tester; + auto dummy_page_holder = std::make_unique<DummyPageHolder>(); + tester.ExpectTotalCount("Blink.UseCounter.Features.DeprecationReport", 0); + // Checking the feature state with reporting intent should record a potential + // violation. + DeprecationReportBody* body = MakeGarbageCollected<DeprecationReportBody>( + "FeatureId", 2e9, "Test report"); + Report* report = MakeGarbageCollected<Report>( + "deprecation", dummy_page_holder->GetDocument().Url().GetString(), body); + + // Send the deprecation report to the Reporting API and any + // ReportingObservers. + ReportingContext::From(&dummy_page_holder->GetDocument()) + ->QueueReport(report); + // tester.ExpectTotalCount("Blink.UseCounter.Features.DeprecationReport", 1); + // The potential violation for an already recorded violation does not count + // again. +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/inspector/browser_protocol.pdl b/third_party/blink/renderer/core/inspector/browser_protocol.pdl index fbdf20f..69900726 100644 --- a/third_party/blink/renderer/core/inspector/browser_protocol.pdl +++ b/third_party/blink/renderer/core/inspector/browser_protocol.pdl
@@ -7109,12 +7109,15 @@ type Credential extends object properties binary credentialId - # SHA-256 hash of the Relying Party ID the credential is scoped to. Must - # be 32 bytes long. - # See https://w3c.github.io/webauthn/#rpidhash - binary rpIdHash - # The private key in PKCS#8 format. + boolean isResidentCredential + # Relying Party ID the credential is scoped to. Must be set when adding a + # credential. + optional string rpId + # The ECDSA P-256 private key in PKCS#8 format. binary privateKey + # An opaque byte sequence with a maximum size of 64 bytes mapping the + # credential to a specific user. + optional binary userHandle # Signature counter. This is incremented by one for each successful # assertion. # See https://w3c.github.io/webauthn/#signature-counter
diff --git a/third_party/blink/renderer/core/layout/layout_theme.cc b/third_party/blink/renderer/core/layout/layout_theme.cc index 206ee6ef..8bacc88f 100644 --- a/third_party/blink/renderer/core/layout/layout_theme.cc +++ b/third_party/blink/renderer/core/layout/layout_theme.cc
@@ -613,6 +613,8 @@ return 0xFFFBFCC5; case CSSValueID::kInfotext: return 0xFF000000; + case CSSValueID::kLinktext: + return 0xFF0000EE; case CSSValueID::kMenu: return 0xFFC0C0C0; case CSSValueID::kMenutext: @@ -631,6 +633,8 @@ return 0xFFC0C0C0; case CSSValueID::kThreedshadow: return 0xFF888888; + case CSSValueID::kVisitedtext: + return 0xFF551A8B; case CSSValueID::kWindow: return 0xFFFFFFFF; case CSSValueID::kWindowframe:
diff --git a/third_party/blink/renderer/core/layout/layout_theme_win.cc b/third_party/blink/renderer/core/layout/layout_theme_win.cc index c5dff3c9..62e366d 100644 --- a/third_party/blink/renderer/core/layout/layout_theme_win.cc +++ b/third_party/blink/renderer/core/layout/layout_theme_win.cc
@@ -42,6 +42,10 @@ case CSSValueID::kHighlighttext: system_index = COLOR_HIGHLIGHTTEXT; break; + case CSSValueID::kLinktext: + case CSSValueID::kVisitedtext: + system_index = COLOR_HOTLIGHT; + break; case CSSValueID::kWindow: system_index = COLOR_WINDOW; break;
diff --git a/third_party/blink/renderer/core/messaging/BUILD.gn b/third_party/blink/renderer/core/messaging/BUILD.gn index df199700..ec799e52 100644 --- a/third_party/blink/renderer/core/messaging/BUILD.gn +++ b/third_party/blink/renderer/core/messaging/BUILD.gn
@@ -8,12 +8,12 @@ sources = [ "blink_cloneable_message.cc", "blink_cloneable_message.h", - "blink_cloneable_message_struct_traits.cc", - "blink_cloneable_message_struct_traits.h", + "blink_cloneable_message_mojom_traits.cc", + "blink_cloneable_message_mojom_traits.h", "blink_transferable_message.cc", "blink_transferable_message.h", - "blink_transferable_message_struct_traits.cc", - "blink_transferable_message_struct_traits.h", + "blink_transferable_message_mojom_traits.cc", + "blink_transferable_message_mojom_traits.h", "message_channel.cc", "message_channel.h", "message_port.cc",
diff --git a/third_party/blink/renderer/core/messaging/OWNERS b/third_party/blink/renderer/core/messaging/OWNERS index 5d0dbdf1..be11b2ec 100644 --- a/third_party/blink/renderer/core/messaging/OWNERS +++ b/third_party/blink/renderer/core/messaging/OWNERS
@@ -1,8 +1,8 @@ mek@chromium.org jbroman@chromium.org -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap b/third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap index 65a49cc6..c74c9e8 100644 --- a/third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap +++ b/third_party/blink/renderer/core/messaging/blink_cloneable_message.typemap
@@ -5,7 +5,7 @@ mojom = "//third_party/blink/public/mojom/messaging/cloneable_message.mojom" public_headers = [ "//third_party/blink/renderer/core/messaging/blink_cloneable_message.h" ] -traits_headers = [ "//third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h" ] +traits_headers = [ "//third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h" ] deps = [ "//mojo/public/cpp/bindings",
diff --git a/third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.cc b/third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.cc similarity index 98% rename from third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.cc rename to third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.cc index 9c00950e..47d739f 100644 --- a/third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.cc +++ b/third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_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 "third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h" +#include "third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h" #include "mojo/public/cpp/base/big_buffer_mojom_traits.h" #include "third_party/blink/renderer/platform/blob/blob_data.h"
diff --git a/third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h b/third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h similarity index 95% rename from third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h rename to third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h index 8ff4d9a..788b2a13 100644 --- a/third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h +++ b/third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_ #include "mojo/public/cpp/base/big_buffer.h" #include "mojo/public/cpp/base/unguessable_token_mojom_traits.h" @@ -13,7 +13,7 @@ #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/messaging/blink_cloneable_message.h" -#include "third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h" +#include "third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h" namespace mojo { @@ -53,4 +53,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_CLONEABLE_MESSAGE_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/core/messaging/blink_transferable_message.typemap b/third_party/blink/renderer/core/messaging/blink_transferable_message.typemap index 154339b..eee20e4 100644 --- a/third_party/blink/renderer/core/messaging/blink_transferable_message.typemap +++ b/third_party/blink/renderer/core/messaging/blink_transferable_message.typemap
@@ -6,7 +6,7 @@ public_headers = [ "//third_party/blink/renderer/core/messaging/blink_transferable_message.h", ] -traits_headers = [ "//third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h" ] +traits_headers = [ "//third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h" ] deps = [ "//mojo/public/cpp/bindings",
diff --git a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.cc similarity index 98% rename from third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc rename to third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.cc index fc8d00f..e426bbf 100644 --- a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.cc +++ b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_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 "third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h" +#include "third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h" #include "mojo/public/cpp/base/big_buffer_mojom_traits.h" #include "third_party/blink/renderer/core/imagebitmap/image_bitmap.h"
diff --git a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h similarity index 96% rename from third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h rename to third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h index ae70605..e08fedc5 100644 --- a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h +++ b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_ #include "mojo/public/cpp/bindings/array_traits_wtf_vector.h" #include "skia/public/mojom/bitmap_skbitmap_mojom_traits.h" @@ -11,7 +11,7 @@ #include "third_party/blink/public/mojom/messaging/transferable_message.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/core/messaging/blink_cloneable_message_struct_traits.h" +#include "third_party/blink/renderer/core/messaging/blink_cloneable_message_mojom_traits.h" #include "third_party/blink/renderer/core/messaging/blink_transferable_message.h" namespace mojo { @@ -88,4 +88,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MESSAGING_BLINK_TRANSFERABLE_MESSAGE_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc similarity index 98% rename from third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc rename to third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.cc index db72b274..c70aa78 100644 --- a/third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits_test.cc +++ b/third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits_test.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 "third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h" +#include "third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" @@ -112,7 +112,7 @@ ASSERT_EQ(originalContentsData, deserialized_contents.Data()); // The original ArrayBufferContents should be neutered. - ASSERT_EQ(NULL, v8_buffer->GetContents().Data()); + ASSERT_EQ(nullptr, v8_buffer->GetContents().Data()); ASSERT_TRUE(original_array_buffer->IsNeutered()); }
diff --git a/third_party/blink/renderer/core/messaging/message_port.cc b/third_party/blink/renderer/core/messaging/message_port.cc index fd635f6..62ca430 100644 --- a/third_party/blink/renderer/core/messaging/message_port.cc +++ b/third_party/blink/renderer/core/messaging/message_port.cc
@@ -37,7 +37,7 @@ #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/user_activation.h" #include "third_party/blink/renderer/core/inspector/thread_debugger.h" -#include "third_party/blink/renderer/core/messaging/blink_transferable_message_struct_traits.h" +#include "third_party/blink/renderer/core/messaging/blink_transferable_message_mojom_traits.h" #include "third_party/blink/renderer/core/messaging/post_message_options.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h"
diff --git a/third_party/blink/renderer/devtools/front_end/cm_web_modes/css.js b/third_party/blink/renderer/devtools/front_end/cm_web_modes/css.js index 05742c5..4855363 100644 --- a/third_party/blink/renderer/devtools/front_end/cm_web_modes/css.js +++ b/third_party/blink/renderer/devtools/front_end/cm_web_modes/css.js
@@ -630,7 +630,7 @@ "katakana", "katakana-iroha", "keep-all", "khmer", "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", - "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "line-through", "linear", "linear-gradient", "lines", "linktext", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", @@ -681,7 +681,7 @@ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", - "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "visibleStroke", "visitedtext", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small" ], valueKeywords = keySet(valueKeywords_);
diff --git a/third_party/blink/renderer/modules/mediarecorder/DEPS b/third_party/blink/renderer/modules/mediarecorder/DEPS index 2343749c..2e96f7b 100644 --- a/third_party/blink/renderer/modules/mediarecorder/DEPS +++ b/third_party/blink/renderer/modules/mediarecorder/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+base/containers/queue.h", "+base/strings/string_piece.h", "+base/task_runner_util.h", "+base/threading/thread_task_runner_handle.h",
diff --git a/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc index 62dcfd7e..8da2d01b 100644 --- a/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc +++ b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.cc
@@ -107,7 +107,7 @@ vea_requested_input_coded_size_ = input_coded_size; output_buffers_.clear(); - Deque<std::unique_ptr<InputBuffer>>().Swap(input_buffers_); + base::queue<std::unique_ptr<InputBuffer>>().swap(input_buffers_); for (int i = 0; i < kVEAEncoderOutputBufferCount; ++i) { std::unique_ptr<base::SharedMemory> shm = @@ -139,7 +139,9 @@ data.append(static_cast<char*>(output_buffer->memory()), metadata.payload_size_bytes); - const auto front_frame = frames_in_encode_.TakeFirst(); + const auto front_frame = frames_in_encode_.front(); + frames_in_encode_.pop(); + PostCrossThreadTask( *origin_task_runner_.get(), FROM_HERE, CrossThreadBindOnce( @@ -173,7 +175,7 @@ void VEAEncoder::FrameFinished(std::unique_ptr<InputBuffer> shm) { DVLOG(3) << __func__; DCHECK(encoding_task_runner_->BelongsToCurrentThread()); - input_buffers_.push_back(std::move(shm)); + input_buffers_.push(std::move(shm)); } void VEAEncoder::EncodeOnEncodingTaskRunner(scoped_refptr<VideoFrame> frame, @@ -230,7 +232,8 @@ input_buffer->mapping = input_buffer->region.Map(); } else { do { - input_buffer = input_buffers_.TakeFirst(); + input_buffer = std::move(input_buffers_.front()); + input_buffers_.pop(); } while (!input_buffers_.empty() && input_buffer->mapping.size() < desired_mapped_size); if (!input_buffer || input_buffer->mapping.size() < desired_mapped_size) @@ -264,7 +267,7 @@ video_frame->stride(media::VideoFrame::kVPlane), input_visible_size_.width(), input_visible_size_.height()); } - frames_in_encode_.push_back(std::make_pair( + frames_in_encode_.push(std::make_pair( media::WebmMuxer::VideoParameters(frame), capture_timestamp)); video_encoder_->Encode(video_frame, force_next_frame_to_be_keyframe_);
diff --git a/third_party/blink/renderer/modules/mediarecorder/vea_encoder.h b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.h index 977af5b5..743ebe0 100644 --- a/third_party/blink/renderer/modules/mediarecorder/vea_encoder.h +++ b/third_party/blink/renderer/modules/mediarecorder/vea_encoder.h
@@ -5,10 +5,10 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VEA_ENCODER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIARECORDER_VEA_ENCODER_H_ +#include "base/containers/queue.h" #include "base/single_thread_task_runner.h" #include "media/video/video_encode_accelerator.h" #include "third_party/blink/renderer/modules/mediarecorder/video_track_recorder.h" -#include "third_party/blink/renderer/platform/wtf/deque.h" #include "third_party/blink/renderer/platform/wtf/vector.h" #include "ui/gfx/geometry/size.h" @@ -88,7 +88,8 @@ Vector<std::unique_ptr<base::SharedMemory>> output_buffers_; // Shared memory buffers for output with the VEA as FIFO. - Deque<std::unique_ptr<InputBuffer>> input_buffers_; + // TODO(crbug.com/960665): Replace with a WTF equivalent. + base::queue<std::unique_ptr<InputBuffer>> input_buffers_; // Tracks error status. bool error_notified_; @@ -103,7 +104,8 @@ gfx::Size vea_requested_input_coded_size_; // Frames and corresponding timestamps in encode as FIFO. - Deque<VideoParamsAndTimestamp> frames_in_encode_; + // TODO(crbug.com/960665): Replace with a WTF equivalent. + base::queue<VideoParamsAndTimestamp> frames_in_encode_; // Number of encoded frames produced consecutively without a keyframe. uint32_t num_frames_after_keyframe_;
diff --git a/third_party/blink/renderer/modules/mediasession/OWNERS b/third_party/blink/renderer/modules/mediasession/OWNERS index 973b6a5f..6b7ed4a 100644 --- a/third_party/blink/renderer/modules/mediasession/OWNERS +++ b/third_party/blink/renderer/modules/mediasession/OWNERS
@@ -1,8 +1,8 @@ foolip@chromium.org mlamouri@chromium.org -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS # TEAM: media-dev@chromium.org # COMPONENT: Blink>Media>Session
diff --git a/third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h b/third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h index 3cfeaca1..1267bc7c 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h +++ b/third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h
@@ -49,7 +49,24 @@ void DidCreateAudioParam(AudioParam*) {} void WillDestroyAudioParam(AudioParam*) {} - // Notify an associated inspector agent when a BaseAudioContext is changed. + // Graph connection events: notifies an associated inspector agent about + // when a connection between graph objects happens. + void DidConnectNodes(AudioNode* source_node, + AudioNode* destination_node, + unsigned source_output_index = 0, + unsigned destination_input_index = 0) {} + void DidDisconnectNodes(AudioNode* source_node, + AudioNode* destination_node = nullptr, + unsigned source_output_index = 0, + unsigned destination_input_index = 0) {} + void DidConnectNodeParam(AudioNode* source_node, + AudioParam* destination_param, + unsigned source_output_index = 0) {} + void DidDisconnectNodeParam(AudioNode* source_node, + AudioParam* destination_param, + unsigned source_output_index = 0) {} + + // Notifies an associated inspector agent when a BaseAudioContext is changed. void DidChangeBaseAudioContext(BaseAudioContext*); BaseAudioContext* GetContextById(const String contextId);
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.cc b/third_party/blink/renderer/modules/webaudio/audio_node.cc index 1125dfa..c04d9c5d 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node.cc
@@ -742,6 +742,8 @@ Handler().UpdatePullStatusIfNeeded(); + GraphTracer().DidConnectNodes(this, destination, output_index, input_index); + return destination; } @@ -784,6 +786,8 @@ connected_params_[output_index]->insert(param); Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidConnectNodeParam(this, param, output_index); } void AudioNode::DisconnectAllFromOutput(unsigned output_index) { @@ -825,6 +829,8 @@ DisconnectAllFromOutput(i); Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodes(this); } void AudioNode::disconnect(unsigned output_index, @@ -846,6 +852,8 @@ DisconnectAllFromOutput(output_index); Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodes(this, nullptr, output_index); } void AudioNode::disconnect(AudioNode* destination, @@ -876,6 +884,8 @@ } Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodes(this, destination); } void AudioNode::disconnect(AudioNode* destination, @@ -914,6 +924,8 @@ } Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodes(this, destination, output_index); } void AudioNode::disconnect(AudioNode* destination, @@ -955,6 +967,9 @@ } Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodes( + this, destination, output_index, input_index); } void AudioNode::disconnect(AudioParam* destination_param, @@ -981,6 +996,8 @@ } Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodeParam(this, destination_param); } void AudioNode::disconnect(AudioParam* destination_param, @@ -1010,6 +1027,8 @@ } Handler().UpdatePullStatusIfNeeded(); + + GraphTracer().DidDisconnectNodeParam(this, destination_param, output_index); } unsigned AudioNode::numberOfInputs() const {
diff --git a/third_party/blink/renderer/modules/xr/OWNERS b/third_party/blink/renderer/modules/xr/OWNERS index 2789c1b..04300e66 100644 --- a/third_party/blink/renderer/modules/xr/OWNERS +++ b/third_party/blink/renderer/modules/xr/OWNERS
@@ -1,6 +1,5 @@ alcooper@chromium.org bajones@chromium.org -billorr@chromium.org klausw@chromium.org # TEAM: xr-dev@chromium.org
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 2b9e621..2ad37fa 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -125,6 +125,7 @@ configs = [ "//third_party/blink/renderer:config", "//third_party/blink/renderer:inside_blink", + "//build/config/compiler:noshadowing", # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. "//build/config/compiler:no_size_t_to_int_warning", @@ -1211,8 +1212,8 @@ "mhtml/shared_buffer_chunk_reader.cc", "mhtml/shared_buffer_chunk_reader.h", "mojo/big_string_mojom_traits.h", - "mojo/bluetooth_struct_traits.cc", - "mojo/bluetooth_struct_traits.h", + "mojo/bluetooth_mojom_traits.cc", + "mojo/bluetooth_mojom_traits.h", "mojo/canonical_cookie_mojom_traits.cc", "mojo/canonical_cookie_mojom_traits.h", "mojo/fetch_api_request_headers_mojom_traits.h", @@ -1762,7 +1763,7 @@ "media/webaudiosourceprovider_impl_test.cc", "mhtml/mhtml_parser_test.cc", "mojo/big_string_mojom_traits_test.cc", - "mojo/geometry_struct_traits_test.cc", + "mojo/geometry_mojom_traits_test.cc", "mojo/interface_invalidator_test.cc", "mojo/kurl_security_origin_test.cc", "mojo/string16_mojom_traits_test.cc",
diff --git a/third_party/blink/renderer/platform/blob/BUILD.gn b/third_party/blink/renderer/platform/blob/BUILD.gn index 506bb0f4..50a8ac77 100644 --- a/third_party/blink/renderer/platform/blob/BUILD.gn +++ b/third_party/blink/renderer/platform/blob/BUILD.gn
@@ -27,8 +27,8 @@ "blob_data.h", "blob_url.cc", "blob_url.h", - "serialized_blob_struct_traits.cc", - "serialized_blob_struct_traits.h", + "serialized_blob_mojom_traits.cc", + "serialized_blob_mojom_traits.h", ] deps = [
diff --git a/third_party/blink/renderer/platform/blob/OWNERS b/third_party/blink/renderer/platform/blob/OWNERS index 5866bae8..03df55f 100644 --- a/third_party/blink/renderer/platform/blob/OWNERS +++ b/third_party/blink/renderer/platform/blob/OWNERS
@@ -1,7 +1,7 @@ file://storage/browser/blob/OWNERS -per-file *_struct_traits*.*=set noparent -per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS +per-file *_mojom_traits*.*=set noparent +per-file *_mojom_traits*.*=file://ipc/SECURITY_OWNERS per-file *.typemap=set noparent per-file *.typemap=file://ipc/SECURITY_OWNERS
diff --git a/third_party/blink/renderer/platform/blob/serialized_blob.typemap b/third_party/blink/renderer/platform/blob/serialized_blob.typemap index 251381d..e1dbe4d 100644 --- a/third_party/blink/renderer/platform/blob/serialized_blob.typemap +++ b/third_party/blink/renderer/platform/blob/serialized_blob.typemap
@@ -5,7 +5,7 @@ mojom = "//third_party/blink/public/mojom/blob/serialized_blob.mojom" public_headers = [ "//third_party/blink/renderer/platform/blob/blob_data.h" ] traits_headers = [ - "//third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h", + "//third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h", ] deps = [
diff --git a/third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.cc b/third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.cc similarity index 97% rename from third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.cc rename to third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.cc index 50bdc957a..c58bb4ca 100644 --- a/third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.cc +++ b/third_party/blink/renderer/platform/blob/serialized_blob_mojom_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 "third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h" +#include "third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h" namespace mojo {
diff --git a/third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h b/third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h similarity index 96% rename from third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h rename to third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h index f11b8150..e47e905 100644 --- a/third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h +++ b/third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_MOJOM_TRAITS_H_ #include "base/memory/ref_counted.h" #include "mojo/public/cpp/bindings/string_traits_wtf.h" @@ -49,4 +49,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_BLOB_SERIALIZED_BLOB_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/platform/graphics/begin_frame_provider.h b/third_party/blink/renderer/platform/graphics/begin_frame_provider.h index e29feeb..edfd386 100644 --- a/third_party/blink/renderer/platform/graphics/begin_frame_provider.h +++ b/third_party/blink/renderer/platform/graphics/begin_frame_provider.h
@@ -51,9 +51,6 @@ } // viz::mojom::blink::EmbeddedFrameSinkClient implementation. - void OnFirstSurfaceActivation(const viz::SurfaceInfo& surface_info) final { - NOTIMPLEMENTED(); - } void BindSurfaceEmbedder( mojom::blink::SurfaceEmbedderRequest request) override { NOTIMPLEMENTED();
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc index 4ab4e95f..5a1ca52 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc
@@ -6,7 +6,6 @@ #include <memory> #include "base/single_thread_task_runner.h" -#include "components/viz/common/features.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/texture_draw_quad.h" #include "components/viz/common/resources/resource_format.h" @@ -61,9 +60,7 @@ binding_(this), placeholder_canvas_id_(canvas_id), num_unreclaimed_frames_posted_(0), - client_(client), - enable_surface_synchronization_( - ::features::IsSurfaceSynchronizationEnabled()) { + client_(client) { // Frameless canvas pass an invalid |frame_sink_id_|; don't create mojo // channel for this special case. if (!frame_sink_id_.is_valid()) @@ -284,12 +281,9 @@ if (change_size_for_next_commit_ || !parent_local_surface_id_allocator_.HasValidLocalSurfaceIdAllocation()) { parent_local_surface_id_allocator_.GenerateId(); - if (enable_surface_synchronization_) { - surface_embedder_->SetLocalSurfaceId( - parent_local_surface_id_allocator_ - .GetCurrentLocalSurfaceIdAllocation() - .local_surface_id()); - } + surface_embedder_->SetLocalSurfaceId( + parent_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation() + .local_surface_id()); change_size_for_next_commit_ = false; } frame->metadata.local_surface_id_allocation_time =
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h index 90b3cf0..d4b1639 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h
@@ -131,8 +131,6 @@ CanvasResourceDispatcherClient* client_; - const bool enable_surface_synchronization_; - base::WeakPtrFactory<CanvasResourceDispatcher> weak_ptr_factory_{this}; };
diff --git a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc index 90975021..19abe900 100644 --- a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc +++ b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.cc
@@ -10,7 +10,6 @@ #include "cc/layers/layer.h" #include "cc/layers/solid_color_layer.h" #include "cc/layers/surface_layer.h" -#include "components/viz/common/features.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/common/surfaces/surface_info.h" #include "media/base/media_switches.h" @@ -33,8 +32,6 @@ std::move(update_submission_state_callback)), binding_(this), surface_embedder_binding_(this), - enable_surface_synchronization_( - ::features::IsSurfaceSynchronizationEnabled()), frame_sink_id_(Platform::Current()->GenerateFrameSinkId()), parent_frame_sink_id_(layer_tree_view ? layer_tree_view->GetFrameSinkId() : viz::FrameSinkId()) { @@ -63,24 +60,9 @@ void SurfaceLayerBridge::SetLocalSurfaceId( const viz::LocalSurfaceId& local_surface_id) { - if (!enable_surface_synchronization_) { - NOTREACHED(); - return; - } EmbedSurface(viz::SurfaceId(frame_sink_id_, local_surface_id)); } -void SurfaceLayerBridge::OnFirstSurfaceActivation( - const viz::SurfaceInfo& surface_info) { - if (enable_surface_synchronization_) { - NOTREACHED(); - return; - } - DCHECK(surface_info.is_valid()); - DCHECK_EQ(frame_sink_id_, surface_info.id().frame_sink_id()); - EmbedSurface(surface_info.id()); -} - void SurfaceLayerBridge::EmbedSurface(const viz::SurfaceId& surface_id) { surface_activated_ = true; if (solid_color_layer_) {
diff --git a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h index 2fcafae..6145244 100644 --- a/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h +++ b/third_party/blink/renderer/platform/graphics/surface_layer_bridge.h
@@ -21,10 +21,6 @@ class SurfaceLayer; } // namespace cc -namespace viz { -class SurfaceInfo; -} // namespace viz - namespace blink { class WebLayerTreeView; @@ -45,7 +41,6 @@ void CreateSolidColorLayer(); // Implementation of blink::mojom::blink::EmbeddedFrameSinkClient - void OnFirstSurfaceActivation(const viz::SurfaceInfo&) override; void BindSurfaceEmbedder( mojom::blink::SurfaceEmbedderRequest request) override; @@ -78,7 +73,6 @@ mojo::Binding<blink::mojom::blink::EmbeddedFrameSinkClient> binding_; mojo::Binding<blink::mojom::blink::SurfaceEmbedder> surface_embedder_binding_; - const bool enable_surface_synchronization_; const viz::FrameSinkId frame_sink_id_; viz::SurfaceId current_surface_id_; const viz::FrameSinkId parent_frame_sink_id_;
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc b/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc index af4d39fb..e06c961 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc +++ b/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc
@@ -8,7 +8,6 @@ #include "base/metrics/histogram_macros.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/trace_event.h" -#include "components/viz/common/features.h" #include "components/viz/common/resources/resource_id.h" #include "components/viz/common/resources/returned_resource.h" #include "media/base/video_frame.h" @@ -30,9 +29,7 @@ : binding_(this), context_provider_callback_(context_provider_callback), resource_provider_(std::move(resource_provider)), - rotation_(media::VIDEO_ROTATION_0), - enable_surface_synchronization_( - ::features::IsSurfaceSynchronizationEnabled()) { + rotation_(media::VIDEO_ROTATION_0) { DETACH_FROM_THREAD(thread_checker_); } @@ -532,8 +529,6 @@ void VideoFrameSubmitter::GenerateNewSurfaceId() { // We need a new id in the event of context loss. child_local_surface_id_allocator_.GenerateId(); - if (!enable_surface_synchronization_) - return; surface_embedder_->SetLocalSurfaceId( child_local_surface_id_allocator_.GetCurrentLocalSurfaceIdAllocation()
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_submitter.h b/third_party/blink/renderer/platform/graphics/video_frame_submitter.h index be8558a..50e4887 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_submitter.h +++ b/third_party/blink/renderer/platform/graphics/video_frame_submitter.h
@@ -168,7 +168,6 @@ // size. viz::ChildLocalSurfaceIdAllocator child_local_surface_id_allocator_; - const bool enable_surface_synchronization_; viz::FrameTokenGenerator next_frame_token_; // Timestamps indexed by frame token for histogram purposes.
diff --git a/third_party/blink/renderer/platform/mojo/BUILD.gn b/third_party/blink/renderer/platform/mojo/BUILD.gn index d245432..cd2c135 100644 --- a/third_party/blink/renderer/platform/mojo/BUILD.gn +++ b/third_party/blink/renderer/platform/mojo/BUILD.gn
@@ -2,10 +2,10 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -source_set("geometry_struct_traits") { +source_set("geometry_mojom_traits") { sources = [ - "geometry_struct_traits.cc", - "geometry_struct_traits.h", + "geometry_mojom_traits.cc", + "geometry_mojom_traits.h", ] public_deps = [ "//third_party/blink/public:blink_headers",
diff --git a/third_party/blink/renderer/platform/mojo/DEPS b/third_party/blink/renderer/platform/mojo/DEPS index 0486ee2f..d2be0c4 100644 --- a/third_party/blink/renderer/platform/mojo/DEPS +++ b/third_party/blink/renderer/platform/mojo/DEPS
@@ -18,7 +18,7 @@ "+skia/public/mojom/bitmap_skbitmap_mojom_traits.h", "+third_party/blink/renderer/platform/blob/blob_data.h", - "+third_party/blink/renderer/platform/blob/serialized_blob_struct_traits.h", + "+third_party/blink/renderer/platform/blob/serialized_blob_mojom_traits.h", "+third_party/blink/renderer/platform/platform_export.h", "+third_party/blink/renderer/platform/weborigin", "+third_party/blink/renderer/platform/wtf",
diff --git a/third_party/blink/renderer/platform/mojo/OWNERS b/third_party/blink/renderer/platform/mojo/OWNERS index 591a684..7aebc8abb 100644 --- a/third_party/blink/renderer/platform/mojo/OWNERS +++ b/third_party/blink/renderer/platform/mojo/OWNERS
@@ -1,6 +1,4 @@ per-file *_mojom_traits*.*=set noparent per-file *_mojom_traits*.*=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/third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.cc b/third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.cc similarity index 91% rename from third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.cc rename to third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.cc index f4fa2943..07f47f2 100644 --- a/third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.cc +++ b/third_party/blink/renderer/platform/mojo/bluetooth_mojom_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 "third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.h" +#include "third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.h" #include "mojo/public/cpp/bindings/string_traits_wtf.h"
diff --git a/third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.h b/third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.h similarity index 82% rename from third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.h rename to third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.h index d72cceb..10e78a1 100644 --- a/third_party/blink/renderer/platform/mojo/bluetooth_struct_traits.h +++ b/third_party/blink/renderer/platform/mojo/bluetooth_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_MOJOM_TRAITS_H_ #include "device/bluetooth/public/mojom/uuid.mojom-blink.h" #include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom-blink.h" @@ -34,4 +34,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_BLUETOOTH_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/platform/mojo/geometry.typemap b/third_party/blink/renderer/platform/mojo/geometry.typemap index 9e3d157..946280e 100644 --- a/third_party/blink/renderer/platform/mojo/geometry.typemap +++ b/third_party/blink/renderer/platform/mojo/geometry.typemap
@@ -14,7 +14,7 @@ "//third_party/blink/public/platform/web_size.h", ] traits_headers = [ - "//third_party/blink/renderer/platform/mojo/geometry_struct_traits.h", + "//third_party/blink/renderer/platform/mojo/geometry_mojom_traits.h", "//ui/gfx/geometry/mojom/geometry_mojom_traits.h", ] @@ -24,7 +24,7 @@ ] public_deps = [ - "//third_party/blink/renderer/platform/mojo:geometry_struct_traits", + "//third_party/blink/renderer/platform/mojo:geometry_mojom_traits", ] # TODO(zqzhang): ideally, gfx.mojom.Size should be mapped into ::blink::IntSize.
diff --git a/third_party/blink/renderer/platform/mojo/geometry_struct_traits.cc b/third_party/blink/renderer/platform/mojo/geometry_mojom_traits.cc similarity index 95% rename from third_party/blink/renderer/platform/mojo/geometry_struct_traits.cc rename to third_party/blink/renderer/platform/mojo/geometry_mojom_traits.cc index 663dcfd3..8514632 100644 --- a/third_party/blink/renderer/platform/mojo/geometry_struct_traits.cc +++ b/third_party/blink/renderer/platform/mojo/geometry_mojom_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 "third_party/blink/renderer/platform/mojo/geometry_struct_traits.h" +#include "third_party/blink/renderer/platform/mojo/geometry_mojom_traits.h" namespace mojo {
diff --git a/third_party/blink/renderer/platform/mojo/geometry_struct_traits.h b/third_party/blink/renderer/platform/mojo/geometry_mojom_traits.h similarity index 92% rename from third_party/blink/renderer/platform/mojo/geometry_struct_traits.h rename to third_party/blink/renderer/platform/mojo/geometry_mojom_traits.h index 986ee17..bc7c409 100644 --- a/third_party/blink/renderer/platform/mojo/geometry_struct_traits.h +++ b/third_party/blink/renderer/platform/mojo/geometry_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_MOJOM_TRAITS_H_ #include "third_party/blink/public/platform/web_float_point.h" #include "third_party/blink/public/platform/web_float_point_3d.h" @@ -65,4 +65,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_GEOMETRY_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/platform/mojo/geometry_struct_traits_test.cc b/third_party/blink/renderer/platform/mojo/geometry_mojom_traits_test.cc similarity index 100% rename from third_party/blink/renderer/platform/mojo/geometry_struct_traits_test.cc rename to third_party/blink/renderer/platform/mojo/geometry_mojom_traits_test.cc
diff --git a/third_party/blink/renderer/platform/mojo/kurl.typemap b/third_party/blink/renderer/platform/mojo/kurl.typemap index 868ae80..5d155c4 100644 --- a/third_party/blink/renderer/platform/mojo/kurl.typemap +++ b/third_party/blink/renderer/platform/mojo/kurl.typemap
@@ -5,7 +5,7 @@ mojom = "//url/mojom/url.mojom" public_headers = [ "//third_party/blink/renderer/platform/weborigin/kurl.h" ] traits_headers = - [ "//third_party/blink/renderer/platform/mojo/kurl_struct_traits.h" ] + [ "//third_party/blink/renderer/platform/mojo/kurl_mojom_traits.h" ] # Note: consumers of this typemap must themselves depend on platform. deps = [
diff --git a/third_party/blink/renderer/platform/mojo/kurl_struct_traits.h b/third_party/blink/renderer/platform/mojo/kurl_mojom_traits.h similarity index 83% rename from third_party/blink/renderer/platform/mojo/kurl_struct_traits.h rename to third_party/blink/renderer/platform/mojo/kurl_mojom_traits.h index f1b8790..9d065c52 100644 --- a/third_party/blink/renderer/platform/mojo/kurl_struct_traits.h +++ b/third_party/blink/renderer/platform/mojo/kurl_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_MOJOM_TRAITS_H_ #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -39,4 +39,4 @@ }; } -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_KURL_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/platform/mojo/security_origin.typemap b/third_party/blink/renderer/platform/mojo/security_origin.typemap index 61acb15..b5e6f3f 100644 --- a/third_party/blink/renderer/platform/mojo/security_origin.typemap +++ b/third_party/blink/renderer/platform/mojo/security_origin.typemap
@@ -6,7 +6,7 @@ public_headers = [ "//third_party/blink/renderer/platform/weborigin/security_origin.h" ] traits_headers = [ - "//third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h", + "//third_party/blink/renderer/platform/mojo/security_origin_mojom_traits.h", ] # Note: consumers of this typemap must themselves depend on platform.
diff --git a/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h b/third_party/blink/renderer/platform/mojo/security_origin_mojom_traits.h similarity index 98% rename from third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h rename to third_party/blink/renderer/platform/mojo/security_origin_mojom_traits.h index cab3d8de..d483e3f 100644 --- a/third_party/blink/renderer/platform/mojo/security_origin_struct_traits.h +++ b/third_party/blink/renderer/platform/mojo/security_origin_mojom_traits.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_STRUCT_TRAITS_H_ -#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_STRUCT_TRAITS_H_ +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_MOJOM_TRAITS_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_MOJOM_TRAITS_H_ #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" @@ -106,4 +106,4 @@ } // namespace mojo -#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_STRUCT_TRAITS_H_ +#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_MOJO_SECURITY_ORIGIN_MOJOM_TRAITS_H_
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 26d86ad..02e16c211dc 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -872,6 +872,9 @@ // Enabled by features::kLegacyWindowsDWriteFontFallback; }, { + name: "LinkSystemColors" + }, + { name: "LongTaskV2", }, {
diff --git a/third_party/blink/tools/BUILD.gn b/third_party/blink/tools/BUILD.gn index 4bb5a01f..c0052f9 100644 --- a/third_party/blink/tools/BUILD.gn +++ b/third_party/blink/tools/BUILD.gn
@@ -9,6 +9,8 @@ args = [ "--metadata-output-dir", rebase_path("$root_out_dir/wpt_expectations_metadata"), + "--additional-expectations", + "../../third_party/blink/web_tests/WPTOverrideExpectations", ] outputs = [ "$root_out_dir/wpt_expectations_metadata/",
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 5944eb93..3989bb54 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -645,6 +645,9 @@ ], 'allowed': [ 'base::data', + # TODO(crbug.com/960665): Remove it once it is replaced with a WTF equivalent. + 'base::queue', + 'base::SharedMemory', 'base::StringPiece', 'base::ThreadTaskRunnerHandle',
diff --git a/third_party/blink/tools/build_wpt_metadata.py b/third_party/blink/tools/build_wpt_metadata.py index 75f8a0f..f080f8f4 100755 --- a/third_party/blink/tools/build_wpt_metadata.py +++ b/third_party/blink/tools/build_wpt_metadata.py
@@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import argparse +import optparse import sys from blinkpy.common.host import Host @@ -11,11 +13,16 @@ def main(args): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--additional-expectations", action="append", + help="Paths to additional expectations files for WPT.") + known_args, rest_args = parser.parse_known_args(args) + host = Host() - port = host.port_factory.get() + port = host.port_factory.get(options=optparse.Values(vars(known_args))) expectations = TestExpectations(port) metadata_builder = WPTMetadataBuilder(expectations) - sys.exit(metadata_builder.run(args)) + sys.exit(metadata_builder.run(rest_args)) if __name__ == '__main__': main(sys.argv[1:])
diff --git a/third_party/blink/tools/update_wpt_output.py b/third_party/blink/tools/update_wpt_output.py index ef78ffd..a8b7e93 100755 --- a/third_party/blink/tools/update_wpt_output.py +++ b/third_party/blink/tools/update_wpt_output.py
@@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import argparse +import optparse import sys from blinkpy.common.host import Host @@ -11,11 +13,16 @@ def main(args): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--additional-expectations", action="append", + help="Paths to additional expectations files for WPT.") + known_args, rest_args = parser.parse_known_args(args) + host = Host() - port = host.port_factory.get() + port = host.port_factory.get(options=optparse.Values(vars(known_args))) expectations = TestExpectations(port) output_updater = WPTOutputUpdater(expectations) - sys.exit(output_updater.run(args)) + sys.exit(output_updater.run(rest_args)) if __name__ == '__main__': main(sys.argv[1:])
diff --git a/third_party/blink/web_tests/MSANExpectations b/third_party/blink/web_tests/MSANExpectations index 0f6d1e7b..59247fe 100644 --- a/third_party/blink/web_tests/MSANExpectations +++ b/third_party/blink/web_tests/MSANExpectations
@@ -99,7 +99,7 @@ crbug.com/862750 [ Linux ] inspector-protocol/memory/sampling-native-profile-blink-gc.js [ Pass Crash ] -crbug.com/813547 [ Linux ] webaudio/BiquadFilter/tail-time-lowpass.html [ Pass Failure ] +crbug.com/813547 [ Linux ] webaudio/BiquadFilter/tail-time-lowpass.html [ Pass Failure Timeout ] crbug.com/856601 [ Linux ] fast/css/visited-link-hang.html [ Pass Timeout ] crbug.com/856601 [ Linux ] http/tests/devtools/elements/styles-4/styles-inline-element-style-changes-should-not-force-style-recalc.js [ Pass Timeout ] @@ -315,3 +315,24 @@ # Sheriff 2019-07-29 crbug.com/856601 [ Linux ] external/wpt/web-locks/idlharness.tentative.https.any.serviceworker.html [ Pass Timeout ] + +# Time out on MSAN +crbug.com/856601 [ Linux ] external/wpt/IndexedDB/idlharness.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/background-fetch/idlharness.https.any.serviceworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/background-fetch/idlharness.https.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/geolocation-API/idlharness.window.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/payment-handler/idlharness.https.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/web-nfc/idlharness.https.window.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/xhr/idlharness.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] http/tests/devtools/a11y-axe-core/settings/geolocations-a11y-test.js [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/api/idl.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.sharedworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/not-omt-sw-fetch/external/wpt/xhr/idlharness.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/fetch/cors-rfc1918/idlharness.tentative.any.sharedworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.sharedworker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] virtual/omt-worker-fetch/external/wpt/xhr/idlharness.any.worker.html [ Pass Timeout ] +crbug.com/856601 [ Linux ] wpt_internal/std-switch/tentative/interface.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 6614935..2d7ceb3 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6482,3 +6482,24 @@ crbug.com/855860 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker-proxied/thorough/redirect-password-base-https-other-https.html [ Pass Failure ] crbug.com/855860 [ Linux ] http/tests/fetch/serviceworker-proxied/thorough/redirect-password-base-https-other-https.html [ Pass Failure ] crbug.com/855860 [ Linux ] virtual/blink-cors/http/tests/fetch/serviceworker-proxied/thorough/redirect-password-base-https-other-https.html [ Pass Failure ] + +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker-proxied/thorough/cookie-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker-proxied/thorough/nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker-proxied/thorough/redirect-loop-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker/thorough/cookie-nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker/thorough/nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker/thorough/redirect-credentials-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker/thorough/redirect-loop-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] http/tests/fetch/serviceworker/thorough/scheme-blob-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/blink-cors/http/tests/fetch/serviceworker-proxied/thorough/nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/blink-cors/http/tests/fetch/serviceworker/thorough/redirect-credentials-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/blink-cors/http/tests/fetch/serviceworker/thorough/scheme-blob-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker-proxied/thorough/auth-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker-proxied/thorough/nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker-proxied/thorough/redirect-loop-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/access-control-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/cookie-nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/cors-preflight2-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/nocors-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/redirect-credentials-base-https-other-https.html [ Pass Failure ] +crbug.com/989863 [ Linux ] virtual/streaming-preload/http/tests/fetch/serviceworker/thorough/redirect-loop-base-https-other-https.html [ Pass Failure ]
diff --git a/third_party/blink/web_tests/WPTOverrideExpectations b/third_party/blink/web_tests/WPTOverrideExpectations new file mode 100644 index 0000000..0765f14 --- /dev/null +++ b/third_party/blink/web_tests/WPTOverrideExpectations
@@ -0,0 +1,12 @@ +# This file lists test expectations for WPT tests running ONLY under the wptrunner code path in +# Chromium. See go/wpt-in-chromium-ci for more info on the overall project. + +# There may be duplicate entries between this file and other expectations, which is acceptable. +# Use of this file is temporary while wptrunner is in development. + +# Bluetooth not supported in Chrome as per +# https://github.com/web-platform-tests/wpt/blob/master/bluetooth/README.md#web-bluetooth-testing +crbug.com/lpz external/wpt/bluetooth [ Skip ] + +# background-fetch tests seem to crash the browser, which is reported as a FAIL +crbug.com/lpz external/wpt/background-fetch/mixed-content-and-allowed-schemes.https.window.html [ Pass Timeout Failure ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json index aa5fd36f..c8faf2f0 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_6.json
@@ -210381,6 +210381,12 @@ {} ] ], + "css/css-text/white-space/pre-line-br-with-whitespace-child-crash.html": [ + [ + "css/css-text/white-space/pre-line-br-with-whitespace-child-crash.html", + {} + ] + ], "css/css-text/white-space/seg-break-transformation-000.html": [ [ "css/css-text/white-space/seg-break-transformation-000.html", @@ -382122,6 +382128,10 @@ "8dd08d80992e6d6310a6697f84c2533d399c8e5e", "reftest" ], + "css/css-text/white-space/pre-line-br-with-whitespace-child-crash.html": [ + "c7e1855f9794f42f965e64fc390e1b50b83059fb", + "testharness" + ], "css/css-text/white-space/pre-wrap-001.html": [ "87ffad96310532a6501e1b75c30f986433cc634e", "reftest" @@ -444519,7 +444529,7 @@ "testharness" ], "mathml/relations/css-styling/padding-border-margin/margin-001.html": [ - "67146882319b40398caa461a3ce86501bee19557", + "e7e2584cc45215aabc608b006529d0799e7c7617", "testharness" ], "mathml/relations/css-styling/padding-border-margin/margin-002.html": [ @@ -480563,7 +480573,7 @@ "support" ], "tools/wpt/browser.py": [ - "da202ddd2690ca6c5ac2527450acaa32ef2b0d96", + "6036b3dc37756fde4b8725e45525367179e9469d", "support" ], "tools/wpt/commands.json": [ @@ -480639,7 +480649,7 @@ "support" ], "tools/wptrunner/requirements_chrome_android.txt": [ - "1bf6ef32ad473a716cc969d06f147e5e827ade35", + "470aaf9a93996d0231e13e05cc35557a36d25de9", "support" ], "tools/wptrunner/requirements_chrome_ios.txt": [ @@ -480715,7 +480725,7 @@ "support" ], "tools/wptrunner/wptrunner/browsers/chrome_android.py": [ - "31ae7995b4010a6fcef0c585eed1128815837fcb", + "b7d553c78a2af4826fced07d3bf420609339cd4d", "support" ], "tools/wptrunner/wptrunner/browsers/chrome_ios.py": [ @@ -480831,7 +480841,7 @@ "support" ], "tools/wptrunner/wptrunner/executors/executorwebdriver.py": [ - "37f735d5751167cc946e18f9002d75653fcce099", + "898447df6f5b8059a209863f6b4f15f326ebd850", "support" ], "tools/wptrunner/wptrunner/executors/executorwebkit.py": [
diff --git a/third_party/blink/web_tests/external/wpt/mathml/relations/css-styling/padding-border-margin/margin-001.html b/third_party/blink/web_tests/external/wpt/mathml/relations/css-styling/padding-border-margin/margin-001.html index 6714688..e7e2584 100644 --- a/third_party/blink/web_tests/external/wpt/mathml/relations/css-styling/padding-border-margin/margin-001.html +++ b/third_party/blink/web_tests/external/wpt/mathml/relations/css-styling/padding-border-margin/margin-001.html
@@ -73,8 +73,8 @@ assert_true(MathMLFeatureDetection.has_mspace()); assert_true(MathMLFeatureDetection.has_dir()); var s = measureSpaceAround("mrow-margin-logical-rtl") - assert_approx_equals(s.left, 20, epsilon, "left margin"); - assert_approx_equals(s.right, 30, epsilon, "right margin"); + assert_approx_equals(s.left, 30, epsilon, "left margin"); + assert_approx_equals(s.right, 20, epsilon, "right margin"); assert_approx_equals(s.top, 40, epsilon, "top margin"); assert_approx_equals(s.bottom, 50, epsilon, "bottom margin"); var b = document.getElementById("mrow-margin-logical-rtl").
diff --git a/third_party/blink/web_tests/external/wpt/tools/wpt/browser.py b/third_party/blink/web_tests/external/wpt/tools/wpt/browser.py index da202ddd..6036b3d 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wpt/browser.py +++ b/third_party/blink/web_tests/external/wpt/tools/wpt/browser.py
@@ -595,7 +595,7 @@ return find_executable("chromedriver") def install_webdriver(self, dest=None, channel=None, browser_binary=None): - chrome = Chrome() + chrome = Chrome(self.logger) return chrome.install_webdriver(dest, channel) def version(self, binary=None, webdriver_binary=None):
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_chrome_android.txt b/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_chrome_android.txt index 1bf6ef3..470aaf9 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_chrome_android.txt +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/requirements_chrome_android.txt
@@ -1,2 +1 @@ mozprocess==1.0.0 -selenium==3.141.0
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/browsers/chrome_android.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/browsers/chrome_android.py index 31ae799..b7d553c 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/browsers/chrome_android.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/browsers/chrome_android.py
@@ -2,18 +2,18 @@ from .base import Browser, ExecutorBrowser, require_arg from .base import get_timeout_multiplier # noqa: F401 +from .chrome import executor_kwargs as chrome_executor_kwargs from ..webdriver_server import ChromeDriverServer -from ..executors import executor_kwargs as base_executor_kwargs -from ..executors.executorselenium import (SeleniumTestharnessExecutor, # noqa: F401 - SeleniumRefTestExecutor) # noqa: F401 +from ..executors.executorwebdriver import (WebDriverTestharnessExecutor, # noqa: F401 + WebDriverRefTestExecutor) # noqa: F401 from ..executors.executorchrome import ChromeDriverWdspecExecutor # noqa: F401 __wptrunner__ = {"product": "chrome_android", "check_args": "check_args", "browser": "ChromeAndroidBrowser", - "executor": {"testharness": "SeleniumTestharnessExecutor", - "reftest": "SeleniumRefTestExecutor", + "executor": {"testharness": "WebDriverTestharnessExecutor", + "reftest": "WebDriverRefTestExecutor", "wdspec": "ChromeDriverWdspecExecutor"}, "browser_kwargs": "browser_kwargs", "executor_kwargs": "executor_kwargs", @@ -36,31 +36,25 @@ def executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs): - from selenium.webdriver import DesiredCapabilities - - # Use extend() to modify the global list in place. + # Use update() to modify the global list in place. _wptserve_ports.update(set( server_config['ports']['http'] + server_config['ports']['https'] + server_config['ports']['ws'] + server_config['ports']['wss'] )) - executor_kwargs = base_executor_kwargs(test_type, server_config, cache_manager, run_info_data, - **kwargs) - executor_kwargs["close_after_done"] = True - capabilities = dict(DesiredCapabilities.CHROME.items()) - capabilities["goog:chromeOptions"] = {} - # TODO(chrome): browser_channel should be properly supported. + executor_kwargs = chrome_executor_kwargs(test_type, server_config, + cache_manager, run_info_data, + **kwargs) + del executor_kwargs["capabilities"]["goog:chromeOptions"]["prefs"] + del executor_kwargs["capabilities"]["goog:chromeOptions"]["useAutomationExtension"] + + # TODO(Hexcles): browser_channel should be properly supported. package_name = "com.android.chrome" # stable channel # Required to start on mobile - capabilities["goog:chromeOptions"]["androidPackage"] = package_name + executor_kwargs["capabilities"]["goog:chromeOptions"]["androidPackage"] = \ + package_name + # Map wptrunner args to chromeOptions. - for (kwarg, capability) in [("binary", "binary"), ("binary_args", "args")]: - if kwargs[kwarg] is not None: - capabilities["goog:chromeOptions"][capability] = kwargs[kwarg] - if test_type == "testharness": - capabilities["useAutomationExtension"] = False - capabilities["excludeSwitches"] = ["enable-automation"] - executor_kwargs["capabilities"] = capabilities return executor_kwargs
diff --git a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py index 37f735d..898447d 100644 --- a/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py +++ b/third_party/blink/web_tests/external/wpt/tools/wptrunner/wptrunner/executors/executorwebdriver.py
@@ -86,6 +86,7 @@ self.parent.base.execute_script(self.runner_script % format_map) def close_old_windows(self): + self.webdriver.actions.release() handles = [item for item in self.webdriver.handles if item != self.runner_handle] for handle in handles: try:
diff --git a/third_party/blink/web_tests/fast/css/css2-system-color.html b/third_party/blink/web_tests/fast/css/css2-system-color.html index ca291f3..0b2f2f15 100644 --- a/third_party/blink/web_tests/fast/css/css2-system-color.html +++ b/third_party/blink/web_tests/fast/css/css2-system-color.html
@@ -42,6 +42,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: InactiveCaptionText"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: InfoBackground"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: InfoText"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: LinkText"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: Menu"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: MenuText"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: Scrollbar"> </div></div> @@ -50,6 +51,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: ThreeDHighlight"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: ThreeDLightShadow"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: ThreeDShadow"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: VisitedText"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: Window"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: WindowFrame"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: WindowText"> </div></div>
diff --git a/third_party/blink/web_tests/fast/css/test-setting-canvas-color-expected.txt b/third_party/blink/web_tests/fast/css/test-setting-canvas-color-expected.txt index 2888558..3193d83 100644 --- a/third_party/blink/web_tests/fast/css/test-setting-canvas-color-expected.txt +++ b/third_party/blink/web_tests/fast/css/test-setting-canvas-color-expected.txt
@@ -36,6 +36,8 @@ PASS Setting color to infobackground was successfully set. PASS Setting color to InfoText was successfully set. PASS Setting color to infotext was successfully set. +FAIL Setting color to LinkText was not set but should! +FAIL Setting color to linktext was not set but should! PASS Setting color to Menu was successfully set. PASS Setting color to menu was successfully set. PASS Setting color to MenuText was successfully set. @@ -52,6 +54,8 @@ PASS Setting color to threedlightshadow was successfully set. PASS Setting color to ThreeDShadow was successfully set. PASS Setting color to threedshadow was successfully set. +FAIL Setting color to VisitedText was not set but should! +FAIL Setting color to visitedtext was not set but should! PASS Setting color to Window was successfully set. PASS Setting color to window was successfully set. PASS Setting color to WindowFrame was successfully set.
diff --git a/third_party/blink/web_tests/fast/css/test-setting-canvas-color.html b/third_party/blink/web_tests/fast/css/test-setting-canvas-color.html index 8c126b6d..e1e3409 100644 --- a/third_party/blink/web_tests/fast/css/test-setting-canvas-color.html +++ b/third_party/blink/web_tests/fast/css/test-setting-canvas-color.html
@@ -56,6 +56,7 @@ "InactiveCaptionText", "InfoBackground", "InfoText", + "LinkText", "Menu", "MenuText", "Scrollbar", @@ -64,6 +65,7 @@ "ThreeDHighlight", "ThreeDLightShadow", "ThreeDShadow", + "VisitedText", "Window", "WindowFrame", "WindowText"
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors/fast/css/css2-system-color-expected.html b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/css2-system-color-expected.html similarity index 93% rename from third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors/fast/css/css2-system-color-expected.html rename to third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/css2-system-color-expected.html index 5039e2c..eef2505 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors/fast/css/css2-system-color-expected.html +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/css2-system-color-expected.html
@@ -40,6 +40,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: rgb(127, 127, 127)"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: rgb(251, 252, 197)"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: rgb(0, 102, 204)"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: rgb(247, 247, 247)"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> @@ -48,6 +49,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: rgb(221, 221, 221)"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: rgb(192, 192, 192)"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: rgb(136, 136, 136)"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: rgb(0, 102, 204)"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: rgb(204, 204, 204)"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div>
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/test-setting-canvas-color-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/test-setting-canvas-color-expected.txt new file mode 100644 index 0000000..b51ef5d3 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/fast/css/test-setting-canvas-color-expected.txt
@@ -0,0 +1,223 @@ +Test case for bug 39168. This tests the CSS color parsing code using <canvas>. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + +PASS Setting color to ActiveBorder was successfully set. +PASS Setting color to activeborder was successfully set. +PASS Setting color to ActiveCaption was successfully set. +PASS Setting color to activecaption was successfully set. +PASS Setting color to AppWorkspace was successfully set. +PASS Setting color to appworkspace was successfully set. +PASS Setting color to Background was successfully set. +PASS Setting color to background was successfully set. +PASS Setting color to ButtonFace was successfully set. +PASS Setting color to buttonface was successfully set. +PASS Setting color to ButtonHighlight was successfully set. +PASS Setting color to buttonhighlight was successfully set. +PASS Setting color to ButtonShadow was successfully set. +PASS Setting color to buttonshadow was successfully set. +PASS Setting color to ButtonText was successfully set. +PASS Setting color to buttontext was successfully set. +PASS Setting color to CaptionText was successfully set. +PASS Setting color to captiontext was successfully set. +PASS Setting color to GrayText was successfully set. +PASS Setting color to graytext was successfully set. +PASS Setting color to Highlight was successfully set. +PASS Setting color to highlight was successfully set. +PASS Setting color to HighlightText was successfully set. +PASS Setting color to highlighttext was successfully set. +PASS Setting color to InactiveBorder was successfully set. +PASS Setting color to inactiveborder was successfully set. +PASS Setting color to InactiveCaption was successfully set. +PASS Setting color to inactivecaption was successfully set. +PASS Setting color to InactiveCaptionText was successfully set. +PASS Setting color to inactivecaptiontext was successfully set. +PASS Setting color to InfoBackground was successfully set. +PASS Setting color to infobackground was successfully set. +PASS Setting color to InfoText was successfully set. +PASS Setting color to infotext was successfully set. +PASS Setting color to LinkText was successfully set. +PASS Setting color to linktext was successfully set. +PASS Setting color to Menu was successfully set. +PASS Setting color to menu was successfully set. +PASS Setting color to MenuText was successfully set. +PASS Setting color to menutext was successfully set. +PASS Setting color to Scrollbar was successfully set. +PASS Setting color to scrollbar was successfully set. +PASS Setting color to ThreeDDarkShadow was successfully set. +PASS Setting color to threeddarkshadow was successfully set. +PASS Setting color to ThreeDFace was successfully set. +PASS Setting color to threedface was successfully set. +PASS Setting color to ThreeDHighlight was successfully set. +PASS Setting color to threedhighlight was successfully set. +PASS Setting color to ThreeDLightShadow was successfully set. +PASS Setting color to threedlightshadow was successfully set. +PASS Setting color to ThreeDShadow was successfully set. +PASS Setting color to threedshadow was successfully set. +PASS Setting color to VisitedText was successfully set. +PASS Setting color to visitedtext was successfully set. +PASS Setting color to Window was successfully set. +PASS Setting color to window was successfully set. +PASS Setting color to WindowFrame was successfully set. +PASS Setting color to windowframe was successfully set. +PASS Setting color to WindowText was successfully set. +PASS Setting color to windowtext was successfully set. +PASS Setting color to aliceblue was successfully set. +PASS Setting color to antiquewhite was successfully set. +PASS Setting color to aqua was successfully set. +PASS Setting color to aquamarine was successfully set. +PASS Setting color to azure was successfully set. +PASS Setting color to beige was successfully set. +PASS Setting color to bisque was successfully set. +PASS Setting color to black was successfully set. +PASS Setting color to blanchedalmond was successfully set. +PASS Setting color to blue was successfully set. +PASS Setting color to blueviolet was successfully set. +PASS Setting color to brown was successfully set. +PASS Setting color to burlywood was successfully set. +PASS Setting color to cadetblue was successfully set. +PASS Setting color to chartreuse was successfully set. +PASS Setting color to chocolate was successfully set. +PASS Setting color to coral was successfully set. +PASS Setting color to cornflowerblue was successfully set. +PASS Setting color to cornsilk was successfully set. +PASS Setting color to crimson was successfully set. +PASS Setting color to cyan was successfully set. +PASS Setting color to darkblue was successfully set. +PASS Setting color to darkcyan was successfully set. +PASS Setting color to darkgoldenrod was successfully set. +PASS Setting color to darkgray was successfully set. +PASS Setting color to darkgreen was successfully set. +PASS Setting color to darkgrey was successfully set. +PASS Setting color to darkkhaki was successfully set. +PASS Setting color to darkmagenta was successfully set. +PASS Setting color to darkolivegreen was successfully set. +PASS Setting color to darkorange was successfully set. +PASS Setting color to darkorchid was successfully set. +PASS Setting color to darkred was successfully set. +PASS Setting color to darksalmon was successfully set. +PASS Setting color to darkseagreen was successfully set. +PASS Setting color to darkslateblue was successfully set. +PASS Setting color to darkslategray was successfully set. +PASS Setting color to darkslategrey was successfully set. +PASS Setting color to darkturquoise was successfully set. +PASS Setting color to darkviolet was successfully set. +PASS Setting color to deeppink was successfully set. +PASS Setting color to deepskyblue was successfully set. +PASS Setting color to dimgray was successfully set. +PASS Setting color to dimgrey was successfully set. +PASS Setting color to dodgerblue was successfully set. +PASS Setting color to firebrick was successfully set. +PASS Setting color to floralwhite was successfully set. +PASS Setting color to forestgreen was successfully set. +PASS Setting color to fuchsia was successfully set. +PASS Setting color to gainsboro was successfully set. +PASS Setting color to ghostwhite was successfully set. +PASS Setting color to gold was successfully set. +PASS Setting color to goldenrod was successfully set. +PASS Setting color to gray was successfully set. +PASS Setting color to green was successfully set. +PASS Setting color to greenyellow was successfully set. +PASS Setting color to grey was successfully set. +PASS Setting color to honeydew was successfully set. +PASS Setting color to hotpink was successfully set. +PASS Setting color to indianred was successfully set. +PASS Setting color to indigo was successfully set. +PASS Setting color to ivory was successfully set. +PASS Setting color to khaki was successfully set. +PASS Setting color to lavender was successfully set. +PASS Setting color to lavenderblush was successfully set. +PASS Setting color to lawngreen was successfully set. +PASS Setting color to lemonchiffon was successfully set. +PASS Setting color to lightblue was successfully set. +PASS Setting color to lightcoral was successfully set. +PASS Setting color to lightcyan was successfully set. +PASS Setting color to lightgoldenrodyellow was successfully set. +PASS Setting color to lightgray was successfully set. +PASS Setting color to lightgreen was successfully set. +PASS Setting color to lightgrey was successfully set. +PASS Setting color to lightpink was successfully set. +PASS Setting color to lightsalmon was successfully set. +PASS Setting color to lightseagreen was successfully set. +PASS Setting color to lightskyblue was successfully set. +PASS Setting color to lightslategray was successfully set. +PASS Setting color to lightslategrey was successfully set. +PASS Setting color to lightsteelblue was successfully set. +PASS Setting color to lightyellow was successfully set. +PASS Setting color to lime was successfully set. +PASS Setting color to limegreen was successfully set. +PASS Setting color to linen was successfully set. +PASS Setting color to magenta was successfully set. +PASS Setting color to maroon was successfully set. +PASS Setting color to mediumaquamarine was successfully set. +PASS Setting color to mediumblue was successfully set. +PASS Setting color to mediumorchid was successfully set. +PASS Setting color to mediumpurple was successfully set. +PASS Setting color to mediumseagreen was successfully set. +PASS Setting color to mediumslateblue was successfully set. +PASS Setting color to mediumspringgreen was successfully set. +PASS Setting color to mediumturquoise was successfully set. +PASS Setting color to mediumvioletred was successfully set. +PASS Setting color to midnightblue was successfully set. +PASS Setting color to mintcream was successfully set. +PASS Setting color to mistyrose was successfully set. +PASS Setting color to moccasin was successfully set. +PASS Setting color to navajowhite was successfully set. +PASS Setting color to navy was successfully set. +PASS Setting color to oldlace was successfully set. +PASS Setting color to olive was successfully set. +PASS Setting color to olivedrab was successfully set. +PASS Setting color to orange was successfully set. +PASS Setting color to orangered was successfully set. +PASS Setting color to orchid was successfully set. +PASS Setting color to palegoldenrod was successfully set. +PASS Setting color to palegreen was successfully set. +PASS Setting color to paleturquoise was successfully set. +PASS Setting color to palevioletred was successfully set. +PASS Setting color to papayawhip was successfully set. +PASS Setting color to peachpuff was successfully set. +PASS Setting color to peru was successfully set. +PASS Setting color to pink was successfully set. +PASS Setting color to plum was successfully set. +PASS Setting color to powderblue was successfully set. +PASS Setting color to purple was successfully set. +PASS Setting color to rosybrown was successfully set. +PASS Setting color to royalblue was successfully set. +PASS Setting color to saddlebrown was successfully set. +PASS Setting color to salmon was successfully set. +PASS Setting color to sandybrown was successfully set. +PASS Setting color to seagreen was successfully set. +PASS Setting color to seashell was successfully set. +PASS Setting color to sienna was successfully set. +PASS Setting color to silver was successfully set. +PASS Setting color to skyblue was successfully set. +PASS Setting color to slateblue was successfully set. +PASS Setting color to slategray was successfully set. +PASS Setting color to slategrey was successfully set. +PASS Setting color to snow was successfully set. +PASS Setting color to springgreen was successfully set. +PASS Setting color to steelblue was successfully set. +PASS Setting color to tan was successfully set. +PASS Setting color to teal was successfully set. +PASS Setting color to thistle was successfully set. +PASS Setting color to tomato was successfully set. +PASS Setting color to turquoise was successfully set. +PASS Setting color to violet was successfully set. +PASS Setting color to wheat was successfully set. +PASS Setting color to white was successfully set. +PASS Setting color to whitesmoke was successfully set. +PASS Setting color to yellow was successfully set. +PASS Setting color to yellowgreen was successfully set. +PASS Setting color to #0f0 was successfully set. +PASS Setting color to hsl(120, 100%, 50%) was successfully set. +PASS Setting color to foobar was not set (as expected). +PASS Setting color to counter(foobar) was not set (as expected). +PASS Setting color to url(http://127.0.0.1:8080/) was not set (as expected). +PASS Setting color to inherited was not set (as expected). +PASS Setting color to #100% was not set (as expected). +PASS Setting color to #100px was not set (as expected). +PASS Setting color to var("test") was not set (as expected). +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/svg/css/rect-system-color-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/svg/css/rect-system-color-expected.txt new file mode 100644 index 0000000..efc23b3 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=UseWindowsSystemColors,LinkSystemColors/svg/css/rect-system-color-expected.txt
@@ -0,0 +1,100 @@ +Test that fill and stroke properties accept system colors + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + + +Testing system colorActiveBorder +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorActiveCaption +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorAppWorkspace +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorBackground +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorButtonFace +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorButtonHighlight +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorButtonShadow +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorButtonText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorCaptionText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorGrayText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorHighlight +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorHighlightText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorInactiveBorder +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorInactiveCaption +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorInactiveCaptionText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorInfoBackground +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorInfoText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorLinkText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorMenu +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorMenuText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorScrollbar +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorThreeDDarkShadow +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorThreeDFace +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorThreeDHighlight +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorThreeDLightShadow +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorThreeDShadow +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorVisitedText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorWindow +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorWindowFrame +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorWindowText +PASS computedStyleText.fill is computedStyleDiv.color +PASS computedStyleText.stroke is computedStyleDiv.color +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors-expected.txt index 8633fad..ed34b4f 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors-expected.txt +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors-expected.txt
@@ -18,7 +18,31 @@ { error : { code : -32602 - message : The Relying Party ID hash must have a size of 32 + message : The Relying Party ID is a required parameter + } + id : <number> + sessionId : <string> +} +{ + error : { + code : -32602 + message : The Authenticator does not support Resident Credentials. + } + id : <number> + sessionId : <string> +} +{ + error : { + code : -32602 + message : The User Handle is required for Resident Credentials + } + id : <number> + sessionId : <string> +} +{ + error : { + code : -32602 + message : The User Handle must have a maximum size of 64 } id : <number> sessionId : <string>
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors.js b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors.js index 40ffd7b..1725e9c 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors.js +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-errors.js
@@ -10,8 +10,8 @@ credential: { credentialId: btoa(credentialId), privateKey: btoa("invalid private key"), - rpIdHash: btoa("invalid hash"), signCount: 0, + isResidentCredential: true, } }; @@ -22,7 +22,7 @@ await dp.WebAuthn.enable(); testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); - // Try with an invalid RP ID hash. + // Try without an RP ID. credentialOptions.authenticatorId = (await dp.WebAuthn.addVirtualAuthenticator({ options: { protocol: "ctap2", @@ -33,9 +33,31 @@ })).result.authenticatorId; testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); - // Try with a private key that is not valid. - credentialOptions.credential.rpIdHash = - await session.evaluateAsync("generateRpIdHash()"); + // Try registering a resident credential on an authenticator not capable of + // resident credentials. + credentialOptions.credential.rpId = "devtools.test"; testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); + + // Try registering a resident credential without a user handle. + credentialOptions.authenticatorId = (await dp.WebAuthn.addVirtualAuthenticator({ + options: { + protocol: "ctap2", + transport: "usb", + hasResidentKey: true, + hasUserVerification: false, + }, + })).result.authenticatorId; + testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); + + // Try a user handle that exceeds the max size. + const MAX_USER_HANDLE_SIZE = 64; + const longHandle = "a".repeat(MAX_USER_HANDLE_SIZE + 1); + credentialOptions.credential.userHandle = btoa(longHandle); + testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); + + // Try with a private key that is not valid. + credentialOptions.credential.userHandle = btoa("nina"); + testRunner.log(await dp.WebAuthn.addCredential(credentialOptions)); + testRunner.completeTest(); })
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-expected.txt index dfc72b5..44b92707 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-expected.txt +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential-expected.txt
@@ -10,4 +10,15 @@ } status : OK } +{ + id : <number> + result : { + } + sessionId : <string> +} +{ + attestation : { + } + status : OK +}
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential.js b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential.js index 83d98b58..b05cf74 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential.js +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-add-credential.js
@@ -10,28 +10,50 @@ options: { protocol: "ctap2", transport: "usb", - hasResidentKey: false, + hasResidentKey: true, hasUserVerification: false, }, })).result.authenticatorId; - // Register a credential. - const credentialId = "cred-1"; - const addCredentialResult = (await dp.WebAuthn.addCredential({ + // Register a non-resident credential. + const nonResidentCredentialId = "cred-1"; + testRunner.log(await dp.WebAuthn.addCredential({ authenticatorId, credential: { - credentialId: btoa(credentialId), - rpIdHash: await session.evaluateAsync("generateRpIdHash()"), + credentialId: btoa(nonResidentCredentialId), + rpId: "devtools.test", privateKey: await session.evaluateAsync("generateBase64Key()"), signCount: 0, + isResidentCredential: false, } })); - testRunner.log(addCredentialResult); - // Authenticate with the registered credential. + // Authenticate with the non-resident credential. testRunner.log(await session.evaluateAsync(`getCredential({ type: "public-key", - id: new TextEncoder().encode("${credentialId}"), + id: new TextEncoder().encode("${nonResidentCredentialId}"), + transports: ["usb", "ble", "nfc"], + })`)); + + // Register a resident credential. + const userHandle = "nina"; + const residentCredentialId = "cred-2"; + testRunner.log(await dp.WebAuthn.addCredential({ + authenticatorId, + credential: { + credentialId: btoa(residentCredentialId), + rpId: "devtools.test", + privateKey: await session.evaluateAsync("generateBase64Key()"), + signCount: 0, + isResidentCredential: true, + userHandle: btoa(userHandle), + } + })); + + // Authenticate with the resident credential. + testRunner.log(await session.evaluateAsync(`getCredential({ + type: "public-key", + id: new TextEncoder().encode("${residentCredentialId}"), transports: ["usb", "ble", "nfc"], })`));
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials-expected.txt b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials-expected.txt index 07e33db..1adfd374 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials-expected.txt +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials-expected.txt
@@ -8,11 +8,22 @@ sessionId : <string> } OK -OK -RP ID hash matches expected value -1 -RP ID hash matches expected value -1 +{ + id : <number> + result : { + } + sessionId : <string> +} +Resident Credential: +isResidentCredential: true +signCount: 1 +rpId: devtools.test +userHandle: nina +Non-Resident Credential: +isResidentCredential: false +signCount: 1 +rpId: undefined +userHandle: { attestation : { }
diff --git a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials.js b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials.js index 76d7655c8..3bb657b 100644 --- a/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials.js +++ b/third_party/blink/web_tests/http/tests/inspector-protocol/webauthn/webauthn-get-credentials.js
@@ -9,7 +9,7 @@ options: { protocol: "ctap2", transport: "usb", - hasResidentKey: false, + hasResidentKey: true, hasUserVerification: false, }, })).result.authenticatorId; @@ -17,37 +17,56 @@ // No credentials registered yet. testRunner.log(await dp.WebAuthn.getCredentials({authenticatorId})); - // Register two credentials. - testRunner.log((await session.evaluateAsync("registerCredential()")).status); + // Register a non-resident credential. testRunner.log((await session.evaluateAsync("registerCredential()")).status); + // TODO(nsatragno): content_shell does not support registering resident + // credentials through navigator.credentials.create(). Update this test to use + // registerCredential() once that feature is supported. + const userHandle = "nina"; + const credentialId = "cred-2"; + testRunner.log(await dp.WebAuthn.addCredential({ + authenticatorId, + credential: { + credentialId: btoa(credentialId), + rpId: "devtools.test", + privateKey: await session.evaluateAsync("generateBase64Key()"), + signCount: 1, + isResidentCredential: true, + userHandle: btoa(userHandle), + } + })); + + let logCredential = credential => { + testRunner.log("isResidentCredential: " + credential.isResidentCredential); + testRunner.log("signCount: " + credential.signCount); + testRunner.log("rpId: " + credential.rpId); + testRunner.log("userHandle: " + atob(credential.userHandle || "")); + }; // Get the registered credentials. let credentials = (await dp.WebAuthn.getCredentials({authenticatorId})).result.credentials; - let expectedRpIdHash = await session.evaluateAsync("generateRpIdHash()"); - for (let credential of credentials) { - if (credential.rpIdHash === expectedRpIdHash) - testRunner.log("RP ID hash matches expected value"); - else - testRunner.log(`RP ID hash does not match. Actual: ${credential.rpIdHash}, expected: ${expectedRpIdHash}`); - testRunner.log(credential.signCount); - } + let residentCredential = credentials.find(cred => cred.isResidentCredential); + let nonResidentCredential = credentials.find(cred => !cred.isResidentCredential); + testRunner.log("Resident Credential:"); + logCredential(residentCredential); + testRunner.log("Non-Resident Credential:"); + logCredential(nonResidentCredential); - // Authenticating with the first credential should succeed. - let credential = credentials[0]; + // Authenticating with the non resident credential should succeed. testRunner.log(await session.evaluateAsync(`getCredential({ type: "public-key", - id: base64ToArrayBuffer("${credential.credentialId}"), + id: base64ToArrayBuffer("${nonResidentCredential.credentialId}"), transports: ["usb", "ble", "nfc"], })`)); - // Sign count should be increased by one for |credential|. + // Sign count should be increased by one for |nonResidentCredential|. credentials = (await dp.WebAuthn.getCredentials({authenticatorId})).result.credentials; testRunner.log(credentials.find( - cred => cred.id === credential.id).signCount); + cred => cred.credentialId === nonResidentCredential.credentialId).signCount); // We should be able to parse the private key. let keyData = - Uint8Array.from(atob(credential.privateKey), c => c.charCodeAt(0)).buffer; + Uint8Array.from(atob(nonResidentCredential.privateKey), c => c.charCodeAt(0)).buffer; let key = await window.crypto.subtle.importKey( "pkcs8", keyData, { name: "ECDSA", namedCurve: "P-256" }, true /* extractable */, ["sign"]);
diff --git a/third_party/blink/web_tests/platform/linux/fast/css/css2-system-color-expected.html b/third_party/blink/web_tests/platform/linux/fast/css/css2-system-color-expected.html index b4fcd2fe..4afb5507 100644 --- a/third_party/blink/web_tests/platform/linux/fast/css/css2-system-color-expected.html +++ b/third_party/blink/web_tests/platform/linux/fast/css/css2-system-color-expected.html
@@ -40,6 +40,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: rgb(127, 127, 127)"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: rgb(251, 252, 197)"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: rgb(247, 247, 247)"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> @@ -48,6 +49,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: rgb(221, 221, 221)"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: rgb(192, 192, 192)"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: rgb(136, 136, 136)"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: rgb(204, 204, 204)"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div>
diff --git a/third_party/blink/web_tests/platform/mac/fast/css/css2-system-color-expected.html b/third_party/blink/web_tests/platform/mac/fast/css/css2-system-color-expected.html index af69827a..940d99ed 100644 --- a/third_party/blink/web_tests/platform/mac/fast/css/css2-system-color-expected.html +++ b/third_party/blink/web_tests/platform/mac/fast/css/css2-system-color-expected.html
@@ -40,6 +40,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: rgb(251, 252, 197)"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: rgb(246, 246, 246)"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: rgb(170, 170, 170)"> </div></div> @@ -48,6 +49,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: rgb(236, 236, 236)"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: rgb(170, 170, 170)"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div>
diff --git a/third_party/blink/web_tests/platform/win/fast/css/css2-system-color-expected.html b/third_party/blink/web_tests/platform/win/fast/css/css2-system-color-expected.html index b4fcd2fe..4afb5507 100644 --- a/third_party/blink/web_tests/platform/win/fast/css/css2-system-color-expected.html +++ b/third_party/blink/web_tests/platform/win/fast/css/css2-system-color-expected.html
@@ -40,6 +40,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: rgb(127, 127, 127)"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: rgb(251, 252, 197)"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: rgb(247, 247, 247)"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> @@ -48,6 +49,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: rgb(221, 221, 221)"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: rgb(192, 192, 192)"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: rgb(136, 136, 136)"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: rgb(204, 204, 204)"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div>
diff --git a/third_party/blink/web_tests/platform/win7/fast/css/css2-system-color-expected.html b/third_party/blink/web_tests/platform/win7/fast/css/css2-system-color-expected.html index b4fcd2fe..4afb5507 100644 --- a/third_party/blink/web_tests/platform/win7/fast/css/css2-system-color-expected.html +++ b/third_party/blink/web_tests/platform/win7/fast/css/css2-system-color-expected.html
@@ -40,6 +40,7 @@ <div class="box"><div class="text">InactiveCaptionText</div><div class="inner" style="background-color: rgb(127, 127, 127)"> </div></div> <div class="box"><div class="text">InfoBackground</div><div class="inner" style="background-color: rgb(251, 252, 197)"> </div></div> <div class="box"><div class="text">InfoText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> + <div class="box"><div class="text">LinkText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Menu</div><div class="inner" style="background-color: rgb(247, 247, 247)"> </div></div> <div class="box"><div class="text">MenuText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div> <div class="box"><div class="text">Scrollbar</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> @@ -48,6 +49,7 @@ <div class="box"><div class="text">ThreeDHighlight</div><div class="inner" style="background-color: rgb(221, 221, 221)"> </div></div> <div class="box"><div class="text">ThreeDLightShadow</div><div class="inner" style="background-color: rgb(192, 192, 192)"> </div></div> <div class="box"><div class="text">ThreeDShadow</div><div class="inner" style="background-color: rgb(136, 136, 136)"> </div></div> + <div class="box"><div class="text">VisitedText</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">Window</div><div class="inner" style="background-color: rgb(255, 255, 255)"> </div></div> <div class="box"><div class="text">WindowFrame</div><div class="inner" style="background-color: rgb(204, 204, 204)"> </div></div> <div class="box"><div class="text">WindowText</div><div class="inner" style="background-color: rgb(0, 0, 0)"> </div></div>
diff --git a/third_party/blink/web_tests/svg/css/css-systemcolors-expected.svg b/third_party/blink/web_tests/svg/css/css-systemcolors-expected.svg index 872c711..a67c15a9 100644 --- a/third_party/blink/web_tests/svg/css/css-systemcolors-expected.svg +++ b/third_party/blink/web_tests/svg/css/css-systemcolors-expected.svg
@@ -339,6 +339,30 @@ </feDiffuseLighting> <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> </filter> + <filter x="0" y="0" width="1" height="1" id="f28"> + <feFlood flood-color="currentColor" color="LinkText" /> + </filter> + <linearGradient id="g28"> + <stop stop-color="currentColor" color="LinkText" /> + </linearGradient> + <filter x="0" y="0" width="1" height="1" id="fl28"> + <feDiffuseLighting color="LinkText" lighting-color="currentColor" in="SourceAlpha" result="light"> + <feDistantLight azimuth="45" elevation="45" /> + </feDiffuseLighting> + <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> + </filter> + <filter x="0" y="0" width="1" height="1" id="f29"> + <feFlood flood-color="currentColor" color="VisitedText" /> + </filter> + <linearGradient id="g29"> + <stop stop-color="currentColor" color="VisitedText" /> + </linearGradient> + <filter x="0" y="0" width="1" height="1" id="fl29"> + <feDiffuseLighting color="VisitedText" lighting-color="currentColor" in="SourceAlpha" result="light"> + <feDistantLight azimuth="45" elevation="45" /> + </feDiffuseLighting> + <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> + </filter> </defs> <rect width="28" height="28" x="0" filter="url(#f0)" /> <rect width="28" height="28" x="0" y="28" fill="url(#g0)" /> @@ -424,4 +448,10 @@ <rect width="28" height="28" x="756" filter="url(#f27)" /> <rect width="28" height="28" x="756" y="28" fill="url(#g27)" /> <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl27)" /> + <rect width="28" height="28" x="756" filter="url(#f28)" /> + <rect width="28" height="28" x="756" y="28" fill="url(#g28)" /> + <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl28)" /> + <rect width="28" height="28" x="756" filter="url(#f29)" /> + <rect width="28" height="28" x="756" y="28" fill="url(#g29)" /> + <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl29)" /> </svg>
diff --git a/third_party/blink/web_tests/svg/css/css-systemcolors.svg b/third_party/blink/web_tests/svg/css/css-systemcolors.svg index a967c11..c044f00 100644 --- a/third_party/blink/web_tests/svg/css/css-systemcolors.svg +++ b/third_party/blink/web_tests/svg/css/css-systemcolors.svg
@@ -339,6 +339,30 @@ </feDiffuseLighting> <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> </filter> + <filter x="0" y="0" width="1" height="1" id="f28"> + <feFlood flood-color="currentColor" color="LinkText" /> + </filter> + <linearGradient id="g28"> + <stop stop-color="currentColor" color="LinkColor" /> + </linearGradient> + <filter x="0" y="0" width="1" height="1" id="fl28"> + <feDiffuseLighting color="LinkColor" lighting-color="currentColor" in="SourceAlpha" result="light"> + <feDistantLight azimuth="45" elevation="45" /> + </feDiffuseLighting> + <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> + </filter> + <filter x="0" y="0" width="1" height="1" id="f29"> + <feFlood flood-color="currentColor" color="VisitedText" /> + </filter> + <linearGradient id="g29"> + <stop stop-color="currentColor" color="VisitedText" /> + </linearGradient> + <filter x="0" y="0" width="1" height="1" id="fl29"> + <feDiffuseLighting color="VisitedText" lighting-color="currentColor" in="SourceAlpha" result="light"> + <feDistantLight azimuth="45" elevation="45" /> + </feDiffuseLighting> + <feComposite in="SourceGraphic" in2="light" k1="1" k2="0" k3="0" k4="0" operator="arithmetic" /> + </filter> </defs> <rect width="28" height="28" x="0" filter="url(#f0)" /> <rect width="28" height="28" x="0" y="28" fill="url(#g0)" /> @@ -424,4 +448,10 @@ <rect width="28" height="28" x="756" filter="url(#f27)" /> <rect width="28" height="28" x="756" y="28" fill="url(#g27)" /> <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl27)" /> + <rect width="28" height="28" x="756" filter="url(#f28)" /> + <rect width="28" height="28" x="756" y="28" fill="url(#g28)" /> + <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl28)" /> + <rect width="28" height="28" x="756" filter="url(#f29)" /> + <rect width="28" height="28" x="756" y="28" fill="url(#g29)" /> + <rect width="28" height="28" x="756" y="56" fill="white" filter="url(#fl29)" /> </svg>
diff --git a/third_party/blink/web_tests/svg/css/rect-system-color-expected.txt b/third_party/blink/web_tests/svg/css/rect-system-color-expected.txt index 5a3355c..06cb707 100644 --- a/third_party/blink/web_tests/svg/css/rect-system-color-expected.txt +++ b/third_party/blink/web_tests/svg/css/rect-system-color-expected.txt
@@ -55,6 +55,9 @@ Testing system colorInfoText PASS computedStyleText.fill is computedStyleDiv.color PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorLinkText +PASS computedStyleText.fill is computedStyleDiv.color +FAIL computedStyleText.stroke should be rgb(0, 0, 0). Was rgb(0, 0, 238). Testing system colorMenu PASS computedStyleText.fill is computedStyleDiv.color PASS computedStyleText.stroke is computedStyleDiv.color @@ -79,6 +82,9 @@ Testing system colorThreeDShadow PASS computedStyleText.fill is computedStyleDiv.color PASS computedStyleText.stroke is computedStyleDiv.color +Testing system colorVisitedText +PASS computedStyleText.fill is computedStyleDiv.color +FAIL computedStyleText.stroke should be rgb(0, 0, 0). Was rgb(85, 26, 139). Testing system colorWindow PASS computedStyleText.fill is computedStyleDiv.color PASS computedStyleText.stroke is computedStyleDiv.color
diff --git a/third_party/blink/web_tests/svg/css/rect-system-color.xhtml b/third_party/blink/web_tests/svg/css/rect-system-color.xhtml index 4d291d6..6b9b3da 100644 --- a/third_party/blink/web_tests/svg/css/rect-system-color.xhtml +++ b/third_party/blink/web_tests/svg/css/rect-system-color.xhtml
@@ -27,8 +27,8 @@ var systemColors = new Array("ActiveBorder", "ActiveCaption", "AppWorkspace", "Background", "ButtonFace", "ButtonHighlight", "ButtonShadow", "ButtonText", "CaptionText", "GrayText", "Highlight", "HighlightText", "InactiveBorder", "InactiveCaption", "InactiveCaptionText", "InfoBackground", "InfoText", - "Menu", "MenuText", "Scrollbar", "ThreeDDarkShadow", "ThreeDFace", "ThreeDHighlight", - "ThreeDLightShadow", "ThreeDShadow", "Window", "WindowFrame", "WindowText"); + "LinkText", "Menu", "MenuText", "Scrollbar", "ThreeDDarkShadow", "ThreeDFace", "ThreeDHighlight", + "ThreeDLightShadow", "ThreeDShadow", "VisitedText", "Window", "WindowFrame", "WindowText"); var svgElement = document.getElementsByTagName("svg")[0]; for (i = 0; i < systemColors.length; ++i) { var textElement = document.createElementNS(SVG_NS, "text");
diff --git a/third_party/libovr/OWNERS b/third_party/libovr/OWNERS index d484bb05..ac139811 100644 --- a/third_party/libovr/OWNERS +++ b/third_party/libovr/OWNERS
@@ -1,5 +1,5 @@ +alcooper@chromium.org bajones@chromium.org -billorr@chromium.org ddorwin@chromium.org # TEAM: xr-dev@chromium.org
diff --git a/third_party/material_design_icons/OWNERS b/third_party/material_design_icons/OWNERS index ccddf8d..312f02a 100644 --- a/third_party/material_design_icons/OWNERS +++ b/third_party/material_design_icons/OWNERS
@@ -1,2 +1,3 @@ lpromero@chromium.org sdefresne@chromium.org +# COMPONENT: Internals
diff --git a/third_party/microsoft_webauthn/OWNERS b/third_party/microsoft_webauthn/OWNERS index dd5ad77..151c96a 100644 --- a/third_party/microsoft_webauthn/OWNERS +++ b/third_party/microsoft_webauthn/OWNERS
@@ -1 +1,3 @@ file://device/fido/OWNERS +# COMPONENT: Blink>WebAuthentication +# TEAM: identity-dev@chromium.org
diff --git a/third_party/openvr/OWNERS b/third_party/openvr/OWNERS index d484bb05..ac139811 100644 --- a/third_party/openvr/OWNERS +++ b/third_party/openvr/OWNERS
@@ -1,5 +1,5 @@ +alcooper@chromium.org bajones@chromium.org -billorr@chromium.org ddorwin@chromium.org # TEAM: xr-dev@chromium.org
diff --git a/third_party/openxr/OWNERS b/third_party/openxr/OWNERS index 781c43d..6fb43b8d 100644 --- a/third_party/openxr/OWNERS +++ b/third_party/openxr/OWNERS
@@ -1,5 +1,5 @@ +alcooper@chromium.org ddorwin@chromium.org -billorr@chromium.org # TEAM: xr-dev@chromium.org # COMPONENT: Internals>XR
diff --git a/third_party/qcms/OWNERS b/third_party/qcms/OWNERS index 49d05d1..89d26bc 100644 --- a/third_party/qcms/OWNERS +++ b/third_party/qcms/OWNERS
@@ -1,3 +1,5 @@ noel@chromium.org ccameron@chromium.org enne@chromium.org +# COMPONENT: Internals>GPU>Internals +# TEAM: graphics-dev@chromium.org
diff --git a/third_party/shaderc/OWNERS b/third_party/shaderc/OWNERS index e9c1789..7aedb8f9 100644 --- a/third_party/shaderc/OWNERS +++ b/third_party/shaderc/OWNERS
@@ -2,3 +2,4 @@ dsinclair@chromium.org # COMPONENT: Internals>GPU>Internals +# TEAM: graphics-dev@chromium.org
diff --git a/third_party/spirv-cross/OWNERS b/third_party/spirv-cross/OWNERS index e9c1789..7aedb8f9 100644 --- a/third_party/spirv-cross/OWNERS +++ b/third_party/spirv-cross/OWNERS
@@ -2,3 +2,4 @@ dsinclair@chromium.org # COMPONENT: Internals>GPU>Internals +# TEAM: graphics-dev@chromium.org
diff --git a/third_party/spirv-headers/OWNERS b/third_party/spirv-headers/OWNERS index afa59fc..24f8d86b 100644 --- a/third_party/spirv-headers/OWNERS +++ b/third_party/spirv-headers/OWNERS
@@ -1,3 +1,4 @@ dsinclair@chromium.org # COMPONENT: Internals>GPU>Internals +# TEAM: graphics-dev@chromium.org
diff --git a/third_party/webxr_test_pages/OWNERS b/third_party/webxr_test_pages/OWNERS index 86ae16e..8bff5847 100644 --- a/third_party/webxr_test_pages/OWNERS +++ b/third_party/webxr_test_pages/OWNERS
@@ -1,7 +1,6 @@ alcooper@chromium.org bajones@chromium.org bialpio@chromium.org -billorr@chromium.org klausw@chromium.org # TEAM: xr-dev@chromium.org
diff --git a/third_party/zlib/crc32_simd.c b/third_party/zlib/crc32_simd.c index 2fef610e..988f00b2 100644 --- a/third_party/zlib/crc32_simd.c +++ b/third_party/zlib/crc32_simd.c
@@ -168,7 +168,7 @@ * warn, and Android defaults to armv7-a. This restriction does not apply to * function-level `target`s, however.) * - * Since we only need three crc intrinsics, and since clang's implementation of + * Since we only need four crc intrinsics, and since clang's implementation of * those are just wrappers around compiler builtins, it's simplest to #define * those builtins directly. If this #define list grows too much (or we depend on * an intrinsic that isn't a trivial wrapper), we may have to find a better way @@ -181,6 +181,7 @@ #define __crc32b __builtin_arm_crc32b #define __crc32d __builtin_arm_crc32d #define __crc32w __builtin_arm_crc32w +#define __crc32cw __builtin_arm_crc32cw #if defined(__aarch64__) #define TARGET_ARMV8_WITH_CRC __attribute__((target("crc"))) @@ -251,7 +252,14 @@ if (s->level >= 6) val &= 0xFFFFFF; - h = __crc32w(h, val); + /* We use CRC32C (Castagnoli) to ensure that the compressed output + * will match between Intel x ARM. + * Unlike the case of data integrity checks for GZIP format where the + * polynomial used is defined (https://tools.ietf.org/html/rfc1952#page-11), + * here it is just a hash function for the hash table used while + * performing compression. + */ + h = __crc32cw(h, val); ret = s->head[h & s->hash_mask]; s->head[h & s->hash_mask] = str;
diff --git a/tools/fuchsia/local-sdk.py b/tools/fuchsia/local-sdk.py index a95d6b4c..51db83b0 100755 --- a/tools/fuchsia/local-sdk.py +++ b/tools/fuchsia/local-sdk.py
@@ -34,7 +34,7 @@ def BuildForArch(arch): build_dir = 'out/release-' + arch - Run('scripts/fx', '--dir', build_dir, 'set', 'terminal.' + arch, + Run('scripts/fx', '--dir', build_dir, 'set', 'terminal.qemu-'+ arch, '--with=//topaz/packages/sdk:topaz', '--with-base=//sdk/bundles:tools', '--args=is_debug=false', '--args=build_sdk_archives=true') Run('scripts/fx', 'build', 'topaz/public/sdk:fuchsia_dart', 'sdk') @@ -59,9 +59,12 @@ # Nuke the SDK from DEPS, put our just-built one there, and set a fake .hash # file. This means that on next gclient runhooks, we'll restore to the # real DEPS-determined SDK. - output_dir = os.path.join(REPOSITORY_ROOT, 'third_party', 'fuchsia-sdk', + sdk_output_dir = os.path.join(REPOSITORY_ROOT, 'third_party', 'fuchsia-sdk', 'sdk') - EnsureEmptyDir(output_dir) + images_output_dir = os.path.join(REPOSITORY_ROOT, 'third_party', + 'fuchsia-sdk', 'images') + EnsureEmptyDir(sdk_output_dir) + EnsureEmptyDir(images_output_dir) original_dir = os.getcwd() fuchsia_root = os.path.abspath(args[0]) @@ -74,20 +77,19 @@ for arch in target_archs: BuildForArch(arch) + arch_output_dir = os.path.join(fuchsia_root, 'out', 'release-' + arch) sdk_tars = [ - os.path.join(fuchsia_root, 'out', 'release-' + arch, 'sdk', 'archive', - 'core.tar.gz'), - os.path.join(fuchsia_root, 'out', 'release-' + arch, 'sdk', 'archive', - 'fuchsia_dart.tar.gz'), + os.path.join(arch_output_dir, 'sdk', 'archive', 'core.tar.gz'), + os.path.join(arch_output_dir, 'sdk', 'archive', 'fuchsia_dart.tar.gz'), ] # Extract tars merging manifests - manifest_path = os.path.join(output_dir, 'meta', 'manifest.json') + manifest_path = os.path.join(sdk_output_dir, 'meta', 'manifest.json') for sdk_tar in sdk_tars: with tarfile.open(sdk_tar, mode='r:gz') as tar: for tar_file in tar: try: - tar.extract(tar_file, output_dir) + tar.extract(tar_file, sdk_output_dir) except IOError: # Ignore overwrite of read-only files. pass @@ -106,6 +108,21 @@ manifest_parts.add(part['meta']) merged_manifest['parts'].append(part) + arch_image_dir = os.path.join(images_output_dir, arch, 'qemu') + os.mkdir(os.path.join(images_output_dir, arch)) + os.mkdir(arch_image_dir) + + # Stage the image directory using entries specified in the build image + # manifest. + images_json = json.load(open(os.path.join(arch_output_dir, 'images.json'))) + for entry in images_json: + if entry['type'] not in ['blk', 'zbi', 'kernel']: + continue + + shutil.copyfile(os.path.join(arch_output_dir, entry['path']), + os.path.join(arch_image_dir, entry['name']) + '.' + + entry['type']) + # Write merged manifest file. with open(manifest_path, 'w') as manifest_file: json.dump(merged_manifest, manifest_file, indent=2) @@ -115,14 +132,14 @@ # tree, as we want to avoid rebuilding all of Chromium if it's only e.g. the # kernel blob has changed. https://crbug.com/793956. sysroot_hash_obj = hashlib.sha1() - for root, dirs, files in os.walk(os.path.join(output_dir, 'sysroot')): + for root, dirs, files in os.walk(os.path.join(sdk_output_dir, 'sysroot')): for f in files: path = os.path.join(root, f) sysroot_hash_obj.update(path) sysroot_hash_obj.update(open(path, 'rb').read()) sysroot_hash = sysroot_hash_obj.hexdigest() - hash_filename = os.path.join(output_dir, '.hash') + hash_filename = os.path.join(sdk_output_dir, '.hash') with open(hash_filename, 'w') as f: f.write('locally-built-sdk-' + sysroot_hash)
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 2fcf259..6923d61 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -39072,6 +39072,8 @@ <int value="8" label="Seek forward"/> <int value="9" label="Skip ad"/> <int value="10" label="Stop"/> + <int value="11" label="Seek to"/> + <int value="12" label="Scrub to"/> </enum> <enum name="MediaSinkType"> @@ -59826,6 +59828,18 @@ <int value="3" label="Stable"/> </enum> +<enum name="UserDemographicsStatus"> + <int value="0" label="Success - user demographics are available for report"/> + <int value="1" label="Sync is not enabled"/> + <int value="2" label="User demographics data is ineligible"/> + <int value="3" + label="Cannot get the current time that is needed to compute user's age"/> + <int value="4" + label="There is more than one profile in the user data directory of the + browser"/> + <int value="5" label="There is no sync service available"/> +</enum> + <enum name="UserGestureRequirement"> <int value="0" label="Required and available"/> <int value="1" label="Required and not available"/>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 271a87c..aec23023 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -10382,6 +10382,9 @@ <histogram name="Autofill.PaymentsCustomerDataBillingIdStatus" enum="BillingIdStatus" expires_after="2019-09-07"> + <obsolete> + Removed as of August 2019. + </obsolete> <owner>mathp@chromium.org</owner> <summary> When PaymentsCustomerData is used to send a request to Google Payments, we @@ -19047,7 +19050,10 @@ </histogram> <histogram name="ChromeOS.PlatformVerification.ExpiryStatus" - enum="ChromeOSPlatformVerificationExpiryStatus" expires_after="M77"> + enum="ChromeOSPlatformVerificationExpiryStatus"> + <obsolete> + Removed in 2019/08 as the histogram is no longer in use. (crbug/975047) + </obsolete> <owner>apronin@chromium.org</owner> <owner>cros-hwsec+uma@chromium.org</owner> <summary> @@ -54308,7 +54314,7 @@ </histogram> <histogram name="KeyboardAccessory.AccessorySheetSuggestionCount" units="count" - expires_after="M79"> + expires_after="M81"> <owner>fhorschig@chromium.org</owner> <summary> Android only. Records how many suggestions a user faced when opening a @@ -54317,7 +54323,7 @@ </histogram> <histogram name="KeyboardAccessory.AccessorySheetSuggestionsSelected" - enum="AccessorySuggestionType" expires_after="M79"> + enum="AccessorySuggestionType" expires_after="M81"> <owner>fhorschig@chromium.org</owner> <summary> Android only. Records which type of suggestion was selected from an open @@ -54326,7 +54332,7 @@ </histogram> <histogram name="KeyboardAccessory.AccessorySheetTriggered" - enum="AccessorySheetTrigger" expires_after="M79"> + enum="AccessorySheetTrigger" expires_after="M81"> <owner>fhorschig@chromium.org</owner> <summary> Android only. Records how often the bottom sheet was opened or closed by a @@ -57978,13 +57984,34 @@ </summary> </histogram> +<histogram name="Media.CodecImage.CodecBufferWaitCoordinator.FrameTimedOut" + enum="BooleanTimedOut" expires_after="M85"> + <owner>vikassoni@chromium.org</owner> + <owner>liberato@chromium.org</owner> + <summary> + Whether we exceeded the timeout in CodecBufferWaitCoordinator:: + WaitForFrameAvailable and will proceed without a frame ready. + </summary> +</histogram> + +<histogram name="Media.CodecImage.CodecBufferWaitCoordinator.WaitTimeForFrame" + units="ms" expires_after="M85"> + <owner>vikassoni@chromium.org</owner> + <owner>liberato@chromium.org</owner> + <summary> + Time spent waiting for a frame to become available in a Non Overlay + (TextureOwner mode) so that MediaCodec can render it. This time is recorded + before the frame is rendered. + </summary> +</histogram> + <histogram name="Media.CodecImage.ImageReaderGLOwner.FrameTimedOut" enum="BooleanTimedOut" expires_after="M76"> <owner>ericrk@chromium.org</owner> <owner>liberato@chromium.org</owner> <summary> - Whether we exceeded the timeout in ImageReaderGLOwner:: - WaitForFrameAvailable and will proceed without a frame ready. + Removed 07/2019. This has been renamed to + Media.CodecImage.CodecBufferWaitCoordinator.FrameTimedOut </summary> </histogram> @@ -57992,9 +58019,8 @@ units="ms" expires_after="M78"> <owner>vikassoni@chromium.org</owner> <summary> - Time spent waiting for a frame to become available in a Non Overlay - (AImageReader mode) so that MediaCodec can render it. This time is recorded - before the frame is rendered. + Removed 07/2019. This has been renamed to + Media.CodecImage.CodecBufferWaitCoordinator.WaitTimeForFrame </summary> </histogram> @@ -58003,8 +58029,8 @@ <owner>ericrk@chromium.org</owner> <owner>liberato@chromium.org</owner> <summary> - Whether we exceeded the timeout in SurfaceTextureGLOwner:: - WaitForFrameAvailable and will proceed without a frame ready. + Removed 07/2019. This has been renamed to + Media.CodecImage.CodecBufferWaitCoordinator.FrameTimedOut </summary> </histogram> @@ -58012,9 +58038,8 @@ units="ms" expires_after="M78"> <owner>liberato@chromium.org</owner> <summary> - Time spent waiting for a frame to become available in a Non Overlay - (SurfaceTexture mode) so that MediaCodec can render it. This time is - recorded before the frame is rendered. + Removed 07/2019. This has been renamed to + Media.CodecImage.CodecBufferWaitCoordinator.WaitTimeForFrame </summary> </histogram> @@ -130637,7 +130662,7 @@ <summary> Counts how many languages are currently added to Chrome by the user but are not eligible for spellchecking because we have no Hunspell dictionaries for - them. This is recorded onceduring spellcheck initialization, and then once + them. This is recorded once during spellcheck initialization, and then once each time the user changes their Chrome languages. </summary> </histogram> @@ -130647,9 +130672,10 @@ <owner>yyushkina@google.com</owner> <owner>gujen@google.com</owner> <summary> - Counts how many spellcheck locales are currently enabled by the user but are - not supported by the Windows OS spellchecker because there are no language - packs installed for them. TThis is recorded onceduring spellcheck + Counts how many Hunspell spellcheck locales are currently enabled by the + user but are not supported by the Windows OS spellchecker because there are + no language packs installed for them. Locales that are not supported by + Hunspell are not counted. This is recorded once during spellcheck initialization, and then once each time the user changes which spellcheck languages are enabled. </summary> @@ -143489,6 +143515,16 @@ </summary> </histogram> +<histogram name="UMA.UserDemographics.Status" enum="UserDemographicsStatus" + expires_after="2020-01-07"> + <owner>vincb@google.com</owner> + <owner>chrome-metrics-team@google.com</owner> + <summary> + Report the status of the retrieval of user demographics from sync that are + reported to UMA. Reported each time UMA metrics are reported. + </summary> +</histogram> + <histogram name="UMA.XMLNodeDumpTime" units="ms" expires_after="2014-10-15"> <obsolete> Deprecated 2013. No longer tracked. @@ -147339,7 +147375,7 @@ </histogram> <histogram base="true" name="VR.Component.Assets.DurationUntilReady.OnEnter" - units="ms" expires_after="M80"> + units="ms" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary> @@ -147349,7 +147385,7 @@ </histogram> <histogram name="VR.Component.Assets.DurationUntilReady.OnRegisterComponent" - units="ms" expires_after="M80"> + units="ms" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary> @@ -147358,14 +147394,14 @@ </histogram> <histogram base="true" name="VR.Component.Assets.Status.OnEnter" - enum="VRComponentStatus" expires_after="M80"> + enum="VRComponentStatus" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary>Status of the VR assets component when entering a VR mode.</summary> </histogram> <histogram name="VR.Component.Assets.VersionAndStatus.OnLoad" - enum="VRAssetsLoadStatus" expires_after="M80"> + enum="VRAssetsLoadStatus" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary> @@ -147377,7 +147413,7 @@ </histogram> <histogram name="VR.Component.Assets.VersionAndStatus.OnUpdate" - enum="VRAssetsComponentUpdateStatus" expires_after="M80"> + enum="VRAssetsComponentUpdateStatus" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary> @@ -147390,7 +147426,7 @@ </histogram> <histogram name="VR.EnterVrBrowserWithoutFeatureModule" enum="BooleanSuccess" - expires_after="2020-01-01"> + expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <owner>xr-dev@chromium.org</owner> @@ -147403,14 +147439,14 @@ </histogram> <histogram base="true" name="VR.NetworkConnectionType.OnEnter" - enum="NetworkConnectionType" expires_after="M80"> + enum="NetworkConnectionType" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary>Network connection type when entering a VR mode.</summary> </histogram> <histogram name="VR.NetworkConnectionType.OnRegisterComponent" - enum="NetworkConnectionType" expires_after="M80"> + enum="NetworkConnectionType" expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary> @@ -147419,7 +147455,7 @@ </histogram> <histogram name="VR.Session.VoiceSearch.StartedCount" units="searches" - expires_after="M80"> + expires_after="2020-07-01"> <owner>xr-dev@chromium.org</owner> <summary> Number of times voice search is started in a single VR session. Recorded @@ -147429,7 +147465,7 @@ </histogram> <histogram name="VR.Shell.EncounteredSuppressedUI" enum="VRSuppressedElement" - expires_after="M80"> + expires_after="2020-07-01"> <owner>xr-dev@chromium.org</owner> <summary> We must suppress monocularly rendered ui elements in VR. This records which @@ -147472,8 +147508,10 @@ </histogram> <histogram name="VRDisplayPresentResult" enum="VRPresentationResult" - expires_after="M81"> + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> The result of calls to VRDisplay::requestPresent(). Reported twice per requestPresent() call, once to record the call, and once to record the @@ -147490,22 +147528,26 @@ </histogram> <histogram name="VRRuntimeVersion" units="normalized version" - expires_after="M80"> + expires_after="2020-07-01"> <owner>cassew@chromium.org</owner> <owner>samdrazin@chromium.org</owner> <summary>The version of the runtime being used for VR.</summary> </histogram> -<histogram name="VRSessionNavigationCount" expires_after="M81"> +<histogram name="VRSessionNavigationCount" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Count of navigations while in a VR session. Logged when a new disjoint session has begun, or when the session has ended in a non-continuable way. </summary> </histogram> -<histogram name="VRSessionTime" units="ms" expires_after="M81"> +<histogram name="VRSessionTime" units="ms" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> The duration of the VR session. Logged when a new disjoint session has begun, or when the session has ended in a non-continuable way. @@ -147524,16 +147566,20 @@ </summary> </histogram> -<histogram name="VRSessionVideoCount" expires_after="M80"> +<histogram name="VRSessionVideoCount" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Number of videos watched in a VR session. Logged when a new disjoint session has begun, or when the session has ended in a non-continuable way. </summary> </histogram> -<histogram name="VRSessionVideoTime" units="ms"> +<histogram name="VRSessionVideoTime" units="ms" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> The duration of a single session spent watching video in VR. Logged when a new disjoint session has begun, or when the session has ended in a @@ -147541,8 +147587,10 @@ </summary> </histogram> -<histogram name="VRViewerType" enum="VRViewerType" expires_after="M80"> +<histogram name="VRViewerType" enum="VRViewerType" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary>The type of headset being used for VR.</summary> </histogram> @@ -155124,15 +155172,20 @@ </summary> </histogram> -<histogram name="XR.RuntimeAvailable" enum="XRRuntimeAvailable"> +<histogram name="XR.RuntimeAvailable" enum="XRRuntimeAvailable" + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Indicates which VR APIs are installed. Recorded shortly after startup. </summary> </histogram> -<histogram name="XR.RuntimeUsed" enum="XRDeviceId"> +<histogram name="XR.RuntimeUsed" enum="XRDeviceId" expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Indicates which XR runtime was used for a session. Recorded when the session was successfully created. @@ -155140,8 +155193,10 @@ </histogram> <histogram name="XR.VRSession.StartAction" enum="VRSessionStartAction" - expires_after="M81"> + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> The action that triggered the transition into Chrome in VR, either from 2D or another VR app. @@ -155188,24 +155243,33 @@ </summary> </histogram> -<histogram name="XR.WebXR.PresentationSession" enum="VRPresentationStartAction"> +<histogram name="XR.WebXR.PresentationSession" enum="VRPresentationStartAction" + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> The action that triggered VR presentation, which is the display of web content on a VR device. </summary> </histogram> -<histogram name="XR.WebXR.ReferenceSpace.Requested" enum="XRReferenceSpaceType"> +<histogram name="XR.WebXR.ReferenceSpace.Requested" enum="XRReferenceSpaceType" + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Records which reference space was requested when a site calls XRSession.requestReferenceSpace(). </summary> </histogram> -<histogram name="XR.WebXR.ReferenceSpace.Succeeded" enum="XRReferenceSpaceType"> +<histogram name="XR.WebXR.ReferenceSpace.Succeeded" enum="XRReferenceSpaceType" + expires_after="2020-07-01"> <owner>billorr@chromium.org</owner> + <owner>cassew@chromium.org</owner> + <owner>samdrazin@chromium.org</owner> <summary> Records which reference spaces are successfully created when the promise returned by XRSession.requestReferenceSpace() is resolved. @@ -155474,6 +155538,11 @@ label="The peak load over all 30 second windows while the page is unactivated of an ad creative. This is measured as percentage of a cpu core used and capped at 100% for multicore systems."/> + <suffix name="AdFrames.PerFrame.PeakWindowStartTime" + label="The start time of the 30 second window associated with the + PeakWindowedPercent of the frame, relative to navigation start + of the page. Measured in milliseconds. Frames with no CPU usage + do not record a start time."/> <suffix name="AdFrames.PerFrame.PercentUsage" label="The average load of an ad creative across the life of the page. This is measured as percentage of a cpu core used and capped at @@ -155523,6 +155592,11 @@ label="The peak load over all 30 second windows during the lifetime of the page. This is measured as percentage of a cpu core used and capped at 100% for multicore systems."/> + <suffix name="FullPage.PeakWindowStartTime" + label="The start time of the 30 second window associated with the + PeakWindowedPercent of the page, relative to navigation start of + the page. Measured in milliseconds. Pages with no CPU usage do + not record a start time."/> <suffix name="FullPage.PercentUsage" label="The average load of the page across its lifetime. This is measured as percentage of a cpu core used and capped at 100% for @@ -169540,7 +169614,13 @@ </affected-histogram> <affected-histogram name="Sync.ModelTypeEntityChange3"/> <affected-histogram name="Sync.ModelTypeMemoryKB"/> - <affected-histogram name="Sync.NonReflectionUpdateFreshnessPossiblySkewed"/> + <affected-histogram name="Sync.NonReflectionUpdateFreshnessPossiblySkewed"> + <obsolete> + Deprecated 06/2019. Replaced by + Sync.NonReflectionUpdateFreshnessPossiblySkewed2. + </obsolete> + </affected-histogram> + <affected-histogram name="Sync.NonReflectionUpdateFreshnessPossiblySkewed2"/> <affected-histogram name="Sync.ReceivedDataTypeGetUpdatesResponseWithToken"> <obsolete> Deprecated 05/2019.
diff --git a/tools/polymer/polymer.gni b/tools/polymer/polymer.gni index 5c95c57..417ccf0c 100644 --- a/tools/polymer/polymer.gni +++ b/tools/polymer/polymer.gni
@@ -2,17 +2,20 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -common_namespace_rewrites = [ - "Polymer.PaperRippleBehavior|PaperRippleBehavior", +common_namespace_rewrites_polymer = [ "cr.ui.FocusOutlineManager|FocusOutlineManager", + "Polymer.PaperRippleBehavior|PaperRippleBehavior", + "Polymer.RenderStatus.afterNextRender|afterNextRender", + "Polymer.IronA11yAnnouncer|IronA11yAnnouncer", # TODO(dpapad): Add more such rewrites as they get discovered. ] common_auto_imports = [ - "ui/webui/resources/html/polymer.html|Polymer,html", - "ui/webui/resources/html/cr/ui/focus_outline_manager.html|FocusOutlineManager", + "third_party/polymer/v1_0/components-chromium/iron-a11y-announcer/iron-a11y-announcer.html|IronA11yAnnouncer", "third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior.html|PaperRippleBehavior", + "ui/webui/resources/html/cr/ui/focus_outline_manager.html|FocusOutlineManager", + "ui/webui/resources/html/polymer.html|Polymer,html", # TODO(dpapad): Add more auto-imports here, as needed. ] @@ -50,7 +53,7 @@ rebase_path(target_gen_dir, root_build_dir), ] - args += [ "--namespace_rewrites" ] + common_namespace_rewrites + args += [ "--namespace_rewrites" ] + common_namespace_rewrites_polymer if (defined(invoker.namespace_rewrites)) { args += invoker.namespace_rewrites }
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index cbb3313..03ad481 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -125,7 +125,7 @@ <item id="gcm_subscription" hash_code="56434025" type="0" deprecated="2019-04-10" content_hash_code="61632174" file_path=""/> <item id="gcm_unregistration" hash_code="119542033" type="0" content_hash_code="30144127" os_list="linux,windows" file_path="google_apis/gcm/engine/unregistration_request.cc"/> <item id="geo_language_provider" hash_code="52821843" type="1" second_id="96590038" content_hash_code="65327456" os_list="linux,windows" semantics_fields="1" policy_fields="3,4" file_path="components/language/content/browser/geo_language_provider.cc"/> - <item id="google_url_tracker" hash_code="5492492" type="0" content_hash_code="54474899" os_list="linux,windows" file_path="components/google/core/browser/google_url_tracker.cc"/> + <item id="google_url_tracker" hash_code="5492492" type="0" deprecated="2019-08-01" content_hash_code="54474899" file_path=""/> <item id="headless_url_request" hash_code="29865866" type="0" deprecated="2018-07-10" content_hash_code="76700151" file_path=""/> <item id="hintsfetcher_gethintsrequest" hash_code="34557599" type="0" content_hash_code="57003380" os_list="linux,windows" file_path="components/optimization_guide/hints_fetcher.cc"/> <item id="history_notice_utils_notice" hash_code="102595701" type="1" second_id="110307337" content_hash_code="130829410" os_list="linux,windows" semantics_fields="2,3,4" policy_fields="4" file_path="components/browsing_data/core/history_notice_utils.cc"/>
diff --git a/ui/android/java/src/org/chromium/ui/modelutil/ListModelBase.java b/ui/android/java/src/org/chromium/ui/modelutil/ListModelBase.java index 8676f54..c72a498b 100644 --- a/ui/android/java/src/org/chromium/ui/modelutil/ListModelBase.java +++ b/ui/android/java/src/org/chromium/ui/modelutil/ListModelBase.java
@@ -169,4 +169,9 @@ } notifyItemMoved(curIndex, newIndex); } + + /** Clear all items from the list. */ + public void clear() { + if (size() > 0) removeRange(0, size()); + } }
diff --git a/ui/android/java/src/org/chromium/ui/modelutil/ModelListAdapter.java b/ui/android/java/src/org/chromium/ui/modelutil/ModelListAdapter.java index 7a6c12c..fc20b49 100644 --- a/ui/android/java/src/org/chromium/ui/modelutil/ModelListAdapter.java +++ b/ui/android/java/src/org/chromium/ui/modelutil/ModelListAdapter.java
@@ -13,10 +13,10 @@ import org.chromium.base.VisibleForTesting; import org.chromium.ui.R; +import org.chromium.ui.modelutil.ListObservable.ListObserver; +import org.chromium.ui.modelutil.PropertyModelChangeProcessor.ViewBinder; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; /** * Adapter for providing data and views to a ListView. @@ -24,10 +24,8 @@ * To use, register a {@link PropertyModelChangeProcessor.ViewBinder} and {@link ViewBuilder} * for each view type in the list using * {@link #registerType(int, ViewBuilder, PropertyModelChangeProcessor.ViewBinder)}. - * Then call {@link #updateModels(List)} to provide a list of items (represented by PropertyModels) - * to display in the list. If the items in the list change (e.g. items are added, removed, or - * change order), call #updateModels again with the new list of items. NOTE: There are plans to - * change the API surface to work with a PropertyObservable instead. + * The constructor takes a {@link ListObservable} list in the form of a {@link ModelList}. Any + * changes that occur in the list will be automatically updated in the view. * * When creating a new view, ModelListAdapter will bind all set properties. When reusing/rebinding * a view, in addition to binding all properties set on the new model, properties that were @@ -38,32 +36,36 @@ * Additionally, ModelListAdapter will hook up a {@link PropertyModelChangeProcessor} when binding * views to ensure that changes to the PropertyModel for that list item are bound to the view. */ -public class ModelListAdapter extends BaseAdapter { - /** - * An interface to provide a means to build specific view types. - * @param <T> The type of view that the implementor will build. - */ - public interface ViewBuilder<T extends View> { - /** - * @return A new view to show in the list. - */ - T buildView(); - } +public class ModelListAdapter extends BaseAdapter implements MVCListAdapter { + private final ModelList mModelList; + private final SparseArray<Pair<ViewBuilder, ViewBinder>> mViewBuilderMap = new SparseArray<>(); + private final ListObserver<Void> mListObserver; - private final List<Pair<Integer, PropertyModel>> mModelList = new ArrayList<>(); - private final SparseArray<Pair<ViewBuilder, PropertyModelChangeProcessor.ViewBinder>> - mViewBuilderMap = new SparseArray<>(); + public ModelListAdapter(ModelList data) { + mModelList = data; + mListObserver = new ListObserver<Void>() { + @Override + public void onItemRangeInserted(ListObservable source, int index, int count) { + notifyDataSetChanged(); + } - /** - * Update the visible models (list items). - * @param models A list of {@link PropertyModel}s to display. The Integer property in the pair - * indicates the view type, while the PropertyModel contains the properties for the item - * to display. - */ - public void updateModels(List<Pair<Integer, PropertyModel>> models) { - mModelList.clear(); - mModelList.addAll(models); - notifyDataSetChanged(); + @Override + public void onItemRangeRemoved(ListObservable source, int index, int count) { + notifyDataSetChanged(); + } + + @Override + public void onItemRangeChanged( + ListObservable<Void> source, int index, int count, @Nullable Void payload) { + notifyDataSetChanged(); + } + + @Override + public void onItemMoved(ListObservable source, int curIndex, int newIndex) { + notifyDataSetChanged(); + } + }; + mModelList.addObserver(mListObserver); } @Override @@ -81,22 +83,16 @@ return position; } - /** - * Register a new view type that this adapter knows how to show. - * @param typeId The ID of the view type. This should not match any other view type registered - * in this adapter. - * @param builder A mechanism for building new views of the specified type. - * @param binder A means of binding a model to the provided view. - */ - public <T extends View> void registerType(int typeId, ViewBuilder<T> builder, - PropertyModelChangeProcessor.ViewBinder<PropertyModel, T, PropertyKey> binder) { + @Override + public <T extends View> void registerType( + int typeId, ViewBuilder<T> builder, ViewBinder<PropertyModel, T, PropertyKey> binder) { assert mViewBuilderMap.get(typeId) == null; mViewBuilderMap.put(typeId, new Pair<>(builder, binder)); } @Override public int getItemViewType(int position) { - return mModelList.get(position).first; + return mModelList.get(position).type; } @Override @@ -118,7 +114,7 @@ PropertyModel oldModel = null; if (convertView == null || convertView.getTag(R.id.view_type) == null || (int) convertView.getTag(R.id.view_type) != getItemViewType(position)) { - int modelTypeId = mModelList.get(position).first; + int modelTypeId = mModelList.get(position).type; convertView = mViewBuilderMap.get(modelTypeId).first.buildView(); // Since the view type returned by getView is not guaranteed to return a view of that @@ -130,9 +126,9 @@ oldModel = (PropertyModel) convertView.getTag(R.id.view_model); } - PropertyModel model = mModelList.get(position).second; + PropertyModel model = mModelList.get(position).model; PropertyModelChangeProcessor.ViewBinder binder = - mViewBuilderMap.get(mModelList.get(position).first).second; + mViewBuilderMap.get(mModelList.get(position).type).second; // 3. Attach a PropertyModelChangeProcessor and PropertyModel to the view (for #1/2 above // when re-using a view).
diff --git a/ui/android/junit/src/org/chromium/ui/modelutil/ModelListAdapterTest.java b/ui/android/junit/src/org/chromium/ui/modelutil/ModelListAdapterTest.java index f57326f..1879925 100644 --- a/ui/android/junit/src/org/chromium/ui/modelutil/ModelListAdapterTest.java +++ b/ui/android/junit/src/org/chromium/ui/modelutil/ModelListAdapterTest.java
@@ -5,7 +5,6 @@ package org.chromium.ui.modelutil; import android.text.TextUtils; -import android.util.Pair; import android.view.View; import org.junit.Assert; @@ -21,8 +20,6 @@ import org.chromium.base.test.util.CallbackHelper; import org.chromium.ui.R; -import java.util.ArrayList; -import java.util.List; import java.util.concurrent.TimeoutException; /** @@ -92,16 +89,13 @@ public void setUp() { MockitoAnnotations.initMocks(this); - mModelListAdapter = new ModelListAdapter(); + ModelListAdapter.ModelList testData = new ModelListAdapter.ModelList(); + mModel = new PropertyModel(BOOLEAN_PROPERTY, FLOAT_PROPERTY, INT_PROPERTY, OBJECT_PROPERTY); + testData.add(new ModelListAdapter.ListItem(VIEW_TYPE_1, mModel)); + + mModelListAdapter = new ModelListAdapter(testData); mModelListAdapter.registerType(VIEW_TYPE_1, new TestViewBuilder(), new TestViewBinder()); mModelListAdapter.registerType(VIEW_TYPE_2, new TestViewBuilder(), new TestViewBinder()); - - mModel = new PropertyModel(BOOLEAN_PROPERTY, FLOAT_PROPERTY, INT_PROPERTY, OBJECT_PROPERTY); - - List<Pair<Integer, PropertyModel>> testData = new ArrayList<>(); - testData.add(new Pair(VIEW_TYPE_1, mModel)); - - mModelListAdapter.updateModels(testData); } @Test
diff --git a/ui/android/junit/src/org/chromium/ui/modelutil/PropertyListModelTest.java b/ui/android/junit/src/org/chromium/ui/modelutil/PropertyListModelTest.java index 34f9235..289df90 100644 --- a/ui/android/junit/src/org/chromium/ui/modelutil/PropertyListModelTest.java +++ b/ui/android/junit/src/org/chromium/ui/modelutil/PropertyListModelTest.java
@@ -26,7 +26,7 @@ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) public class PropertyListModelTest implements ListObservable.ListObserver<PropertyKey> { - private static final int METHOD_COUNT = 31; + private static final int METHOD_COUNT = 32; private static final PropertyModel.WritableIntPropertyKey INTEGER_KEY = new PropertyModel.WritableIntPropertyKey();
diff --git a/ui/base/class_property.cc b/ui/base/class_property.cc index d6a5378..86c0c48 100644 --- a/ui/base/class_property.cc +++ b/ui/base/class_property.cc
@@ -9,12 +9,20 @@ namespace ui { -PropertyHandler::PropertyHandler() {} +PropertyHandler::PropertyHandler() = default; + +PropertyHandler::PropertyHandler(PropertyHandler&& other) = default; PropertyHandler::~PropertyHandler() { ClearProperties(); } +void PropertyHandler::AcquireAllPropertiesFrom(PropertyHandler&& other) { + for (auto& prop_pair : other.prop_map_) + prop_map_[std::move(prop_pair.first)] = std::move(prop_pair.second); + other.prop_map_.clear(); +} + int64_t PropertyHandler::SetPropertyInternal(const void* key, const char* name, PropertyDeallocator deallocator,
diff --git a/ui/base/class_property.h b/ui/base/class_property.h index d937c57..ab892269 100644 --- a/ui/base/class_property.h +++ b/ui/base/class_property.h
@@ -67,7 +67,14 @@ class UI_BASE_EXPORT PropertyHandler { public: PropertyHandler(); - ~PropertyHandler(); + PropertyHandler(PropertyHandler&& other); + virtual ~PropertyHandler(); + PropertyHandler& operator=(PropertyHandler&& rhs) = default; + + // Takes the ownership of all the properties in |other|, overwriting any + // similarly-keyed existing properties without affecting existing ones with + // different keys. + void AcquireAllPropertiesFrom(PropertyHandler&& other); // Sets the |value| of the given class |property|. Setting to the default // value (e.g., NULL) removes the property. The lifetime of objects set as
diff --git a/ui/base/class_property_unittest.cc b/ui/base/class_property_unittest.cc index 05c7137..ffc2dca 100644 --- a/ui/base/class_property_unittest.cc +++ b/ui/base/class_property_unittest.cc
@@ -157,6 +157,40 @@ EXPECT_EQ(p3, TestProperty::last_deleted()); } +TEST(PropertyTest, AcquireAllPropertiesFrom) { + // Set some properties on src, including an owned property. + std::unique_ptr<PropertyHandler> src = std::make_unique<PropertyHandler>(); + void* last_deleted = TestProperty::last_deleted(); + EXPECT_FALSE(src->GetProperty(kOwnedKey)); + TestProperty* p1 = new TestProperty(); + src->SetProperty(kOwnedKey, p1); + src->SetProperty(kIntKey, INT_MAX); + + // dest will take ownership of the owned property. Existing properties with + // similar keys will be overwritten. Existing properties with different keys + // will remain unchanged. + std::unique_ptr<PropertyHandler> dest = std::make_unique<PropertyHandler>(); + dest->SetProperty(kIntKey, INT_MIN); + dest->SetProperty(kStringKey, kTestStringValue); + + dest->AcquireAllPropertiesFrom(std::move(*src)); + EXPECT_EQ(p1, dest->GetProperty(kOwnedKey)); // Ownership taken. + EXPECT_EQ(INT_MAX, dest->GetProperty(kIntKey)); // Overwritten. + // Remains unchanged. + EXPECT_EQ(std::string(kTestStringValue), dest->GetProperty(kStringKey)); + + // src no longer has properties. + EXPECT_TRUE(src->GetAllPropertyKeys().empty()); + EXPECT_FALSE(src->GetProperty(kOwnedKey)); + EXPECT_EQ(kDefaultIntValue, src->GetProperty(kIntKey)); + // Destroy src. Owned property remains alive. + src.reset(); + EXPECT_EQ(last_deleted, TestProperty::last_deleted()); + // Destroy dest, now the owned property is deleted. + dest.reset(); + EXPECT_EQ(p1, TestProperty::last_deleted()); +} + TEST(PropertyTest, AssignableProperty) { PropertyHandler h;
diff --git a/ui/chromeos/ime/candidate_view_unittest.cc b/ui/chromeos/ime/candidate_view_unittest.cc index 730bb38f..24edee4 100644 --- a/ui/chromeos/ime/candidate_view_unittest.cc +++ b/ui/chromeos/ime/candidate_view_unittest.cc
@@ -57,7 +57,7 @@ } widget_ = new views::Widget(); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->Show(); aura::Window* native_window = widget_->GetNativeWindow();
diff --git a/ui/compositor/layer_unittest.cc b/ui/compositor/layer_unittest.cc index 486a0b1..3a894775 100644 --- a/ui/compositor/layer_unittest.cc +++ b/ui/compositor/layer_unittest.cc
@@ -774,7 +774,13 @@ EXPECT_TRUE(d3.painted()); } -TEST_F(LayerWithDelegateTest, Cloning) { +// crbug.com/989936 +#if defined(OS_LINUX) && defined(UNDEFINED_SANITIZER) +#define MAYBE_Cloning DISABLED_Cloning +#else +#define MAYBE_Cloning Cloning +#endif +TEST_F(LayerWithDelegateTest, MAYBE_Cloning) { std::unique_ptr<Layer> layer = CreateLayer(LAYER_SOLID_COLOR); gfx::Transform transform; @@ -1039,8 +1045,14 @@ ASSERT_TRUE(roundtrip); EXPECT_EQ(name, *roundtrip); } - -TEST_F(LayerWithNullDelegateTest, SwitchLayerPreservesCCLayerState) { +// crbug.com/989936 +#if defined(OS_LINUX) && defined(UNDEFINED_SANITIZER) +#define MAYBE_SwitchLayerPreservesCCLayerState \ + DISABLED_SwitchLayerPreservesCCLayerState +#else +#define MAYBE_SwitchLayerPreservesCCLayerState SwitchLayerPreservesCCLayerState +#endif +TEST_F(LayerWithNullDelegateTest, MAYBE_SwitchLayerPreservesCCLayerState) { std::unique_ptr<Layer> l1 = CreateLayer(LAYER_SOLID_COLOR); l1->SetFillsBoundsOpaquely(true); l1->SetVisible(false);
diff --git a/ui/events/blink/blink_features.cc b/ui/events/blink/blink_features.cc index 54965ec..b173f77 100644 --- a/ui/events/blink/blink_features.cc +++ b/ui/events/blink/blink_features.cc
@@ -28,7 +28,7 @@ "DontSendKeyEventsToJavascript", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kSkipTouchEventFilter{"SkipTouchEventFilter", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const char kSkipTouchEventFilterTypeParamName[] = "type"; const char kSkipTouchEventFilterTypeParamValueDiscrete[] = "discrete"; const char kSkipTouchEventFilterTypeParamValueAll[] = "all"; @@ -37,4 +37,4 @@ const char kSkipTouchEventFilterFilteringProcessParamValueBrowser[] = "browser"; const char kSkipTouchEventFilterFilteringProcessParamValueBrowserAndRenderer[] = "browser_and_renderer"; -} +} // namespace features
diff --git a/ui/message_center/views/message_popup_view.cc b/ui/message_center/views/message_popup_view.cc index 0751647..9626c08e 100644 --- a/ui/message_center/views/message_popup_view.cc +++ b/ui/message_center/views/message_popup_view.cc
@@ -128,7 +128,7 @@ params.native_widget = new views::DesktopNativeWidgetAura(widget); #endif - widget->Init(params); + widget->Init(std::move(params)); #if defined(OS_CHROMEOS) // On Chrome OS, this widget is shown in the shelf container. It means this
diff --git a/ui/message_center/views/notification_header_view_unittest.cc b/ui/message_center/views/notification_header_view_unittest.cc index 42b6fa1..86e41a4f 100644 --- a/ui/message_center/views/notification_header_view_unittest.cc +++ b/ui/message_center/views/notification_header_view_unittest.cc
@@ -32,7 +32,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); views::View* container = new views::View(); widget_.SetContentsView(container);
diff --git a/ui/message_center/views/notification_view_md_unittest.cc b/ui/message_center/views/notification_view_md_unittest.cc index 271de35c..da33719 100644 --- a/ui/message_center/views/notification_view_md_unittest.cc +++ b/ui/message_center/views/notification_view_md_unittest.cc
@@ -321,7 +321,7 @@ views::Widget::InitParams init_params( CreateParams(views::Widget::InitParams::TYPE_POPUP)); widget_ = new views::Widget(); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(notification_view_.get()); widget_->SetSize(notification_view_->GetPreferredSize()); widget_->Show();
diff --git a/ui/message_center/views/slide_out_controller_unittest.cc b/ui/message_center/views/slide_out_controller_unittest.cc index ebd67735..16ea607 100644 --- a/ui/message_center/views/slide_out_controller_unittest.cc +++ b/ui/message_center/views/slide_out_controller_unittest.cc
@@ -62,7 +62,7 @@ CreateParams(views::Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); views::View* root = widget_->GetRootView(); views::View* target_ = new views::View();
diff --git a/ui/ozone/platform/x11/x11_window_ozone.cc b/ui/ozone/platform/x11/x11_window_ozone.cc index 39b062b..ae01fad 100644 --- a/ui/ozone/platform/x11/x11_window_ozone.cc +++ b/ui/ozone/platform/x11/x11_window_ozone.cc
@@ -60,13 +60,6 @@ } config.bounds = properties.bounds; - -#if defined(OS_CHROMEOS) - config.activatable = !UseTestConfigForPlatformWindows(); -#else - config.activatable = properties.activatable; -#endif - config.force_show_in_taskbar = properties.force_show_in_taskbar; config.keep_on_top = properties.keep_on_top; config.visible_on_all_workspaces = properties.visible_on_all_workspaces; @@ -76,6 +69,12 @@ config.wm_class_class = properties.wm_class_class; config.wm_role_name = properties.wm_role_name; + // TODO(nickdiego): {Use,Enable}TestConfigForPlatformWindows are used by test + // infra to disable platform windows activation. Figure out another way to do + // this in case Widget::InitParams::activation is needed in the future. + config.activatable = + properties.activatable && !UseTestConfigForPlatformWindows(); + return config; }
diff --git a/ui/platform_window/platform_window.h b/ui/platform_window/platform_window.h index f27b99f..1f56add8 100644 --- a/ui/platform_window/platform_window.h +++ b/ui/platform_window/platform_window.h
@@ -25,7 +25,7 @@ // underlying platform windowing system (i.e. X11/Win/OSX). class PlatformWindow : public PropertyHandler { public: - virtual ~PlatformWindow() {} + ~PlatformWindow() override = default; virtual void Show() = 0; virtual void Hide() = 0;
diff --git a/ui/platform_window/platform_window_init_properties.h b/ui/platform_window/platform_window_init_properties.h index 18af35a..3028a1a 100644 --- a/ui/platform_window/platform_window_init_properties.h +++ b/ui/platform_window/platform_window_init_properties.h
@@ -57,7 +57,7 @@ fuchsia::ui::views::ViewToken view_token; #endif - bool activatable = false; + bool activatable = true; bool force_show_in_taskbar; bool keep_on_top = false; bool visible_on_all_workspaces = false;
diff --git a/ui/resources/BUILD.gn b/ui/resources/BUILD.gn index 4daf59a..a1be356 100644 --- a/ui/resources/BUILD.gn +++ b/ui/resources/BUILD.gn
@@ -40,7 +40,7 @@ source = "../webui/resources/webui_resources.grd" deps = [ - "//ui/webui/resources/js:modulize", + "//ui/webui/resources:modulize", ] # The .grd contains references to generated files.
diff --git a/ui/views/accessibility/ax_aura_obj_cache_unittest.cc b/ui/views/accessibility/ax_aura_obj_cache_unittest.cc index 54a4aff..94089d8 100644 --- a/ui/views/accessibility/ax_aura_obj_cache_unittest.cc +++ b/ui/views/accessibility/ax_aura_obj_cache_unittest.cc
@@ -87,7 +87,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget->Init(params); + parent_widget->Init(std::move(params)); parent_widget->GetNativeWindow()->SetTitle( base::ASCIIToUTF16("ParentWindow")); parent_widget->Show(); @@ -99,7 +99,7 @@ params.child = true; params.bounds = gfx::Rect(100, 100, 200, 200); params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET; - child_widget->Init(params); + child_widget->Init(std::move(params)); child_widget->GetNativeWindow()->SetTitle(base::ASCIIToUTF16("ChildWindow")); child_widget->Show();
diff --git a/ui/views/accessibility/ax_tree_source_views_unittest.cc b/ui/views/accessibility/ax_tree_source_views_unittest.cc index aeff646..c78bbdd 100644 --- a/ui/views/accessibility/ax_tree_source_views_unittest.cc +++ b/ui/views/accessibility/ax_tree_source_views_unittest.cc
@@ -48,7 +48,7 @@ params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(11, 22, 333, 444); params.context = GetContext(); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetContentsView(new View()); label1_ = new Label(base::ASCIIToUTF16("Label 1"));
diff --git a/ui/views/accessibility/ax_virtual_view_unittest.cc b/ui/views/accessibility/ax_virtual_view_unittest.cc index e7520c3..f8c2611 100644 --- a/ui/views/accessibility/ax_virtual_view_unittest.cc +++ b/ui/views/accessibility/ax_virtual_view_unittest.cc
@@ -42,7 +42,7 @@ widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); button_ = new TestButton; button_->SetSize(gfx::Size(20, 20)); widget_->GetContentsView()->AddChildView(button_);
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc index a0727e4..6c137463 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc
@@ -48,7 +48,7 @@ widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); button_ = new TestButton(); button_->SetID(NON_DEFAULT_VIEW_ID); @@ -412,7 +412,7 @@ std::unique_ptr<Widget> widget(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); View* root = widget->GetRootView();
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc index 137f4087..bc8bdeb1 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc
@@ -62,7 +62,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); View* content = new View; widget.SetContentsView(content); @@ -104,7 +104,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); View* content = new View; widget.SetContentsView(content); @@ -174,7 +174,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 400, 200); - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.Show(); // Initially it has 1 child. @@ -198,7 +198,7 @@ // we test with child = true, making it a child widget. child_init_params.child = GetParam(); - child_widget.Init(child_init_params); + child_widget.Init(std::move(child_init_params)); child_widget.Show(); // Now the IAccessible for the parent widget should have 2 children. @@ -250,7 +250,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); View* content = new View; widget.SetContentsView(content); @@ -315,7 +315,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.CloseNow(); LONG child_count = 0; @@ -332,7 +332,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); ComPtr<IAccessible> accessible( widget.GetRootView()->GetNativeViewAccessible()); @@ -349,7 +349,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); View* contents_view = new View; widget.SetContentsView(contents_view);
diff --git a/ui/views/accessible_pane_view_unittest.cc b/ui/views/accessible_pane_view_unittest.cc index b7dc491..2f990ff 100644 --- a/ui/views/accessible_pane_view_unittest.cc +++ b/ui/views/accessible_pane_view_unittest.cc
@@ -79,7 +79,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); root->AddChildView(test_view); widget->Show(); @@ -108,7 +108,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params_main.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params_main.bounds = gfx::Rect(0, 0, 20, 20); - widget_main->Init(params_main); + widget_main->Init(std::move(params_main)); View* root_main = widget_main->GetRootView(); root_main->AddChildView(test_view_main); widget_main->Show(); @@ -123,7 +123,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params_bar.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params_bar.bounds = gfx::Rect(50, 50, 650, 650); - widget_bar->Init(params_bar); + widget_bar->Init(std::move(params_bar)); View* root_bar = widget_bar->GetRootView(); root_bar->AddChildView(test_view_bar); widget_bar->Show(); @@ -164,7 +164,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); root->AddChildView(test_view); root->AddChildView(test_view_2); @@ -195,7 +195,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); root->AddChildView(original_test_view); root->AddChildView(test_view); @@ -243,7 +243,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget.Init(params); + widget.Init(std::move(params)); View* root = widget.GetRootView(); root->AddChildView(test_view1); root->AddChildView(test_view2);
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.cc b/ui/views/bubble/bubble_dialog_delegate_view.cc index 161f0b5..e7d3bbcb 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view.cc
@@ -106,7 +106,7 @@ ? Widget::InitParams::ACTIVATABLE_YES : Widget::InitParams::ACTIVATABLE_NO; bubble->OnBeforeBubbleWidgetInit(&bubble_params, bubble_widget); - bubble_widget->Init(bubble_params); + bubble_widget->Init(std::move(bubble_params)); #if !defined(OS_MACOSX) // On Mac, having a parent window creates a permanent stacking order, so // there's no need to do this. Also, calling StackAbove() on Mac shows the
diff --git a/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc b/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc index f0ada20..144314d 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc
@@ -107,7 +107,7 @@ Widget* widget = new Widget(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ui/views/bubble/bubble_frame_view_unittest.cc b/ui/views/bubble/bubble_frame_view_unittest.cc index d4b6ed7..5b320201 100644 --- a/ui/views/bubble/bubble_frame_view_unittest.cc +++ b/ui/views/bubble/bubble_frame_view_unittest.cc
@@ -97,7 +97,7 @@ test_base->CreateParams(Widget::InitParams::TYPE_BUBBLE); params.delegate = widget_delegate_.get(); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); } ~TestBubbleFrameView() override = default; @@ -911,7 +911,7 @@ public: explicit TestAnchor(Widget::InitParams params) { params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); widget_.Show(); }
diff --git a/ui/views/cocoa/bridged_native_widget_interactive_uitest.mm b/ui/views/cocoa/bridged_native_widget_interactive_uitest.mm index 736f611..b17a954 100644 --- a/ui/views/cocoa/bridged_native_widget_interactive_uitest.mm +++ b/ui/views/cocoa/bridged_native_widget_interactive_uitest.mm
@@ -55,7 +55,7 @@ init_params.bounds = gfx::Rect(100, 100, 300, 200); init_params.delegate = new ResizableDelegateView; widget_.reset(new Widget); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); } void TearDown() override { @@ -286,7 +286,7 @@ init_params.delegate = widget_delegate; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(100, 200, 400, 300); - widget.Init(init_params); + widget.Init(std::move(init_params)); WidgetActivationWaiter activation_waiter(&widget, true); widget.Show();
diff --git a/ui/views/cocoa/bridged_native_widget_unittest.mm b/ui/views/cocoa/bridged_native_widget_unittest.mm index bb58136..ebe176a 100644 --- a/ui/views/cocoa/bridged_native_widget_unittest.mm +++ b/ui/views/cocoa/bridged_native_widget_unittest.mm
@@ -304,7 +304,7 @@ using NativeWidgetMac::GetNSWindowHost; // internal::NativeWidgetPrivate: - void InitNativeWidget(const Widget::InitParams& params) override { + void InitNativeWidget(Widget::InitParams params) override { ownership_ = params.ownership; base::scoped_nsobject<NativeWidgetMacNSWindow> window( @@ -377,23 +377,16 @@ ui::MaterialDesignController::Initialize(); - init_params_.native_widget = native_widget_mac_; - - // Use a frameless window, otherwise Widget will try to center the window - // before the tests covering the Init() flow are ready to do that. - init_params_.type = Widget::InitParams::TYPE_WINDOW_FRAMELESS; - - // To control the lifetime without an actual window that must be closed, - // tests in this file need to use WIDGET_OWNS_NATIVE_WIDGET. - init_params_.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - - // Opacity defaults to "infer" which is usually updated by ViewsDelegate. - init_params_.opacity = Widget::InitParams::OPAQUE_WINDOW; - - init_params_.bounds = gfx::Rect(100, 100, 100, 100); + Widget::InitParams init_params; + init_params.native_widget = native_widget_mac_; + init_params.type = type_; + init_params.ownership = ownership_; + init_params.opacity = opacity_; + init_params.bounds = bounds_; + init_params.shadow_type = shadow_type_; if (native_widget_mac_) - native_widget_mac_->GetWidget()->Init(init_params_); + native_widget_mac_->GetWidget()->Init(std::move(init_params)); } void TearDown() override { @@ -414,8 +407,19 @@ std::unique_ptr<Widget> widget_; MockNativeWidgetMac* native_widget_mac_; // Weak. Owned by |widget_|. - // Make the InitParams available to tests to cover initialization codepaths. - Widget::InitParams init_params_; + // Use a frameless window, otherwise Widget will try to center the window + // before the tests covering the Init() flow are ready to do that. + Widget::InitParams::Type type_ = Widget::InitParams::TYPE_WINDOW_FRAMELESS; + // To control the lifetime without an actual window that must be closed, + // tests in this file need to use WIDGET_OWNS_NATIVE_WIDGET. + Widget::InitParams::Ownership ownership_ = + Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; + // Opacity defaults to "infer" which is usually updated by ViewsDelegate. + Widget::InitParams::WindowOpacity opacity_ = + Widget::InitParams::OPAQUE_WINDOW; + gfx::Rect bounds_ = gfx::Rect(100, 100, 100, 100); + Widget::InitParams::ShadowType shadow_type_ = + Widget::InitParams::SHADOW_TYPE_DEFAULT; private: TestViewsDelegate test_views_delegate_; @@ -544,7 +548,7 @@ textfield->set_controller(this); view_->RemoveAllChildViews(true); view_->AddChildView(textfield); - textfield->SetBoundsRect(init_params_.bounds); + textfield->SetBoundsRect(bounds_); // Request focus so the InputMethod can dispatch events to the RootView, and // have them delivered to the textfield. Note that focusing a textfield @@ -863,11 +867,17 @@ void CreateNewWidgetToInit() { widget_.reset(new Widget); native_widget_mac_ = new MockNativeWidgetMac(widget_.get()); - init_params_.native_widget = native_widget_mac_; } void PerformInit() { - widget_->Init(init_params_); + Widget::InitParams init_params; + init_params.native_widget = native_widget_mac_; + init_params.type = type_; + init_params.ownership = ownership_; + init_params.opacity = opacity_; + init_params.bounds = bounds_; + init_params.shadow_type = shadow_type_; + widget_->Init(std::move(init_params)); } private: @@ -890,9 +900,9 @@ // Tests the shadow type given in InitParams. TEST_F(BridgedNativeWidgetInitTest, ShadowType) { // Verify Widget::InitParam defaults and arguments added from SetUp(). - EXPECT_EQ(Widget::InitParams::TYPE_WINDOW_FRAMELESS, init_params_.type); - EXPECT_EQ(Widget::InitParams::OPAQUE_WINDOW, init_params_.opacity); - EXPECT_EQ(Widget::InitParams::SHADOW_TYPE_DEFAULT, init_params_.shadow_type); + EXPECT_EQ(Widget::InitParams::TYPE_WINDOW_FRAMELESS, type_); + EXPECT_EQ(Widget::InitParams::OPAQUE_WINDOW, opacity_); + EXPECT_EQ(Widget::InitParams::SHADOW_TYPE_DEFAULT, shadow_type_); CreateNewWidgetToInit(); EXPECT_FALSE( @@ -905,7 +915,7 @@ [bridge_window() hasShadow]); // SHADOW_TYPE_DEFAULT means a shadow. CreateNewWidgetToInit(); - init_params_.shadow_type = Widget::InitParams::SHADOW_TYPE_NONE; + shadow_type_ = Widget::InitParams::SHADOW_TYPE_NONE; PerformInit(); EXPECT_FALSE([bridge_window() hasShadow]); // Preserves lack of shadow. @@ -915,7 +925,7 @@ EXPECT_FALSE( [bridge_window() hasShadow]); // SHADOW_TYPE_NONE removes shadow. - init_params_.shadow_type = Widget::InitParams::SHADOW_TYPE_DEFAULT; + shadow_type_ = Widget::InitParams::SHADOW_TYPE_DEFAULT; CreateNewWidgetToInit(); PerformInit(); EXPECT_TRUE([bridge_window() hasShadow]); // Preserves shadow.
diff --git a/ui/views/controls/button/button.cc b/ui/views/controls/button/button.cc index 7c7562e2..68a3ec7 100644 --- a/ui/views/controls/button/button.cc +++ b/ui/views/controls/button/button.cc
@@ -231,7 +231,10 @@ if (state_ != STATE_DISABLED) { const bool should_enter_pushed = ShouldEnterPushedState(event); const bool should_show_pending = - should_enter_pushed && notify_action_ == NOTIFY_ON_RELEASE && !InDrag(); + should_enter_pushed && + button_controller_->notify_action() == + ButtonController::NotifyAction::NOTIFY_ON_RELEASE && + !InDrag(); if (HitTestPoint(event.location())) { SetState(should_enter_pushed ? STATE_PRESSED : STATE_HOVERED); if (should_show_pending && GetInkDrop()->GetTargetInkDropState() ==
diff --git a/ui/views/controls/button/button.h b/ui/views/controls/button/button.h index cc11bbff..e14c113e 100644 --- a/ui/views/controls/button/button.h +++ b/ui/views/controls/button/button.h
@@ -60,12 +60,6 @@ STATE_COUNT, }; - // An enum describing the events on which a button should notify its listener. - enum NotifyAction { - NOTIFY_ON_PRESS, - NOTIFY_ON_RELEASE, - }; - // An enum describing the events on which a button should be clicked for a // given key event. enum KeyClickAction { @@ -133,13 +127,6 @@ animate_on_state_change_ = value; } - // Sets the event on which the button should notify its listener. - void set_notify_action(NotifyAction notify_action) { - notify_action_ = notify_action; - } - - NotifyAction notify_action() const { return notify_action_; } - void set_hide_ink_drop_when_showing_context_menu( bool hide_ink_drop_when_showing_context_menu) { hide_ink_drop_when_showing_context_menu_ = @@ -352,9 +339,6 @@ // See description above setter. bool request_focus_on_press_ = false; - // The event on which the button should notify its listener. - NotifyAction notify_action_ = NOTIFY_ON_RELEASE; - // True when a button click should trigger an animation action on // ink_drop_delegate(). bool has_ink_drop_action_on_click_ = false;
diff --git a/ui/views/controls/button/button_controller.cc b/ui/views/controls/button/button_controller.cc index 03741cd..8998a0c 100644 --- a/ui/views/controls/button/button_controller.cc +++ b/ui/views/controls/button/button_controller.cc
@@ -28,7 +28,7 @@ } button_controller_delegate_->RequestFocusFromEvent(); if (button_controller_delegate_->IsTriggerableEvent(event) && - button_->notify_action() == Button::NOTIFY_ON_PRESS) { + notify_action_ == ButtonController::NOTIFY_ON_PRESS) { button_controller_delegate_->NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). @@ -43,7 +43,7 @@ } else { button_->SetState(Button::STATE_HOVERED); if (button_controller_delegate_->IsTriggerableEvent(event) && - button_->notify_action() == Button::NOTIFY_ON_RELEASE) { + notify_action_ == ButtonController::NOTIFY_ON_RELEASE) { button_controller_delegate_->NotifyClick(event); // NOTE: We may be deleted at this point (by the listener's notification // handler). @@ -51,7 +51,7 @@ } } } - if (button_->notify_action() == Button::NOTIFY_ON_RELEASE) + if (notify_action_ == ButtonController::NOTIFY_ON_RELEASE) button_controller_delegate_->OnClickCanceled(event); }
diff --git a/ui/views/controls/button/button_controller.h b/ui/views/controls/button/button_controller.h index c319459..d027ec7 100644 --- a/ui/views/controls/button/button_controller.h +++ b/ui/views/controls/button/button_controller.h
@@ -19,8 +19,21 @@ std::unique_ptr<ButtonControllerDelegate> delegate); virtual ~ButtonController(); + // An enum describing the events on which a button should notify its listener. + enum NotifyAction { + NOTIFY_ON_PRESS, + NOTIFY_ON_RELEASE, + }; + Button* button() { return button_; } + // Sets the event on which the button's listener should be notified. + void set_notify_action(NotifyAction notify_action) { + notify_action_ = notify_action; + } + + NotifyAction notify_action() const { return notify_action_; } + // Methods that parallel View::On<Event> handlers: virtual bool OnMousePressed(const ui::MouseEvent& event); virtual void OnMouseReleased(const ui::MouseEvent& event); @@ -49,6 +62,9 @@ // TODO(cyan): Remove |button_| and access everything via the delegate. std::unique_ptr<ButtonControllerDelegate> button_controller_delegate_; + // The event on which the button's listener should be notified. + NotifyAction notify_action_ = NOTIFY_ON_RELEASE; + DISALLOW_COPY_AND_ASSIGN(ButtonController); };
diff --git a/ui/views/controls/button/button_unittest.cc b/ui/views/controls/button/button_unittest.cc index aaa6b35..0ddde19 100644 --- a/ui/views/controls/button/button_unittest.cc +++ b/ui/views/controls/button/button_unittest.cc
@@ -21,6 +21,7 @@ #include "ui/views/animation/test/test_ink_drop.h" #include "ui/views/animation/test/test_ink_drop_host.h" #include "ui/views/context_menu_controller.h" +#include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/button/button_observer.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/button/image_button.h" @@ -174,7 +175,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); button_ = std::make_unique<TestButton>(false); @@ -260,7 +261,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(700, 700, 10, 10); - second_widget.Init(params); + second_widget.Init(std::move(params)); second_widget.Show(); second_widget.GetNativeWindow()->SetCapture(); @@ -333,7 +334,8 @@ // Set the notify action to its listener on mouse press. button()->Reset(); - button()->set_notify_action(Button::NOTIFY_ON_PRESS); + button()->button_controller()->set_notify_action( + ButtonController::NotifyAction::NOTIFY_ON_PRESS); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); @@ -367,7 +369,8 @@ // Set the notify action to its listener on mouse press. button()->Reset(); - button()->set_notify_action(Button::NOTIFY_ON_PRESS); + button()->button_controller()->set_notify_action( + ButtonController::NotifyAction::NOTIFY_ON_PRESS); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_RIGHT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON)); @@ -622,7 +625,8 @@ TestInkDrop* ink_drop = new TestInkDrop(); CreateButtonWithInkDrop(base::WrapUnique(ink_drop), false); - button()->set_notify_action(Button::NOTIFY_ON_RELEASE); + button()->button_controller()->set_notify_action( + ButtonController::NotifyAction::NOTIFY_ON_RELEASE); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), @@ -663,7 +667,8 @@ TestInkDrop* ink_drop = new TestInkDrop(); CreateButtonWithInkDrop(base::WrapUnique(ink_drop), true); - button()->set_notify_action(Button::NOTIFY_ON_PRESS); + button()->button_controller()->set_notify_action( + ButtonController::NotifyAction::NOTIFY_ON_PRESS); button()->OnMousePressed(ui::MouseEvent( ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(),
diff --git a/ui/views/controls/button/checkbox_unittest.cc b/ui/views/controls/button/checkbox_unittest.cc index 7b94b9d..e9845d0 100644 --- a/ui/views/controls/button/checkbox_unittest.cc +++ b/ui/views/controls/button/checkbox_unittest.cc
@@ -27,7 +27,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); checkbox_ = new Checkbox(base::string16());
diff --git a/ui/views/controls/button/label_button_unittest.cc b/ui/views/controls/button/label_button_unittest.cc index c55ee6e14..49b75a6c 100644 --- a/ui/views/controls/button/label_button_unittest.cc +++ b/ui/views/controls/button/label_button_unittest.cc
@@ -516,7 +516,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 20, 20); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); button_ = new LabelButton(nullptr, base::string16());
diff --git a/ui/views/controls/button/menu_button_controller.cc b/ui/views/controls/button/menu_button_controller.cc index 74b0644..cfebc7f 100644 --- a/ui/views/controls/button/menu_button_controller.cc +++ b/ui/views/controls/button/menu_button_controller.cc
@@ -21,11 +21,12 @@ namespace views { namespace { -ui::EventType NotifyActionToMouseEventType(Button::NotifyAction notify_action) { +ui::EventType NotifyActionToMouseEventType( + ButtonController::NotifyAction notify_action) { switch (notify_action) { - case Button::NOTIFY_ON_PRESS: + case ButtonController::NOTIFY_ON_PRESS: return ui::ET_MOUSE_PRESSED; - case Button::NOTIFY_ON_RELEASE: + case ButtonController::NOTIFY_ON_RELEASE: return ui::ET_MOUSE_RELEASED; } } @@ -80,8 +81,7 @@ : ButtonController(button, std::move(delegate)), listener_(listener) { // Triggers on button press by default, unless drag-and-drop is enabled, see // MenuButtonController::IsTriggerableEventType. - // TODO(cyan): Move NotifyAction into ButtonController. - button->set_notify_action(Button::NOTIFY_ON_PRESS); + set_notify_action(ButtonController::NOTIFY_ON_PRESS); } MenuButtonController::~MenuButtonController() = default; @@ -289,7 +289,7 @@ ui::EventType active_on = delegate()->GetDragOperations(mouse_event->location()) == ui::DragDropTypes::DRAG_NONE - ? NotifyActionToMouseEventType(button()->notify_action()) + ? NotifyActionToMouseEventType(notify_action()) : ui::ET_MOUSE_RELEASED; return event.type() == active_on; }
diff --git a/ui/views/controls/button/menu_button_unittest.cc b/ui/views/controls/button/menu_button_unittest.cc index f296f95a..ab584bf 100644 --- a/ui/views/controls/button/menu_button_unittest.cc +++ b/ui/views/controls/button/menu_button_unittest.cc
@@ -113,7 +113,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); } Widget* widget_ = nullptr;
diff --git a/ui/views/controls/button/radio_button_unittest.cc b/ui/views/controls/button/radio_button_unittest.cc index 77f4f55..78566b4 100644 --- a/ui/views/controls/button/radio_button_unittest.cc +++ b/ui/views/controls/button/radio_button_unittest.cc
@@ -28,7 +28,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); button_container_ = new View();
diff --git a/ui/views/controls/button/toggle_button_unittest.cc b/ui/views/controls/button/toggle_button_unittest.cc index 4baaf44..0dec528e8 100644 --- a/ui/views/controls/button/toggle_button_unittest.cc +++ b/ui/views/controls/button/toggle_button_unittest.cc
@@ -62,7 +62,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); button_ = new TestToggleButton(&counter_);
diff --git a/ui/views/controls/combobox/combobox.cc b/ui/views/controls/combobox/combobox.cc index 27f3b74..b7c3573 100644 --- a/ui/views/controls/combobox/combobox.cc +++ b/ui/views/controls/combobox/combobox.cc
@@ -24,6 +24,8 @@ #include "ui/views/animation/flood_fill_ink_drop_ripple.h" #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/background.h" +#include "ui/views/controls/button/button.h" +#include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/combobox/combobox_listener.h" #include "ui/views/controls/combobox/combobox_util.h" #include "ui/views/controls/focus_ring.h" @@ -58,7 +60,8 @@ public: explicit TransparentButton(ButtonListener* listener) : Button(listener) { SetFocusBehavior(FocusBehavior::NEVER); - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action( + ButtonController::NotifyAction::NOTIFY_ON_PRESS); SetInkDropMode(InkDropMode::ON); set_has_ink_drop_action_on_click(true);
diff --git a/ui/views/controls/combobox/combobox_unittest.cc b/ui/views/controls/combobox/combobox_unittest.cc index 3120641..1797ea12 100644 --- a/ui/views/controls/combobox/combobox_unittest.cc +++ b/ui/views/controls/combobox/combobox_unittest.cc
@@ -246,7 +246,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(combobox_); @@ -372,7 +372,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(100, 100, 100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(combobox_);
diff --git a/ui/views/controls/editable_combobox/editable_combobox.cc b/ui/views/controls/editable_combobox/editable_combobox.cc index 3b1ad64..86ce8229 100644 --- a/ui/views/controls/editable_combobox/editable_combobox.cc +++ b/ui/views/controls/editable_combobox/editable_combobox.cc
@@ -43,6 +43,7 @@ #include "ui/views/animation/ink_drop_impl.h" #include "ui/views/animation/ink_drop_ripple.h" #include "ui/views/controls/button/button.h" +#include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/combobox/combobox_util.h" #include "ui/views/controls/editable_combobox/editable_combobox_listener.h" #include "ui/views/controls/menu/menu_config.h" @@ -67,7 +68,7 @@ : Button(listener), color_(color) { // Similar to Combobox's TransparentButton. SetFocusBehavior(FocusBehavior::NEVER); - set_notify_action(Button::NOTIFY_ON_PRESS); + button_controller()->set_notify_action(ButtonController::NOTIFY_ON_PRESS); SetInkDropMode(InkDropMode::ON); set_has_ink_drop_action_on_click(true);
diff --git a/ui/views/controls/editable_combobox/editable_combobox_unittest.cc b/ui/views/controls/editable_combobox/editable_combobox_unittest.cc index 54eab4cb..5699b42 100644 --- a/ui/views/controls/editable_combobox/editable_combobox_unittest.cc +++ b/ui/views/controls/editable_combobox/editable_combobox_unittest.cc
@@ -185,7 +185,7 @@ parent_of_combobox_->SetBoundsRect(gfx::Rect(0, 0, 500, 40)); combobox_->SetBoundsRect(gfx::Rect(0, 0, 500, 40)); - widget_->Init(params); + widget_->Init(std::move(params)); View* container = new View(); widget_->SetContentsView(container); container->AddChildView(parent_of_combobox_);
diff --git a/ui/views/controls/image_view_unittest.cc b/ui/views/controls/image_view_unittest.cc index f5b69ab8..640ff5b7 100644 --- a/ui/views/controls/image_view_unittest.cc +++ b/ui/views/controls/image_view_unittest.cc
@@ -48,7 +48,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); View* container = new View(); // Make sure children can take up exactly as much space as they require. BoxLayout::Orientation orientation =
diff --git a/ui/views/controls/label_unittest.cc b/ui/views/controls/label_unittest.cc index 847e8c7..80a0f2f 100644 --- a/ui/views/controls/label_unittest.cc +++ b/ui/views/controls/label_unittest.cc
@@ -126,7 +126,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_.Init(params); + widget_.Init(std::move(params)); View* container = new View(); widget_.SetContentsView(container);
diff --git a/ui/views/controls/menu/menu_controller_unittest.cc b/ui/views/controls/menu/menu_controller_unittest.cc index ce0b8a3..367c18fc 100644 --- a/ui/views/controls/menu/menu_controller_unittest.cc +++ b/ui/views/controls/menu/menu_controller_unittest.cc
@@ -746,7 +746,7 @@ owner_ = std::make_unique<GestureTestWidget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - owner_->Init(params); + owner_->Init(std::move(params)); event_generator_ = std::make_unique<ui::test::EventGenerator>(GetRootWindow(owner())); owner_->Show();
diff --git a/ui/views/controls/menu/menu_host.cc b/ui/views/controls/menu/menu_host.cc index b655bec..02450d08 100644 --- a/ui/views/controls/menu/menu_host.cc +++ b/ui/views/controls/menu/menu_host.cc
@@ -136,7 +136,7 @@ // revert this change once http://crbug.com/125248 is fixed. params.force_software_compositing = true; #endif - Init(params); + Init(std::move(params)); #if !defined(OS_MACOSX) pre_dispatch_handler_ =
diff --git a/ui/views/controls/menu/menu_item_view_unittest.cc b/ui/views/controls/menu/menu_item_view_unittest.cc index e745aec..16d2fd7 100644 --- a/ui/views/controls/menu/menu_item_view_unittest.cc +++ b/ui/views/controls/menu/menu_item_view_unittest.cc
@@ -297,7 +297,7 @@ widget_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); menu_runner_ = std::make_unique<MenuRunner>(menu_item_view_, 0);
diff --git a/ui/views/controls/menu/menu_runner_unittest.cc b/ui/views/controls/menu/menu_runner_unittest.cc index 549983a..a4a085e 100644 --- a/ui/views/controls/menu/menu_runner_unittest.cc +++ b/ui/views/controls/menu/menu_runner_unittest.cc
@@ -78,7 +78,7 @@ owner_ = std::make_unique<Widget>(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - owner_->Init(params); + owner_->Init(std::move(params)); owner_->Show(); } @@ -384,7 +384,7 @@ MenuRunnerTest::SetUp(); widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); widget_->SetSize(gfx::Size(300, 300));
diff --git a/ui/views/controls/message_box_view.cc b/ui/views/controls/message_box_view.cc index f2f9631..117e6b73 100644 --- a/ui/views/controls/message_box_view.cc +++ b/ui/views/controls/message_box_view.cc
@@ -84,7 +84,7 @@ MessageBoxView::MessageBoxView(const InitParams& params) : inter_row_vertical_spacing_(params.inter_row_vertical_spacing), message_width_(params.message_width) { - Init(params); + Init(std::move(params)); } MessageBoxView::~MessageBoxView() = default;
diff --git a/ui/views/controls/native/native_view_host_aura_unittest.cc b/ui/views/controls/native/native_view_host_aura_unittest.cc index 11da73e..1ff2d2e 100644 --- a/ui/views/controls/native/native_view_host_aura_unittest.cc +++ b/ui/views/controls/native/native_view_host_aura_unittest.cc
@@ -498,7 +498,7 @@ params.bounds = gfx::Rect(10, 10, 100, 100); params.parent = window.get(); std::unique_ptr<Widget> child_widget = std::make_unique<Widget>(); - child_widget->Init(params); + child_widget->Init(std::move(params)); native_view_host->Attach(window.get());
diff --git a/ui/views/controls/native/native_view_host_test_base.cc b/ui/views/controls/native/native_view_host_test_base.cc index 66445990..a320fffe 100644 --- a/ui/views/controls/native/native_view_host_test_base.cc +++ b/ui/views/controls/native/native_view_host_test_base.cc
@@ -38,7 +38,7 @@ Widget::InitParams toplevel_params = CreateParams(Widget::InitParams::TYPE_WINDOW); toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel_->Init(toplevel_params); + toplevel_->Init(std::move(toplevel_params)); } void NativeViewHostTestBase::CreateTestingHost() { @@ -54,7 +54,7 @@ Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = native_parent_view; - child->Init(child_params); + child->Init(std::move(child_params)); child->SetContentsView(contents_view); // Owned by |parent_view|.
diff --git a/ui/views/controls/resize_area_unittest.cc b/ui/views/controls/resize_area_unittest.cc index 0e14fca5..72fe15e 100644 --- a/ui/views/controls/resize_area_unittest.cc +++ b/ui/views/controls/resize_area_unittest.cc
@@ -131,7 +131,7 @@ init_params.bounds = gfx::Rect(size); widget_ = new views::Widget(); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(resize_area_); widget_->Show();
diff --git a/ui/views/controls/scrollbar/scrollbar_unittest.cc b/ui/views/controls/scrollbar/scrollbar_unittest.cc index ddc3c35..32933a4 100644 --- a/ui/views/controls/scrollbar/scrollbar_unittest.cc +++ b/ui/views/controls/scrollbar/scrollbar_unittest.cc
@@ -58,7 +58,7 @@ widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); View* container = new View(); widget_->SetContentsView(container);
diff --git a/ui/views/controls/slider_unittest.cc b/ui/views/controls/slider_unittest.cc index b2844dc..e8036f2 100644 --- a/ui/views/controls/slider_unittest.cc +++ b/ui/views/controls/slider_unittest.cc
@@ -208,7 +208,7 @@ init_params.bounds = gfx::Rect(size); widget_ = new views::Widget(); - widget_->Init(init_params); + widget_->Init(std::move(init_params)); widget_->SetContentsView(slider_); widget_->Show();
diff --git a/ui/views/controls/styled_label_unittest.cc b/ui/views/controls/styled_label_unittest.cc index 8d9c27b4..b1d0daabe 100644 --- a/ui/views/controls/styled_label_unittest.cc +++ b/ui/views/controls/styled_label_unittest.cc
@@ -376,7 +376,7 @@ Widget* widget = new Widget(); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); View* container = new View(); widget->SetContentsView(container); container->AddChildView(styled());
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc b/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc index b92e074..f6aa8045 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc +++ b/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc
@@ -57,7 +57,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetContentsView(tabbed_pane_.get()); } @@ -239,7 +239,7 @@ // Testing accessibility information requires the View to have a Widget. Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - widget->Init(params); + widget->Init(std::move(params)); widget->GetContentsView()->AddChildView(tabbed_pane_.get()); widget->Show();
diff --git a/ui/views/controls/table/table_view_unittest.cc b/ui/views/controls/table/table_view_unittest.cc index 5a68a4dc..474271f0 100644 --- a/ui/views/controls/table/table_view_unittest.cc +++ b/ui/views/controls/table/table_view_unittest.cc
@@ -283,7 +283,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); params.delegate = GetWidgetDelegate(widget_.get()); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->GetContentsView()->AddChildView(std::move(scroll_view)); widget_->Show(); }
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index 4d0229c..0361a3d 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -457,7 +457,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(100, 100, 100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); input_method_->SetDelegate( test::WidgetTest::GetInputMethodDelegateForWidget(widget_)); View* container = new View(); @@ -3388,7 +3388,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(100, 100, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(container); container->AddChildView(new_textfield);
diff --git a/ui/views/corewm/desktop_capture_controller_unittest.cc b/ui/views/corewm/desktop_capture_controller_unittest.cc index 3891cf1..4d4f40a 100644 --- a/ui/views/corewm/desktop_capture_controller_unittest.cc +++ b/ui/views/corewm/desktop_capture_controller_unittest.cc
@@ -61,7 +61,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.native_widget = new DesktopNativeWidgetAura(widget); params.bounds = gfx::Rect(0, 0, 200, 100); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; } @@ -107,7 +107,7 @@ params.bounds = gfx::Rect(50, 50, 650, 650); params.native_widget = test::CreatePlatformNativeWidgetImpl( params, widget1.get(), test::kStubCapture, nullptr); - widget1->Init(params); + widget1->Init(std::move(params)); internal::RootView* root1 = static_cast<internal::RootView*>(widget1->GetRootView()); @@ -129,7 +129,7 @@ params.bounds = gfx::Rect(50, 50, 650, 650); params.native_widget = test::CreatePlatformNativeWidgetImpl( params, widget2.get(), test::kStubCapture, nullptr); - widget2->Init(params); + widget2->Init(std::move(params)); internal::RootView* root2 = static_cast<internal::RootView*>(widget2->GetRootView());
diff --git a/ui/views/corewm/tooltip_aura.cc b/ui/views/corewm/tooltip_aura.cc index 6d6e85b..8b90af1 100644 --- a/ui/views/corewm/tooltip_aura.cc +++ b/ui/views/corewm/tooltip_aura.cc
@@ -65,7 +65,7 @@ if (CanUseTranslucentTooltipWidget()) params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/corewm/tooltip_controller_unittest.cc b/ui/views/corewm/tooltip_controller_unittest.cc index 328f002..f221ff6f 100644 --- a/ui/views/corewm/tooltip_controller_unittest.cc +++ b/ui/views/corewm/tooltip_controller_unittest.cc
@@ -64,7 +64,7 @@ params.parent = root; #endif params.bounds = gfx::Rect(0, 0, 200, 100); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; }
diff --git a/ui/views/examples/examples_window.cc b/ui/views/examples/examples_window.cc index 2de2b72..9c725202c 100644 --- a/ui/views/examples/examples_window.cc +++ b/ui/views/examples/examples_window.cc
@@ -247,7 +247,7 @@ params.delegate = new ExamplesWindowContents(std::move(on_close), std::move(examples)); params.context = window_context; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); } }
diff --git a/ui/views/examples/widget_example.cc b/ui/views/examples/widget_example.cc index 0a36f58..de45873 100644 --- a/ui/views/examples/widget_example.cc +++ b/ui/views/examples/widget_example.cc
@@ -102,7 +102,7 @@ gfx::Size(300, 200)); Widget* widget = new Widget(); - widget->Init(params); + widget->Init(std::move(params)); // If the Widget has no contents by default, add a view with a 'Close' button. if (!widget->GetContentsView()) {
diff --git a/ui/views/focus/focus_manager_unittest.cc b/ui/views/focus/focus_manager_unittest.cc index 0af0ee35..192a529 100644 --- a/ui/views/focus/focus_manager_unittest.cc +++ b/ui/views/focus/focus_manager_unittest.cc
@@ -144,11 +144,11 @@ params.parent = GetWidget()->GetNativeView(); std::unique_ptr<Widget> widget1(new Widget); - widget1->Init(params); + widget1->Init(std::move(params)); widget1->Show(); std::unique_ptr<Widget> widget2(new Widget); - widget2->Init(params); + widget2->Init(std::move(params)); widget2->Show(); widget_listener.ClearFocusChanges(); @@ -468,7 +468,7 @@ Widget::InitParams params; params.delegate = this; params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); tracked_focus_manager_ = static_cast<FocusManagerDtorTracked*>(GetFocusManager()); @@ -877,7 +877,7 @@ Widget child_widget; delegate = std::make_unique<AdvanceFocusWidgetDelegate>(&child_widget); params.delegate = delegate.get(); - child_widget.Init(params); + child_widget.Init(std::move(params)); View* view1 = new View; view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); view1->SetBounds(0, 0, 20, 20); @@ -1098,7 +1098,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 1024, 768); - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); widget.Activate();
diff --git a/ui/views/focus/focus_traversal_unittest.cc b/ui/views/focus/focus_traversal_unittest.cc index 3d2ef8e..0664155 100644 --- a/ui/views/focus/focus_traversal_unittest.cc +++ b/ui/views/focus/focus_traversal_unittest.cc
@@ -156,7 +156,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); params.parent = details.parent->GetWidget()->GetNativeView(); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_->Init(params); + widget_->Init(std::move(params)); widget_->SetFocusTraversableParentView(this); widget_->SetContentsView(child_); }
diff --git a/ui/views/layout/flex_layout.cc b/ui/views/layout/flex_layout.cc index 91ad5ce..d0c04e3 100644 --- a/ui/views/layout/flex_layout.cc +++ b/ui/views/layout/flex_layout.cc
@@ -50,6 +50,7 @@ NormalizedSize preferred_size; NormalizedSize current_size; NormalizedInsets margins; + bool using_default_margins = true; NormalizedInsets internal_padding; NormalizedRect actual_bounds; FlexSpecification flex; @@ -63,10 +64,16 @@ template <typename T> T GetViewProperty(const View* view, const ui::PropertyHandler& defaults, - const ui::ClassProperty<T*>* property) { + const ui::ClassProperty<T*>* property, + bool* is_default = nullptr) { T* found_value = view->GetProperty(property); - if (found_value) + if (found_value) { + if (is_default) + *is_default = false; return *found_value; + } + if (is_default) + *is_default = true; found_value = defaults.GetProperty(property); if (found_value) return *found_value; @@ -257,6 +264,15 @@ return *this; } +FlexLayout& FlexLayout::SetIncludeHostInsetsInLayout( + bool include_host_insets_in_layout) { + if (include_host_insets_in_layout != include_host_insets_in_layout_) { + include_host_insets_in_layout_ = include_host_insets_in_layout; + InvalidateLayout(); + } + return *this; +} + FlexLayout& FlexLayout::SetCollapseMargins(bool collapse_margins) { if (collapse_margins != collapse_margins_) { collapse_margins_ = collapse_margins; @@ -293,6 +309,15 @@ return *this; } +FlexLayout& FlexLayout::SetIgnoreDefaultMainAxisMargins( + bool ignore_default_main_axis_margins) { + if (ignore_default_main_axis_margins_ != ignore_default_main_axis_margins) { + ignore_default_main_axis_margins_ = ignore_default_main_axis_margins; + InvalidateLayout(); + } + return *this; +} + FlexLayout& FlexLayout::SetMinimumCrossAxisSize(int size) { if (minimum_cross_axis_size_ != size) { minimum_cross_axis_size_ = size; @@ -305,8 +330,15 @@ const SizeBounds& size_bounds) const { FlexLayoutData data; - data.host_insets = Normalize(orientation(), host_view()->GetInsets()); - data.interior_margin = Normalize(orientation(), interior_margin()); + if (include_host_insets_in_layout()) { + // Combining the interior margin and host insets means we only have to set + // the margin value; we'll leave the insets at zero. + data.interior_margin = + Normalize(orientation(), interior_margin() + host_view()->GetInsets()); + } else { + data.host_insets = Normalize(orientation(), host_view()->GetInsets()); + data.interior_margin = Normalize(orientation(), interior_margin()); + } NormalizedSizeBounds bounds = Normalize(orientation(), size_bounds); bounds.Inset(data.host_insets); if (bounds.cross() && *bounds.cross() < minimum_cross_axis_size()) @@ -366,7 +398,8 @@ flex_child.margins = Normalize(orientation(), - GetViewProperty(child, layout_defaults_, views::kMarginsKey)); + GetViewProperty(child, layout_defaults_, views::kMarginsKey, + &flex_child.using_default_margins)); flex_child.internal_padding = Normalize( orientation(), GetViewProperty(child, layout_defaults_, views::kInternalPaddingKey)); @@ -443,6 +476,20 @@ } } +Inset1D FlexLayout::GetCrossAxisMargins(const FlexLayoutData& layout, + size_t child_index) const { + const FlexChildData& child_data = layout.child_data[child_index]; + const int leading_margin = + CalculateMargin(layout.interior_margin.cross_leading(), + child_data.margins.cross_leading(), + child_data.internal_padding.cross_leading()); + const int trailing_margin = + CalculateMargin(layout.interior_margin.cross_trailing(), + child_data.margins.cross_trailing(), + child_data.internal_padding.cross_trailing()); + return Inset1D(leading_margin, trailing_margin); +} + int FlexLayout::CalculateMargin(int margin1, int margin2, int internal_padding) const { @@ -457,37 +504,39 @@ const NormalizedSizeBounds& bounds) const { if (!bounds.cross()) return base::nullopt; - - const FlexChildData& child_layout = layout.child_data[child_index]; - const int leading_margin = - CalculateMargin(layout.interior_margin.cross_leading(), - child_layout.margins.cross_leading(), - child_layout.internal_padding.cross_leading()); - const int trailing_margin = - CalculateMargin(layout.interior_margin.cross_trailing(), - child_layout.margins.cross_trailing(), - child_layout.internal_padding.cross_trailing()); - return std::max(0, *bounds.cross() - (leading_margin + trailing_margin)); + const Inset1D cross_margins = GetCrossAxisMargins(layout, child_index); + return std::max(0, *bounds.cross() - cross_margins.size()); } int FlexLayout::CalculateChildSpacing( const FlexLayoutData& layout, base::Optional<size_t> child1_index, base::Optional<size_t> child2_index) const { + const FlexChildData* const child1 = + child1_index ? &layout.child_data[*child1_index] : nullptr; + const FlexChildData* const child2 = + child2_index ? &layout.child_data[*child2_index] : nullptr; + + const int child1_trailing = + child1 && (child2 || !ignore_default_main_axis_margins() || + !child1->using_default_margins) + ? child1->margins.main_trailing() + : 0; + const int child2_leading = + child2 && (child1 || !ignore_default_main_axis_margins() || + !child2->using_default_margins) + ? child2->margins.main_leading() + : 0; + const int left_margin = - child1_index ? layout.child_data[*child1_index].margins.main_trailing() - : layout.interior_margin.main_leading(); + child1 ? child1_trailing : layout.interior_margin.main_leading(); const int right_margin = - child2_index ? layout.child_data[*child2_index].margins.main_leading() - : layout.interior_margin.main_trailing(); + child2 ? child2_leading : layout.interior_margin.main_trailing(); + const int left_padding = - child1_index - ? layout.child_data[*child1_index].internal_padding.main_trailing() - : 0; + child1 ? child1->internal_padding.main_trailing() : 0; const int right_padding = - child2_index - ? layout.child_data[*child2_index].internal_padding.main_leading() - : 0; + child2 ? child2->internal_padding.main_leading() : 0; return CalculateMargin(left_margin, right_margin, left_padding + right_padding); @@ -521,20 +570,12 @@ continue; // Update the cross-axis margins and if necessary, the size. - Inset1D& cross_spacing = cross_spacings[i]; - cross_spacing.set_leading( - CalculateMargin(data->interior_margin.cross_leading(), - flex_child.margins.cross_leading(), - flex_child.internal_padding.cross_leading())); - cross_spacing.set_trailing( - CalculateMargin(data->interior_margin.cross_trailing(), - flex_child.margins.cross_trailing(), - flex_child.internal_padding.cross_trailing())); + cross_spacings[i] = GetCrossAxisMargins(*data, i); if (!force_cross_size) { const int cross_size = std::min(flex_child.current_size.cross(), flex_child.preferred_size.cross()); - data->total_size.SetToMax(0, cross_spacing.size() + cross_size); + data->total_size.SetToMax(0, cross_spacings[i].size() + cross_size); } // Calculate main-axis size and upper-left main axis coordinate.
diff --git a/ui/views/layout/flex_layout.h b/ui/views/layout/flex_layout.h index 5ca0ab23..63488a6a 100644 --- a/ui/views/layout/flex_layout.h +++ b/ui/views/layout/flex_layout.h
@@ -81,11 +81,14 @@ // .SetCrossAxisAlignment() // .SetDefaultFlex(...); FlexLayout& SetOrientation(LayoutOrientation orientation); - FlexLayout& SetCollapseMargins(bool collapse_margins); FlexLayout& SetMainAxisAlignment(LayoutAlignment main_axis_alignment); FlexLayout& SetCrossAxisAlignment(LayoutAlignment cross_axis_alignment); FlexLayout& SetInteriorMargin(const gfx::Insets& interior_margin); FlexLayout& SetMinimumCrossAxisSize(int size); + FlexLayout& SetCollapseMargins(bool collapse_margins); + FlexLayout& SetIncludeHostInsetsInLayout(bool include_host_insets_in_layout); + FlexLayout& SetIgnoreDefaultMainAxisMargins( + bool ignore_default_main_axis_margins); LayoutOrientation orientation() const { return orientation_; } bool collapse_margins() const { return collapse_margins_; } @@ -93,6 +96,12 @@ LayoutAlignment cross_axis_alignment() const { return cross_axis_alignment_; } const gfx::Insets& interior_margin() const { return interior_margin_; } int minimum_cross_axis_size() const { return minimum_cross_axis_size_; } + bool include_host_insets_in_layout() const { + return include_host_insets_in_layout_; + } + bool ignore_default_main_axis_margins() const { + return ignore_default_main_axis_margins_; + } // Moves and uses |value| as the default value for layout property |key|. template <class T, class U> @@ -135,6 +144,11 @@ // See FlexSpecification::order(). using FlexOrderToViewIndexMap = std::map<int, std::vector<size_t>>; + // Returns the combined margins across the cross axis of the host view, for a + // particular child view. + Inset1D GetCrossAxisMargins(const FlexLayoutData& layout, + size_t child_index) const; + // Calculates a margin between two child views based on each's margin and any // internal padding present in one or both elements. Uses properties of the // layout, like whether adjacent margins should be collapsed. @@ -222,6 +236,33 @@ // The minimum cross axis size for the layout. int minimum_cross_axis_size_ = 0; + // Whether to include host insets in the layout. Use when e.g. the host has an + // empty border and you want to treat that empty space as part of the interior + // margin of the host view. + // + // Most useful in conjunction with |collapse_margins| so child margins can + // overlap with the host's insets. + // + // In the future, we might consider putting this as metadata on the host's + // border - e.g. an EmptyBorder would be included in host insets but a thick + // frame would not be. + bool include_host_insets_in_layout_ = false; + + // Whether host |interior_margin| overrides default child margins at the + // leading and trailing edge of the host view. + // + // Example: + // layout->SetIgnoreDefaultMainAxisMargins(true) + // .SetCollapseMargins(true) + // .SetDefault(kMarginsKey, {5, 10}) + // .SetInteriorMargin({5, 5}); + // + // This produces a margin of 5 DIP on all edges of the host view, with 10 DIP + // between child views. If SetIgnoreDefaultMainAxisMargins(true) was not + // called, the default child margin of 10 would also apply on the leading and + // trailing edge of the host view. + bool ignore_default_main_axis_margins_ = false; + // Default properties for any views that don't have them explicitly set for // this layout. PropertyHandler layout_defaults_{this};
diff --git a/ui/views/layout/flex_layout_unittest.cc b/ui/views/layout/flex_layout_unittest.cc index 48ba06c..6a19f86 100644 --- a/ui/views/layout/flex_layout_unittest.cc +++ b/ui/views/layout/flex_layout_unittest.cc
@@ -821,6 +821,129 @@ EXPECT_EQ(Rect(6, expected_y, 12, 10), child->bounds()); } +// Include Host Insets Tests --------------------------------------------------- + +TEST_F(FlexLayoutTest, SetIncludeHostInsetsInLayout_NoChange) { + host_->SetBorder(views::CreateEmptyBorder(2, 2, 2, 2)); + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetCollapseMargins(false); + layout_->SetInteriorMargin(kLayoutInsets); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kEnd); + layout_->SetDefault(views::kMarginsKey, gfx::Insets(4)); + constexpr Size kChildSize(10, 10); + AddChild(kChildSize); + View* const child2 = AddChild(kChildSize); + AddChild(kChildSize); + child2->SetProperty(views::kMarginsKey, gfx::Insets(10)); + + const Size expected_preferred_size = host_->GetPreferredSize(); + host_->SetSize(expected_preferred_size); + const std::vector<Rect> expected_bounds = GetChildBounds(); + + layout_->SetIncludeHostInsetsInLayout(true); + const Size preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(expected_preferred_size, preferred_size); + host_->Layout(); + EXPECT_EQ(expected_bounds, GetChildBounds()); +} + +TEST_F(FlexLayoutTest, SetIncludeHostInsetsInLayout_CollapseIntoInsets) { + host_->SetBorder(views::CreateEmptyBorder(2, 2, 2, 2)); + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetCollapseMargins(true); + layout_->SetInteriorMargin(kLayoutInsets); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kEnd); + layout_->SetDefault(views::kMarginsKey, gfx::Insets(4)); + constexpr Size kChildSize(10, 10); + AddChild(kChildSize); + View* const child2 = AddChild(kChildSize); + AddChild(kChildSize); + child2->SetProperty(views::kMarginsKey, gfx::Insets(15)); + + layout_->SetIncludeHostInsetsInLayout(true); + const Size preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(40, 76), preferred_size); + host_->SetSize(preferred_size); + const std::vector<Rect> expected{Rect(19, 7, 10, 10), Rect(15, 32, 10, 10), + Rect(19, 57, 10, 10)}; + EXPECT_EQ(expected, GetChildBounds()); +} + +TEST_F(FlexLayoutTest, SetIncludeHostInsetsInLayout_OverlapInsets) { + host_->SetBorder(views::CreateEmptyBorder(4, 5, 5, 5)); + layout_->SetOrientation(LayoutOrientation::kHorizontal); + layout_->SetCollapseMargins(true); + layout_->SetInteriorMargin(kLayoutInsets); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + View* const child = AddChild(Size(10, 10)); + child->SetProperty(views::kInternalPaddingKey, Insets(10, 10, 10, 10)); + + layout_->SetIncludeHostInsetsInLayout(true); + const Size preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(15, 12), preferred_size); + host_->SetSize(preferred_size); + EXPECT_EQ(Rect(1, 0, 10, 10), child->bounds()); +} + +// Default Main Axis Margins Tests --------------------------------------------- + +TEST_F(FlexLayoutTest, SetIgnoreDefaultMainAxisMargins_IgnoresDefaultMargins) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetCollapseMargins(false); + layout_->SetInteriorMargin(kLayoutInsets); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kEnd); + layout_->SetDefault(views::kMarginsKey, gfx::Insets(4)); + constexpr Size kChildSize(10, 10); + AddChild(kChildSize); + AddChild(kChildSize); + AddChild(kChildSize); + + Size preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(33, 66), preferred_size); + + layout_->SetIgnoreDefaultMainAxisMargins(true); + preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(33, 58), preferred_size); + + host_->SetSize(preferred_size); + const std::vector<Rect> expected{Rect(10, 5, 10, 10), Rect(10, 23, 10, 10), + Rect(10, 41, 10, 10)}; + EXPECT_EQ(expected, GetChildBounds()); +} + +TEST_F(FlexLayoutTest, + SetIgnoreDefaultMainAxisMargins_IncludesExplicitMargins) { + layout_->SetOrientation(LayoutOrientation::kVertical); + layout_->SetCollapseMargins(true); + layout_->SetInteriorMargin(kLayoutInsets); + layout_->SetMainAxisAlignment(LayoutAlignment::kStart); + layout_->SetCrossAxisAlignment(LayoutAlignment::kStart); + layout_->SetDefault(views::kMarginsKey, gfx::Insets(4)); + constexpr Size kChildSize(10, 10); + View* const child1 = AddChild(kChildSize); + AddChild(kChildSize); + View* const child3 = AddChild(kChildSize); + + child1->SetProperty(views::kMarginsKey, gfx::Insets(11)); + child3->SetProperty(views::kMarginsKey, gfx::Insets(12)); + + Size preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(34, 76), preferred_size); + + layout_->SetIgnoreDefaultMainAxisMargins(true); + preferred_size = host_->GetPreferredSize(); + EXPECT_EQ(Size(34, 76), preferred_size); + + host_->SetSize(preferred_size); + const std::vector<Rect> expected{Rect(11, 11, 10, 10), Rect(6, 32, 10, 10), + Rect(12, 54, 10, 10)}; + EXPECT_EQ(expected, GetChildBounds()); +} + // Alignment Tests ------------------------------------------------------------- TEST_F(FlexLayoutTest, Layout_CrossStart) {
diff --git a/ui/views/test/focus_manager_test.cc b/ui/views/test/focus_manager_test.cc index 7b68bfc..f233464a 100644 --- a/ui/views/test/focus_manager_test.cc +++ b/ui/views/test/focus_manager_test.cc
@@ -32,7 +32,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.delegate = this; params.bounds = gfx::Rect(0, 0, 1024, 768); - widget->Init(params); + widget->Init(std::move(params)); InitContentView(); widget->Show();
diff --git a/ui/views/test/widget_test.cc b/ui/views/test/widget_test.cc index 71f0919..ba0b022 100644 --- a/ui/views/test/widget_test.cc +++ b/ui/views/test/widget_test.cc
@@ -24,7 +24,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.native_widget = CreatePlatformNativeWidgetImpl(params, widget, kStubCapture, nullptr); - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -34,7 +34,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.native_widget = CreatePlatformNativeWidgetImpl(params, widget, kStubCapture, nullptr); - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -45,7 +45,7 @@ Widget* child = new Widget; params.native_widget = CreatePlatformNativeWidgetImpl(params, child, kStubCapture, nullptr); - child->Init(params); + child->Init(std::move(params)); child->SetContentsView(new View); return child; } @@ -53,7 +53,7 @@ Widget* WidgetTest::CreateTopLevelNativeWidget() { Widget* toplevel = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel->Init(params); + toplevel->Init(std::move(params)); return toplevel; } @@ -61,7 +61,7 @@ Widget* child = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_CONTROL); params.parent = parent->GetNativeView(); - child->Init(params); + child->Init(std::move(params)); child->SetContentsView(new View); return child; } @@ -104,7 +104,7 @@ void TestDesktopWidgetDelegate::InitWidget(Widget::InitParams init_params) { init_params.delegate = this; init_params.bounds = initial_bounds_; - widget_->Init(init_params); + widget_->Init(std::move(init_params)); } void TestDesktopWidgetDelegate::WindowClosing() { @@ -142,7 +142,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.context = context; params.delegate = this; - GetWidget()->Init(params); + GetWidget()->Init(std::move(params)); GetWidget()->GetContentsView()->AddChildView(view_); }
diff --git a/ui/views/touchui/touch_selection_controller_impl.cc b/ui/views/touchui/touch_selection_controller_impl.cc index 41623615..77727f2 100644 --- a/ui/views/touchui/touch_selection_controller_impl.cc +++ b/ui/views/touchui/touch_selection_controller_impl.cc
@@ -84,7 +84,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = parent; params.delegate = widget_delegate; - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/touchui/touch_selection_controller_impl_unittest.cc b/ui/views/touchui/touch_selection_controller_impl_unittest.cc index 6b85640..98e16e4 100644 --- a/ui/views/touchui/touch_selection_controller_impl_unittest.cc +++ b/ui/views/touchui/touch_selection_controller_impl_unittest.cc
@@ -93,7 +93,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.bounds = gfx::Rect(0, 0, 200, 200); - textfield_widget_->Init(params); + textfield_widget_->Init(std::move(params)); View* container = new View(); textfield_widget_->SetContentsView(container); container->AddChildView(textfield_); @@ -110,7 +110,7 @@ widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); }
diff --git a/ui/views/view_targeter_unittest.cc b/ui/views/view_targeter_unittest.cc index a3fca5e3..eac9398b 100644 --- a/ui/views/view_targeter_unittest.cc +++ b/ui/views/view_targeter_unittest.cc
@@ -124,7 +124,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.Show(); View* content = new View; @@ -171,7 +171,7 @@ CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); + widget.Init(std::move(init_params)); // The coordinates used for SetBounds() are in the parent coordinate space. View* content = new View; @@ -253,7 +253,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); + widget.Init(std::move(init_params)); // The coordinates used for SetBounds() are in the parent coordinate space. View* content = new View; @@ -363,7 +363,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); + widget.Init(std::move(init_params)); // The coordinates used for SetBounds() are in the parent coordinate space. View* content = new View; @@ -445,7 +445,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); + widget.Init(std::move(init_params)); // The coordinates used for SetBounds() are in the parent coordinate space. View* content = new View; @@ -540,7 +540,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 650, 650); - widget.Init(params); + widget.Init(std::move(params)); internal::RootView* root_view = static_cast<internal::RootView*>(widget.GetRootView()); @@ -594,7 +594,7 @@ // The coordinates in this test are in the coordinate space of the root view. Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500));
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index 28637ad1..02fdd039 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -423,7 +423,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); internal::RootView* root = static_cast<internal::RootView*>(widget->GetRootView()); @@ -486,7 +486,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); root->AddChildView(v1); @@ -517,9 +517,9 @@ // the helper class goes out of scope. class ScopedTestPaintWidget { public: - explicit ScopedTestPaintWidget(const Widget::InitParams& params) - : widget_(new Widget) { - widget_->Init(params); + explicit ScopedTestPaintWidget(Widget::InitParams params) + : widget_(new Widget) { + widget_->Init(std::move(params)); widget_->GetRootView()->SetBounds(0, 0, 25, 26); } @@ -1331,7 +1331,7 @@ TEST_F(ViewTest, GetEventHandlerForRect) { Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); @@ -1643,7 +1643,7 @@ TEST_F(ViewTest, CanProcessEventsWithinSubtree) { Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); @@ -1799,7 +1799,7 @@ TEST_F(ViewTest, NotifyEnterExitOnChild) { Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); @@ -1937,7 +1937,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); Textfield* textfield = new Textfield(); @@ -1974,7 +1974,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); View* root_view = widget->GetRootView(); Textfield* normal = new Textfield(); @@ -2075,7 +2075,7 @@ // A Widget with a TestView in the view hierarchy. Used for accelerator tests. class TestViewWidget { public: - TestViewWidget(const Widget::InitParams& create_params, + TestViewWidget(Widget::InitParams create_params, ui::Accelerator* initial_accelerator, bool show_after_init = true) : view_(new TestView) { @@ -2088,10 +2088,10 @@ } // Create a window and add the view as its child. - Widget::InitParams params = create_params; + Widget::InitParams params = std::move(create_params); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 100, 100); - widget_.Init(params); + widget_.Init(std::move(params)); View* root = widget_.GetRootView(); root->AddChildView(view_); if (show_after_init) @@ -2151,7 +2151,7 @@ Widget::InitParams child_params = CreateParams(Widget::InitParams::TYPE_CONTROL); child_params.parent = widget->GetNativeView(); - child_widget->Init(child_params); + child_widget->Init(std::move(child_params)); child_widget->SetContentsView(child_view); FocusManager* child_focus_manager = child_widget->GetFocusManager(); @@ -2432,18 +2432,18 @@ Widget::InitParams toplevel1_params = CreateParams(Widget::InitParams::TYPE_POPUP); toplevel1_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel1->Init(toplevel1_params); + toplevel1->Init(std::move(toplevel1_params)); std::unique_ptr<Widget> toplevel2(new Widget); Widget::InitParams toplevel2_params = CreateParams(Widget::InitParams::TYPE_POPUP); toplevel2_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel2->Init(toplevel2_params); + toplevel2->Init(std::move(toplevel2_params)); Widget* child = new Widget; Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); child_params.parent = toplevel1->GetNativeView(); - child->Init(child_params); + child->Init(std::move(child_params)); ToplevelWidgetObserverView* observer_view = new ToplevelWidgetObserverView(); @@ -2501,7 +2501,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); View* root = widget->GetRootView(); @@ -2540,7 +2540,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); root->AddChildView(v1); @@ -2679,7 +2679,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = viewport_bounds; - widget->Init(params); + widget->Init(std::move(params)); widget->GetRootView()->SetBoundsRect(viewport_bounds); View* viewport = new View; @@ -2736,7 +2736,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = viewport_bounds; - widget->Init(params); + widget->Init(std::move(params)); widget->GetRootView()->SetBoundsRect(viewport_bounds); View* viewport = new View; @@ -2838,7 +2838,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = viewport_bounds; - widget->Init(params); + widget->Init(std::move(params)); widget->GetRootView()->SetBoundsRect(viewport_bounds); TestView* parent_view = new TestView; @@ -3054,7 +3054,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* child = new View; widget->GetRootView()->AddChildView(child); @@ -3086,7 +3086,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); TestView* v1 = new TestView; @@ -3370,7 +3370,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 650, 650); - widget.Init(params); + widget.Init(std::move(params)); View* root = widget.GetRootView(); @@ -3437,7 +3437,7 @@ // Test move between widgets. Widget second_widget; params.bounds = gfx::Rect(150, 150, 650, 650); - second_widget.Init(params); + second_widget.Init(std::move(params)); View* second_root = second_widget.GetRootView(); @@ -3707,7 +3707,7 @@ ActiveWidget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); View* view1 = widget.GetRootView()->AddChildView(std::make_unique<View>()); view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); @@ -3822,7 +3822,7 @@ widget_ = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(50, 50, 200, 200); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); widget_->GetRootView()->SetBounds(0, 0, 200, 200); } @@ -5013,7 +5013,7 @@ std::unique_ptr<Widget> widget(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->GetRootView()->AddChildView(test_view); EXPECT_TRUE(test_view->native_theme_); @@ -5052,7 +5052,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 350, 350); - widget->Init(params); + widget->Init(std::move(params)); View* root = widget->GetRootView(); TestView* v = root->AddChildView(std::make_unique<TestView>()); v->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); @@ -5139,7 +5139,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 350, 350); - widget.Init(params); + widget.Init(std::move(params)); AddViewWithChildLayer(widget.GetRootView()); ViewThatAddsViewInOnThemeChanged* v = widget.GetRootView()->AddChildView( @@ -5177,7 +5177,7 @@ NoLayerWhenHiddenView view; Widget* widget = new Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - widget->Init(params); + widget->Init(std::move(params)); widget->SetBounds(gfx::Rect(0, 0, 100, 100)); widget->GetContentsView()->AddChildView(&view); widget->Show();
diff --git a/ui/views/view_unittest_aura.cc b/ui/views/view_unittest_aura.cc index e99fbfcb..9d64d4f2 100644 --- a/ui/views/view_unittest_aura.cc +++ b/ui/views/view_unittest_aura.cc
@@ -27,7 +27,7 @@ params.parent = parent; params.bounds = bounds; Widget* widget = new Widget(); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc index 250a42b0..aae20bd0 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11.cc
@@ -1274,7 +1274,7 @@ params.bounds = gfx::Rect(location, image.size()); widget->set_focus_on_creation(false); widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE); - widget->Init(params); + widget->Init(std::move(params)); if (params.opacity == Widget::InitParams::TRANSLUCENT_WINDOW) widget->SetOpacity(kDragWidgetOpacity); widget->GetNativeWindow()->SetName("DragWindow");
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc index df07559..98cf507 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_aurax11_unittest.cc
@@ -386,7 +386,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); cursor_manager_ = std::make_unique<DesktopNativeCursorManager>(); @@ -853,7 +853,7 @@ params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.native_widget = new DesktopNativeWidgetAura(widget_.get()); params.bounds = gfx::Rect(100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); cursor_manager_ = std::make_unique<DesktopNativeCursorManager>(); @@ -896,7 +896,7 @@ target_params.native_widget = new DesktopNativeWidgetAura(target_widget.get()); target_params.bounds = gfx::Rect(100, 100); - target_widget->Init(target_params); + target_widget->Init(std::move(target_params)); target_widget->Show(); std::unique_ptr<TestDragDropDelegate> delegate(new TestDragDropDelegate);
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_unittest.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_unittest.cc index 336258b..7ddcc7e 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_unittest.cc
@@ -196,7 +196,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(100, 100); - widget_->Init(params); + widget_->Init(std::move(params)); widget_->Show(); // Creates FakeDragDropDelegate and set it for |window|.
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc index e7d20b8..4f4386a 100644 --- a/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc +++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc
@@ -114,7 +114,7 @@ // native widget which breaks this code path. init_params.native_widget = new DesktopNativeWidgetAura(top_level_handler->top_level_widget_); - top_level_handler->top_level_widget_->Init(init_params); + top_level_handler->top_level_widget_->Init(std::move(init_params)); top_level_handler->top_level_widget_->SetFullscreen(full_screen); top_level_handler->top_level_widget_->Show(); @@ -431,12 +431,14 @@ //////////////////////////////////////////////////////////////////////////////// // DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation: -void DesktopNativeWidgetAura::InitNativeWidget( - const Widget::InitParams& params) { +void DesktopNativeWidgetAura::InitNativeWidget(Widget::InitParams params) { ownership_ = params.ownership; widget_type_ = params.type; name_ = params.name; + content_window_->AcquireAllPropertiesFrom( + std::move(params.init_properties_container)); + NativeWidgetAura::RegisterNativeWidgetForWindow(this, content_window_); content_window_->SetType(GetAuraWindowTypeForWidgetType(params.type)); content_window_->Init(params.layer_type); @@ -451,7 +453,7 @@ } host_.reset(desktop_window_tree_host_->AsWindowTreeHost()); } - desktop_window_tree_host_->Init(params); + desktop_window_tree_host_->Init(std::move(params)); host_->window()->AddChild(content_window_); host_->window()->SetProperty(kDesktopNativeWidgetAuraKey, this);
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura.h b/ui/views/widget/desktop_aura/desktop_native_widget_aura.h index 8b038de..9e27c8c 100644 --- a/ui/views/widget/desktop_aura/desktop_native_widget_aura.h +++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura.h
@@ -104,7 +104,7 @@ protected: // Overridden from internal::NativeWidgetPrivate: - void InitNativeWidget(const Widget::InitParams& params) override; + void InitNativeWidget(Widget::InitParams params) override; void OnWidgetInitDone() override; NonClientFrameView* CreateNonClientFrameView() override; bool ShouldUseNativeFrame() const override;
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc index 9cfd92c..e3bfa42 100644 --- a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
@@ -55,7 +55,7 @@ params.bounds = gfx::Rect(0, 0, 200, 200); params.parent = window.get(); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); } // Verifies that the Aura windows making up a widget instance have the correct @@ -74,7 +74,7 @@ #endif init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); gfx::Rect bounds(0, 0, 100, 100); widget.SetBounds(bounds); @@ -102,7 +102,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); EXPECT_FALSE(widget.GetNativeView()->IsVisible()); } @@ -112,7 +112,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); EXPECT_FALSE(widget.CanActivate()); EXPECT_EQ(nullptr, aura::client::GetFocusClient(widget.GetNativeWindow()) @@ -127,7 +127,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); ShowWindow(widget.GetNativeView()->GetHost()->GetAcceleratedWidget(), SW_SHOWNORMAL); EXPECT_FALSE(widget.IsVisible()); @@ -139,7 +139,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); // Make sure that changing frame type doesn't crash when there's no non-client // view. @@ -172,13 +172,13 @@ Widget::InitParams init_params_a = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params_a.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_a.Init(init_params_a); + widget_a.Init(std::move(init_params_a)); Widget widget_b; Widget::InitParams init_params_b = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params_b.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget_b.Init(init_params_b); + widget_b.Init(std::move(init_params_b)); aura::client::CursorClient* cursor_client_a = aura::client::GetCursorClient( widget_a.GetNativeView()->GetHost()->window()); @@ -264,7 +264,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); // Owned by |widget|. aura::Window* window = new aura::Window(&delegate); @@ -285,7 +285,7 @@ params.parent = parent; params.native_widget = CreatePlatformNativeWidgetImpl(params, widget.get(), kStubCapture, nullptr); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); return widget; } @@ -306,7 +306,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent.Init(init_params); + parent.Init(std::move(init_params)); parent.Show(); aura::Window* parent_window = parent.GetNativeWindow(); @@ -353,7 +353,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); // Post a task that terminates the nested loop and destroyes the widget. This @@ -392,7 +392,7 @@ init_params.layer_type = ui::LAYER_NOT_DRAWN; init_params.accept_events = fullscreen; - widget_.Init(init_params); + widget_.Init(std::move(init_params)); owned_window_ = new aura::Window(&child_window_delegate_); owned_window_->SetType(aura::client::WINDOW_TYPE_NORMAL); @@ -595,7 +595,7 @@ Widget::InitParams params = test->CreateParams(Widget::InitParams::TYPE_POPUP); params.bounds = gfx::Rect(0, 0, 50, 100); - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(new CloseWidgetView(last_event_type)); widget->Show(); GenerateMouseEvents(widget, last_event_type); @@ -646,7 +646,7 @@ gfx::Rect initial_bounds(0, 0, 500, 500); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); top_level_widget.Show(); EXPECT_TRUE(top_level_widget.IsVisible()); @@ -750,7 +750,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); ui::WindowEventTarget* target =
diff --git a/ui/views/widget/desktop_aura/desktop_screen_x11_unittest.cc b/ui/views/widget/desktop_aura/desktop_screen_x11_unittest.cc index f105572..00c74e76 100644 --- a/ui/views/widget/desktop_aura/desktop_screen_x11_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_screen_x11_unittest.cc
@@ -117,7 +117,7 @@ } toplevel_params.bounds = bounds; toplevel_params.remove_standard_frame = true; - toplevel->Init(toplevel_params); + toplevel->Init(std::move(toplevel_params)); return toplevel; }
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_interactive_uitest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_interactive_uitest.cc index f959917f..a78dac93 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_interactive_uitest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_interactive_uitest.cc
@@ -161,7 +161,7 @@ toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; toplevel_params.bounds = bounds; toplevel_params.remove_standard_frame = true; - toplevel->Init(toplevel_params); + toplevel->Init(std::move(toplevel_params)); return toplevel; }
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc index 76a55cfb..71ffafc 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc
@@ -57,7 +57,7 @@ params.remove_standard_frame = true; params.native_widget = new DesktopNativeWidgetAura(widget.get()); params.bounds = gfx::Rect(100, 100, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win_unittest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_win_unittest.cc index 6d4aef5..cb045d8 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win_unittest.cc
@@ -24,12 +24,13 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.name = "test-debugging-id"; - widget.Init(params); + constexpr char kDebuggingName[] = "test-debugging-id"; + params.name = kDebuggingName; + widget.Init(std::move(params)); DesktopWindowTreeHostWin* desktop_window_tree_host = static_cast<DesktopWindowTreeHostWin*>( widget.GetNativeWindow()->GetHost()); - EXPECT_EQ(params.name, + EXPECT_EQ(std::string(kDebuggingName), DesktopWindowTreeHostWinTestApi(desktop_window_tree_host) .GetHwndMessageHandler() ->debugging_id()); @@ -71,7 +72,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); // Cache a pointer to the object we return to Windows. @@ -102,7 +103,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); // Cache a pointer to the object we return to Windows. @@ -136,7 +137,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); // Cache a pointer to the object we return to Windows.
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_interactive_uitest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_interactive_uitest.cc index c9a1535..5f154118 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_interactive_uitest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_interactive_uitest.cc
@@ -79,7 +79,7 @@ params.remove_standard_frame = true; params.native_widget = new DesktopNativeWidgetAura(widget.get()); params.bounds = bounds; - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc index 702502cf..1ea1d04e 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_x11_unittest.cc
@@ -128,7 +128,7 @@ params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.remove_standard_frame = true; params.bounds = gfx::Rect(100, 100, 100, 100); - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -362,7 +362,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); ui::X11EventSource::GetInstance()->DispatchXEvents(); @@ -421,7 +421,7 @@ Widget::InitParams parent_params = CreateParams(Widget::InitParams::TYPE_WINDOW); parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget.Init(parent_params); + parent_widget.Init(std::move(parent_params)); parent_widget.Show(); ui::X11EventSource::GetInstance()->DispatchXEvents(); @@ -430,7 +430,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = parent_widget.GetNativeWindow(); - child_widget.Init(child_params); + child_widget.Init(std::move(child_params)); child_widget.Show(); ui::X11EventSource::GetInstance()->DispatchXEvents(); @@ -466,7 +466,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(200, 100); - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); ui::X11EventSource::GetInstance()->DispatchXEvents(); @@ -539,14 +539,14 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(0, 0, 50, 50); - first.Init(params); + first.Init(std::move(params)); first.Show(); Widget second; params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 50, 50); - second.Init(params); + second.Init(std::move(params)); second.Show(); ui::X11EventSource::GetInstance()->DispatchXEvents();
diff --git a/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc b/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc index 100a1e8..dbdf6fd9 100644 --- a/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc +++ b/ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc
@@ -103,7 +103,7 @@ params.native_widget = new DesktopNativeWidgetAura(toplevel.get()); params.bounds = bounds; params.remove_standard_frame = true; - toplevel->Init(params); + toplevel->Init(std::move(params)); toplevel->Show(); return toplevel; }
diff --git a/ui/views/widget/desktop_widget_unittest.cc b/ui/views/widget/desktop_widget_unittest.cc index 1ab32fe..ad150c7 100644 --- a/ui/views/widget/desktop_widget_unittest.cc +++ b/ui/views/widget/desktop_widget_unittest.cc
@@ -20,7 +20,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(10, 11, 200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget.Init(params); + parent_widget.Init(std::move(params)); // Owned by |dialog|. DialogDelegateView* dialog_delegate_view = new DialogDelegateView; @@ -57,7 +57,7 @@ origin + work_area.OffsetFromOrigin(), gfx::Size(700, work_area.height() - origin.y() - work_area.y())); params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); + widget1.Init(std::move(params1)); Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW); @@ -67,7 +67,7 @@ params2.child = true; params2.native_widget = test::CreatePlatformNativeWidgetImpl( params2, &widget2, test::kStubCapture, nullptr); - widget2.Init(params2); + widget2.Init(std::move(params2)); Widget::InitParams params3 = CreateParams(Widget::InitParams::TYPE_CONTROL); @@ -77,7 +77,7 @@ params3.bounds = gfx::Rect(origin, gfx::Size(500, work_area.height() - 200)); params3.native_widget = test::CreatePlatformNativeWidgetImpl( params3, &widget3, test::kStubCapture, nullptr); - widget3.Init(params3); + widget3.Init(std::move(params3)); // The origin of the 3rd window should be the sum of all parent origins. gfx::Point expected_origin(origin.x() * 3 + work_area.x(), @@ -106,7 +106,7 @@ params.bounds = gfx::Rect( origin, gfx::Size(work_area.width() / 2, work_area.height() / 2)); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); // The bounds of the window should be fully on the primary display. gfx::Point expected_origin(work_area.right() - work_area.width() / 2, @@ -138,7 +138,7 @@ params1.bounds = gfx::Rect( origin, gfx::Size(work_area.width() / 2, work_area.height() / 2)); params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); + widget1.Init(std::move(params1)); gfx::Rect widget_bounds(widget1.GetWindowBoundsInScreen()); @@ -151,7 +151,7 @@ params2.child = true; params2.native_widget = test::CreatePlatformNativeWidgetImpl( params2, &widget2, test::kStubCapture, nullptr); - widget2.Init(params2); + widget2.Init(std::move(params2)); // The bounds of the child window should be fully in the parent. gfx::Point expected_origin(
diff --git a/ui/views/widget/native_widget_aura.cc b/ui/views/widget/native_widget_aura.cc index e160cce..5c57a25 100644 --- a/ui/views/widget/native_widget_aura.cc +++ b/ui/views/widget/native_widget_aura.cc
@@ -154,12 +154,15 @@ //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, internal::NativeWidgetPrivate implementation: -void NativeWidgetAura::InitNativeWidget(const Widget::InitParams& params) { +void NativeWidgetAura::InitNativeWidget(Widget::InitParams params) { // See Widget::InitParams::context for details. DCHECK(params.parent || params.context); ownership_ = params.ownership; + window_->AcquireAllPropertiesFrom( + std::move(params.init_properties_container)); + RegisterNativeWidgetForWindow(this, window_); window_->SetType(GetAuraWindowTypeForWidgetType(params.type)); if (params.corner_radius) {
diff --git a/ui/views/widget/native_widget_aura.h b/ui/views/widget/native_widget_aura.h index 8fea00d..b31bef1 100644 --- a/ui/views/widget/native_widget_aura.h +++ b/ui/views/widget/native_widget_aura.h
@@ -68,7 +68,7 @@ aura::Window* window); // Overridden from internal::NativeWidgetPrivate: - void InitNativeWidget(const Widget::InitParams& params) override; + void InitNativeWidget(Widget::InitParams params) override; void OnWidgetInitDone() override; NonClientFrameView* CreateNonClientFrameView() override; bool ShouldUseNativeFrame() const override;
diff --git a/ui/views/widget/native_widget_aura_interactive_uitest.cc b/ui/views/widget/native_widget_aura_interactive_uitest.cc index c50bcca..6715dff 100644 --- a/ui/views/widget/native_widget_aura_interactive_uitest.cc +++ b/ui/views/widget/native_widget_aura_interactive_uitest.cc
@@ -60,7 +60,7 @@ params1.native_widget = CreatePlatformNativeWidgetImpl(params1, widget1, kDefault, nullptr); params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1->Init(params1); + widget1->Init(std::move(params1)); Textfield* textfield1 = new Textfield; widget1->GetRootView()->AddChildView(textfield1); @@ -70,7 +70,7 @@ params2.native_widget = CreatePlatformNativeWidgetImpl(params2, widget2, kDefault, nullptr); params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2->Init(params2); + widget2->Init(std::move(params2)); Textfield* textfield2a = new Textfield; widget2->GetRootView()->AddChildView(textfield2a); Textfield* textfield2b = new Textfield;
diff --git a/ui/views/widget/native_widget_aura_unittest.cc b/ui/views/widget/native_widget_aura_unittest.cc index af625e07..4ddad6d 100644 --- a/ui/views/widget/native_widget_aura_unittest.cc +++ b/ui/views/widget/native_widget_aura_unittest.cc
@@ -35,7 +35,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_POPUP); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.parent = parent; - widget->Init(params); + widget->Init(std::move(params)); return static_cast<NativeWidgetAura*>(widget->native_widget()); } @@ -145,7 +145,7 @@ params.show_state = ui::SHOW_STATE_MINIMIZED; params.bounds.SetRect(0, 0, 1024, 800); std::unique_ptr<Widget> widget(new Widget()); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); EXPECT_TRUE(widget->IsMinimized()); @@ -194,7 +194,7 @@ params.show_state = ui::SHOW_STATE_NORMAL; params.bounds.SetRect(0, 0, 1024, 800); Widget widget; - widget.Init(params); + widget.Init(std::move(params)); std::unique_ptr<TestWindowObserver> observer( new TestWindowObserver(widget.GetNativeWindow())); widget.Show(); @@ -294,7 +294,7 @@ params.context = root_window(); params.show_state = ui::SHOW_STATE_MAXIMIZED; params.bounds = gfx::Rect(10, 10, 100, 200); - widget->Init(params); + widget->Init(std::move(params)); EXPECT_FALSE(widget->did_size_change_more_than_once()); widget->CloseNow(); } @@ -350,7 +350,7 @@ params.delegate = new PropertyTestWidgetDelegate(widget.get()); params.parent = nullptr; params.context = root_window(); - widget->Init(params); + widget->Init(std::move(params)); EXPECT_TRUE(layout_manager->added()); widget->CloseNow(); } @@ -362,7 +362,7 @@ params.context = root_window(); params.bounds.SetRect(10, 20, 300, 400); std::unique_ptr<Widget> widget(new Widget()); - widget->Init(params); + widget->Init(std::move(params)); // For Aura, client area bounds match window bounds. gfx::Rect client_bounds = widget->GetClientAreaBoundsInScreen(); @@ -420,7 +420,7 @@ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.context = root_window(); params.bounds = gfx::Rect(0, 0, 100, 200); - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(view); widget->Show(); @@ -462,7 +462,7 @@ parent_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; parent_params.context = root_window(); - parent->Init(parent_params); + parent->Init(std::move(parent_params)); parent->SetContentsView(parent_root); parent->SetBounds(gfx::Rect(0, 0, 400, 400)); parent->Show(); @@ -471,7 +471,7 @@ Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); child_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = parent->GetNativeWindow(); - child->Init(child_params); + child->Init(std::move(child_params)); child->SetBounds(gfx::Rect(0, 0, 200, 200)); child->Show(); @@ -525,7 +525,7 @@ Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS); parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; parent_params.context = root_window(); - parent.Init(parent_params); + parent.Init(std::move(parent_params)); parent.SetContentsView(parent_root_view); parent.SetBounds(gfx::Rect(0, 0, 400, 400)); parent.Show(); @@ -534,7 +534,7 @@ Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = parent.GetNativeWindow(); - child.Init(child_params); + child.Init(std::move(child_params)); child.SetBounds(gfx::Rect(0, 0, 200, 200)); child.Show(); @@ -571,7 +571,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.context = root_window(); params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); aura::Window* window = widget->GetNativeWindow(); EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey)); widget->FlashFrame(true); @@ -657,7 +657,7 @@ Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW); parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; parent_params.context = root_window(); - parent.Init(parent_params); + parent.Init(std::move(parent_params)); parent.SetBounds(gfx::Rect(0, 0, 480, 320)); // Add a child bubble window to the above parent window and show it. @@ -665,7 +665,7 @@ Widget::InitParams child_params(Widget::InitParams::TYPE_BUBBLE); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.parent = parent.GetNativeWindow(); - child.Init(child_params); + child.Init(std::move(child_params)); child.SetBounds(gfx::Rect(0, 0, 200, 200)); child.Show();
diff --git a/ui/views/widget/native_widget_mac.h b/ui/views/widget/native_widget_mac.h index 6db556b..56a4e03 100644 --- a/ui/views/widget/native_widget_mac.h +++ b/ui/views/widget/native_widget_mac.h
@@ -85,7 +85,7 @@ } // internal::NativeWidgetPrivate: - void InitNativeWidget(const Widget::InitParams& params) override; + void InitNativeWidget(Widget::InitParams params) override; void OnWidgetInitDone() override; NonClientFrameView* CreateNonClientFrameView() override; bool ShouldUseNativeFrame() const override;
diff --git a/ui/views/widget/native_widget_mac.mm b/ui/views/widget/native_widget_mac.mm index f948242..a153cd5 100644 --- a/ui/views/widget/native_widget_mac.mm +++ b/ui/views/widget/native_widget_mac.mm
@@ -183,7 +183,7 @@ //////////////////////////////////////////////////////////////////////////////// // NativeWidgetMac, internal::NativeWidgetPrivate implementation: -void NativeWidgetMac::InitNativeWidget(const Widget::InitParams& params) { +void NativeWidgetMac::InitNativeWidget(Widget::InitParams params) { ownership_ = params.ownership; name_ = params.name; type_ = params.type;
diff --git a/ui/views/widget/native_widget_mac_unittest.mm b/ui/views/widget/native_widget_mac_unittest.mm index d11874a..6cd51c6 100644 --- a/ui/views/widget/native_widget_mac_unittest.mm +++ b/ui/views/widget/native_widget_mac_unittest.mm
@@ -166,7 +166,7 @@ Widget::InitParams parent_init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); parent_init_params.bounds = gfx::Rect(100, 100, 200, 200); - CreateWidgetWithTestWindow(parent_init_params, &native_parent); + CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent); return native_parent; } @@ -177,7 +177,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW); parent_init_params.remove_standard_frame = true; parent_init_params.bounds = gfx::Rect(100, 100, 200, 200); - CreateWidgetWithTestWindow(parent_init_params, &native_parent); + CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent); return native_parent; } @@ -186,7 +186,7 @@ NativeWidgetMacTestWindow** window) { Widget* widget = new Widget; params.native_widget = new TestWindowNativeWidgetMac(widget); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); *window = base::mac::ObjCCastStrict<NativeWidgetMacTestWindow>( widget->GetNativeWindow().GetNativeNSWindow()); @@ -492,13 +492,15 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW); init_params.bounds = gfx::Rect(100, 100, 200, 200); - Widget* parent = CreateWidgetWithTestWindow(init_params, &parent_window); + Widget* parent = + CreateWidgetWithTestWindow(std::move(init_params), &parent_window); // CreateWidgetWithTestWindow calls Show() EXPECT_EQ(1, [parent_window orderWindowCount]); init_params.parent = parent->GetNativeView(); - Widget* child = CreateWidgetWithTestWindow(init_params, &child_window); + Widget* child = + CreateWidgetWithTestWindow(std::move(init_params), &child_window); // The child is ordered twice, once by Show() and again (by AppKit) when it is // registered as a child window. @@ -528,7 +530,7 @@ return; // Fails when swarmed. http://crbug.com/660582 Widget* widget = new Widget; Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW); - widget->Init(init_params); + widget->Init(std::move(init_params)); PaintCountView* view = new PaintCountView(); widget->GetContentsView()->AddChildView(view); @@ -756,7 +758,7 @@ Widget::InitParams init_params; init_params.parent = anchor_view.get(); init_params.type = Widget::InitParams::TYPE_POPUP; - child->Init(init_params); + child->Init(std::move(init_params)); return child; } @@ -917,7 +919,7 @@ CreateParams(Widget::InitParams::TYPE_POPUP); init_params.parent = [native_parent contentView]; init_params.bounds = gfx::Rect(0, 0, 100, 200); - CreateWidgetWithTestWindow(init_params, &window); + CreateWidgetWithTestWindow(std::move(init_params), &window); [window setDeallocFlag:&child_dealloced]; } { @@ -1093,7 +1095,7 @@ TEST_F(NativeWidgetMacTest, CapturedMouseUpClearsDrag) { MouseTrackingWidget* widget = new MouseTrackingWidget; Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW); - widget->Init(init_params); + widget->Init(std::move(init_params)); NSWindow* window = widget->GetNativeWindow().GetNativeNSWindow(); BridgedContentView* native_view = [window contentView]; @@ -1664,7 +1666,7 @@ init_params.bounds = gfx::Rect(100, 100, 100, 100); init_params.native_widget = CreatePlatformNativeWidgetImpl( init_params, child, kStubCapture, nullptr); - child->Init(init_params); + child->Init(std::move(init_params)); child->Show(); // NSWindow parent/child relationship should be established on Show() and @@ -1741,7 +1743,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(100, 100, 300, 200); - parent->Init(params); + parent->Init(std::move(params)); parent->Show(); ParentCloseMonitor monitor(parent.get()); @@ -1856,7 +1858,7 @@ CustomTitleWidgetDelegate delegate(widget); params.delegate = &delegate; params.bounds = gfx::Rect(0, 0, 800, 600); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow(); @@ -1895,7 +1897,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.bounds = rect; - Widget* widget = CreateWidgetWithTestWindow(init_params, &window); + Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window); // Simulate the initial paint. BridgedNativeWidgetTestApi(window).SimulateFrameSwap(rect.size()); @@ -1905,7 +1907,7 @@ widget->CloseNow(); init_params.opacity = Widget::InitParams::TRANSLUCENT_WINDOW; - widget = CreateWidgetWithTestWindow(init_params, &window); + widget = CreateWidgetWithTestWindow(std::move(init_params), &window); BridgedNativeWidgetTestApi test_api(window); // First paint on a translucent window needs to invalidate the shadow. Once. @@ -1947,20 +1949,20 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); EXPECT_EQ(init_params.opacity, Widget::InitParams::INFER_OPACITY); - Widget* widget = CreateWidgetWithTestWindow(init_params, &window); + Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window); // Infer should default to opaque on Mac. EXPECT_TRUE([[window contentView] isOpaque]); widget->CloseNow(); init_params.opacity = Widget::InitParams::TRANSLUCENT_WINDOW; - widget = CreateWidgetWithTestWindow(init_params, &window); + widget = CreateWidgetWithTestWindow(std::move(init_params), &window); EXPECT_FALSE([[window contentView] isOpaque]); widget->CloseNow(); // Test opaque explicitly. init_params.opacity = Widget::InitParams::OPAQUE_WINDOW; - widget = CreateWidgetWithTestWindow(init_params, &window); + widget = CreateWidgetWithTestWindow(std::move(init_params), &window); EXPECT_TRUE([[window contentView] isOpaque]); widget->CloseNow(); } @@ -1974,7 +1976,7 @@ // This is relative to the top-left of the primary screen, so unless the bot's // display is smaller than 400x300, the window will be wholly contained there. params.bounds = gfx::Rect(100, 100, 300, 200); - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); NSRect expected = [[[NSScreen screens] firstObject] visibleFrame]; NSRect actual = gfx::ScreenRectToNSRect(widget.GetWorkAreaBoundsInScreen()); @@ -2126,7 +2128,7 @@ Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); params.parent = parent->GetNativeView(); Widget* widget = new Widget; - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(new View); NSView* child_view = widget->GetNativeView().GetNativeNSView(); @@ -2163,16 +2165,16 @@ Widget::InitParams toplevel_params = CreateParams(Widget::InitParams::TYPE_POPUP); toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel1->Init(toplevel_params); + toplevel1->Init(std::move(toplevel_params)); toplevel1->Show(); std::unique_ptr<Widget> toplevel2(new Widget); - toplevel2->Init(toplevel_params); + toplevel2->Init(std::move(toplevel_params)); toplevel2->Show(); Widget* child = new Widget; Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); - child->Init(child_params); + child->Init(std::move(child_params)); child->Show(); Widget::ReparentNativeView(child->GetNativeView(),
diff --git a/ui/views/widget/native_widget_private.h b/ui/views/widget/native_widget_private.h index 84acc003..4aa5fd1 100644 --- a/ui/views/widget/native_widget_private.h +++ b/ui/views/widget/native_widget_private.h
@@ -78,7 +78,7 @@ static gfx::Rect ConstrainBoundsToDisplayWorkArea(const gfx::Rect& bounds); // Initializes the NativeWidget. - virtual void InitNativeWidget(const Widget::InitParams& params) = 0; + virtual void InitNativeWidget(Widget::InitParams params) = 0; // Called at the end of Widget::Init(), after Widget has completed // initialization.
diff --git a/ui/views/widget/native_widget_unittest.cc b/ui/views/widget/native_widget_unittest.cc index 2affa7fa..5167fab 100644 --- a/ui/views/widget/native_widget_unittest.cc +++ b/ui/views/widget/native_widget_unittest.cc
@@ -44,7 +44,7 @@ Widget::InitParams params = CreateParams(type); params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET; params.bounds = gfx::Rect(10, 10, 200, 200); - widget->Init(params); + widget->Init(std::move(params)); return widget->native_widget_private(); }
diff --git a/ui/views/widget/root_view_unittest.cc b/ui/views/widget/root_view_unittest.cc index 0498f67..7f5977f3 100644 --- a/ui/views/widget/root_view_unittest.cc +++ b/ui/views/widget/root_view_unittest.cc
@@ -46,7 +46,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.Show(); bool got_key_event = false; @@ -117,7 +117,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.Show(); internal::RootView* root_view = static_cast<internal::RootView*>(widget.GetRootView()); @@ -185,7 +185,7 @@ CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(100, 100); - widget.Init(init_params); + widget.Init(std::move(init_params)); internal::RootView* root_view = static_cast<internal::RootView*>(widget.GetRootView()); @@ -259,7 +259,7 @@ CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.bounds = gfx::Rect(100, 100); - widget.Init(init_params); + widget.Init(std::move(init_params)); internal::RootView* root_view = static_cast<internal::RootView*>(widget.GetRootView()); @@ -411,7 +411,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -450,7 +450,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -490,7 +490,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -530,7 +530,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -567,7 +567,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -605,7 +605,7 @@ Widget widget; Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetBounds(gfx::Rect(10, 10, 500, 500)); View* content = new View; @@ -663,7 +663,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(init_params); + widget->Init(std::move(init_params)); widget->SetBounds(gfx::Rect(10, 10, 500, 500)); WidgetDeletionObserver widget_deletion_observer(widget); @@ -701,7 +701,7 @@ Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(init_params); + widget->Init(std::move(init_params)); widget->SetBounds(gfx::Rect(10, 10, 500, 500)); WidgetDeletionObserver widget_deletion_observer(widget);
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc index cfdd9a4..74bdc0b 100644 --- a/ui/views/widget/widget.cc +++ b/ui/views/widget/widget.cc
@@ -144,7 +144,7 @@ Widget::InitParams::InitParams(Type type) : type(type) {} -Widget::InitParams::InitParams(const InitParams& other) = default; +Widget::InitParams::InitParams(InitParams&& other) = default; Widget::InitParams::~InitParams() = default; @@ -204,7 +204,7 @@ params.delegate = delegate; params.parent = parent; params.bounds = bounds; - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -223,7 +223,7 @@ params.delegate = delegate; params.context = context; params.bounds = bounds; - widget->Init(params); + widget->Init(std::move(params)); return widget; } @@ -294,9 +294,8 @@ type == InitParams::TYPE_BUBBLE; } -void Widget::Init(const InitParams& in_params) { +void Widget::Init(InitParams params) { TRACE_EVENT0("views", "Widget::Init"); - InitParams params = in_params; // If an internal name was not provided the class name of the contents view // is a reasonable default. @@ -332,10 +331,17 @@ native_widget_ = CreateNativeWidget(params, this)->AsNativeWidgetPrivate(); root_view_.reset(CreateRootView()); default_theme_provider_ = std::make_unique<ui::DefaultThemeProvider>(); - native_widget_->InitNativeWidget(params); - if (params.type == InitParams::TYPE_MENU) + + // Copy the elements of params that will be used after it is moved. + const InitParams::Type type = params.type; + const gfx::Rect bounds = params.bounds; + const ui::WindowShowState show_state = params.show_state; + WidgetDelegate* delegate = params.delegate; + + native_widget_->InitNativeWidget(std::move(params)); + if (type == InitParams::TYPE_MENU) is_mouse_button_pressed_ = native_widget_->IsMouseButtonDown(); - if (RequiresNonClientView(params.type)) { + if (RequiresNonClientView(type)) { non_client_view_ = new NonClientView; non_client_view_->SetFrameView(CreateNonClientFrameView()); // Create the ClientView, add it to the NonClientView and add the @@ -354,22 +360,22 @@ UpdateWindowIcon(); UpdateWindowTitle(); non_client_view_->ResetWindowControls(); - SetInitialBounds(params.bounds); + SetInitialBounds(bounds); // Perform the initial layout. This handles the case where the size might // not actually change when setting the initial bounds. If it did, child // views won't have a dirty Layout state, so won't do any work. root_view_->Layout(); - if (params.show_state == ui::SHOW_STATE_MAXIMIZED) { + if (show_state == ui::SHOW_STATE_MAXIMIZED) { Maximize(); - } else if (params.show_state == ui::SHOW_STATE_MINIMIZED) { + } else if (show_state == ui::SHOW_STATE_MINIMIZED) { Minimize(); saved_show_state_ = ui::SHOW_STATE_MINIMIZED; } - } else if (params.delegate) { - SetContentsView(params.delegate->GetContentsView()); - SetInitialBoundsForFramelessWindow(params.bounds); + } else if (delegate) { + SetContentsView(delegate->GetContentsView()); + SetInitialBoundsForFramelessWindow(bounds); } // TODO(https://crbug.com/953978): Use GetNativeTheme() for all platforms. #if defined(OS_MACOSX) || defined(OS_WIN)
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h index e5df434..3d63c45 100644 --- a/ui/views/widget/widget.h +++ b/ui/views/widget/widget.h
@@ -214,9 +214,11 @@ // Initialization for other |type| types. explicit InitParams(Type type); - InitParams(const InitParams& other); + InitParams(InitParams&& other); ~InitParams(); + InitParams& operator=(InitParams&& rhs) = default; + // Returns the activatablity based on |activatable|, but also handles the // case where |activatable| is |ACTIVATABLE_DEFAULT|. bool CanActivate() const; @@ -332,6 +334,12 @@ // If set, mouse events will be sent to the widget even if inactive. bool wants_mouse_events_when_inactive = false; + + // Contains any properties with which the native widget should be + // initialized prior to adding it to the window hierarchy. All the + // properties in |init_properties_container| will be moved to the native + // widget. + ui::PropertyHandler init_properties_container; }; // Represents a lock held on the widget's ShouldPaintAsActive() state. As @@ -414,7 +422,9 @@ // Returns true if the specified type requires a NonClientView. static bool RequiresNonClientView(InitParams::Type type); - void Init(const InitParams& params); + // Initializes the widget, and in turn, the native widget. |params| should be + // moved to Init() by the caller. + void Init(InitParams params); // Returns the gfx::NativeView associated with this Widget. gfx::NativeView GetNativeView() const;
diff --git a/ui/views/widget/widget_interactive_uitest.cc b/ui/views/widget/widget_interactive_uitest.cc index 7546772..24c48fc 100644 --- a/ui/views/widget/widget_interactive_uitest.cc +++ b/ui/views/widget/widget_interactive_uitest.cc
@@ -873,13 +873,13 @@ init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.native_widget = new DesktopNativeWidgetAura(&widget1); init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget1.Init(init_params); + widget1.Init(std::move(init_params)); widget1.Show(); EXPECT_EQ(true, widget1.active()); WidgetActivationTest widget2; init_params.native_widget = new DesktopNativeWidgetAura(&widget2); - widget2.Init(init_params); + widget2.Init(std::move(init_params)); widget2.Show(); EXPECT_EQ(true, widget2.active()); EXPECT_EQ(false, widget1.active()); @@ -906,7 +906,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW); params.native_widget = new DesktopNativeWidgetAura(&widget1); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params); + widget1.Init(std::move(params)); widget1.SetBounds(gfx::Rect(0, 0, 200, 200)); widget1.Show(); @@ -927,7 +927,7 @@ Widget widget2; params.native_widget = new DesktopNativeWidgetAura(&widget2); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2.Init(params); + widget2.Init(std::move(params)); widget2.SetBounds(gfx::Rect(0, 0, 200, 200)); widget2.Show(); @@ -967,7 +967,7 @@ params.native_widget = new DesktopNativeWidgetAura(&widget); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; widget.set_frame_type(Widget::FRAME_TYPE_FORCE_CUSTOM); - widget.Init(params); + widget.Init(std::move(params)); widget.SetBounds(gfx::Rect(0, 0, 200, 200)); widget.Show(); @@ -1042,7 +1042,7 @@ gfx::Rect initial_bounds(0, 0, 500, 500); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); ShowSync(&top_level_widget); gfx::NativeView top_level_native_view = top_level_widget.GetNativeView(); @@ -1115,7 +1115,7 @@ gfx::Rect initial_bounds(0, 0, 500, 500); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); ShowSync(&top_level_widget); ASSERT_FALSE(focus_listener.focus_changes().empty()); @@ -1149,7 +1149,7 @@ init_params.bounds = gfx::Rect(0, 0, 200, 200); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; init_params.activatable = Widget::InitParams::ACTIVATABLE_NO; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.Show(); EXPECT_FALSE(widget.IsActive()); @@ -1207,7 +1207,7 @@ Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_POPUP); params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params1.activatable = Widget::InitParams::ACTIVATABLE_YES; - widget1.Init(params1); + widget1.Init(std::move(params1)); View* view1 = new View(); view1->SetFocusBehavior(View::FocusBehavior::ALWAYS); @@ -1226,7 +1226,7 @@ Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_POPUP); params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params2.activatable = Widget::InitParams::ACTIVATABLE_YES; - widget2.Init(params2); + widget2.Init(std::move(params2)); View* view2 = new View(); view2->SetFocusBehavior(View::FocusBehavior::ALWAYS); @@ -1325,7 +1325,7 @@ Widget widget2; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2.Init(params); + widget2.Init(std::move(params)); widget2.Show(); RunPendingMessagesForActiveStatusChange(); @@ -1591,7 +1591,7 @@ params1.native_widget = CreateNativeWidget(params1, use_desktop_native_widget, &widget1); params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); + widget1.Init(std::move(params1)); widget1.Show(); CaptureLostState capture_state2; @@ -1601,7 +1601,7 @@ params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params2.native_widget = CreateNativeWidget(params2, use_desktop_native_widget, &widget2); - widget2.Init(params2); + widget2.Init(std::move(params2)); widget2.Show(); // Set capture to widget2 and verity it gets it. @@ -1658,7 +1658,7 @@ CaptureLostTrackingWidget* widget = new CaptureLostTrackingWidget(&capture_state); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->SetCapture(widget->GetRootView()); @@ -1674,7 +1674,7 @@ CaptureLostTrackingWidget* widget = new CaptureLostTrackingWidget(&capture_state); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->SetCapture(widget->GetRootView()); @@ -1688,7 +1688,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); widget.SetCapture(widget.GetRootView()); @@ -1702,7 +1702,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(400, 400); - widget.Init(params); + widget.Init(std::move(params)); MouseView* mouse_view1 = new MouseView; MouseView* mouse_view2 = new MouseView; @@ -1744,7 +1744,7 @@ Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); + widget1.Init(std::move(params1)); MouseView* mouse_view1 = new MouseView; widget1.SetContentsView(mouse_view1); widget1.Show(); @@ -1754,7 +1754,7 @@ Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2.Init(params2); + widget2.Init(std::move(params2)); widget2.Show(); widget2.SetBounds(gfx::Rect(400, 0, 300, 300)); @@ -1805,7 +1805,7 @@ Widget::InitParams toplevel_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel.Init(toplevel_params); + toplevel.Init(std::move(toplevel_params)); toplevel.Show(); Widget* child = new Widget; @@ -1813,7 +1813,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); child_params.parent = toplevel.GetNativeView(); child_params.context = toplevel.GetNativeWindow(); - child->Init(child_params); + child->Init(std::move(child_params)); CaptureOnActivationObserver observer; child->AddObserver(&observer); @@ -1872,7 +1872,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params1.native_widget = new DesktopNativeWidgetAura(&widget1); params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); + widget1.Init(std::move(params1)); widget1.Show(); MouseEventTrackingWidget widget2; @@ -1880,7 +1880,7 @@ CreateParams(views::Widget::InitParams::TYPE_WINDOW); params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params2.native_widget = new DesktopNativeWidgetAura(&widget2); - widget2.Init(params2); + widget2.Init(std::move(params2)); widget2.Show(); // Set capture to widget2 and verity it gets it.
diff --git a/ui/views/widget/widget_unittest.cc b/ui/views/widget/widget_unittest.cc index 64a5731a..ad2cd7a 100644 --- a/ui/views/widget/widget_unittest.cc +++ b/ui/views/widget/widget_unittest.cc
@@ -183,7 +183,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.name = "MyWidget"; - widget.Init(params); + widget.Init(std::move(params)); EXPECT_EQ("MyWidget", widget.native_widget_private()->GetName()); EXPECT_EQ("MyWidget", widget.GetName()); @@ -353,7 +353,7 @@ params.native_widget = CreatePlatformNativeWidgetImpl( params, widget.get(), kStubCapture, &state.native_widget_deleted); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); // Now delete the Widget, which should delete the NativeWidget. widget.reset(); @@ -374,7 +374,7 @@ params.native_widget = CreatePlatformNativeWidgetImpl( params, widget.get(), kStubCapture, &state.native_widget_deleted); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); // Now delete the Widget, which should delete the NativeWidget. widget.reset(); @@ -400,7 +400,7 @@ params.native_widget = CreatePlatformNativeWidgetImpl( params, widget.get(), kStubCapture, &state.native_widget_deleted); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); // Now close the toplevel, which deletes the view hierarchy. toplevel->CloseNow(); @@ -428,7 +428,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.native_widget = CreatePlatformNativeWidgetImpl( params, widget, kStubCapture, &state.native_widget_deleted); - widget->Init(params); + widget->Init(std::move(params)); // Now destroy the native widget. widget->CloseNow(); @@ -448,7 +448,7 @@ params.parent = toplevel->GetNativeView(); params.native_widget = CreatePlatformNativeWidgetImpl( params, widget, kStubCapture, &state.native_widget_deleted); - widget->Init(params); + widget->Init(std::move(params)); // Now destroy the native widget. This is achieved by closing the toplevel. toplevel->CloseNow(); @@ -471,7 +471,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.native_widget = CreatePlatformNativeWidgetImpl( params, widget, kStubCapture, &state.native_widget_deleted); - widget->Init(params); + widget->Init(std::move(params)); // Now simulate a destroy of the platform native widget from the OS: SimulateNativeDestroy(widget); @@ -493,7 +493,7 @@ params.parent = toplevel->GetNativeView(); params.native_widget = CreatePlatformNativeWidgetImpl( params, widget, kStubCapture, &state.native_widget_deleted); - widget->Init(params); + widget->Init(std::move(params)); // Destroy the widget (achieved by closing the toplevel). toplevel->CloseNow(); @@ -519,7 +519,7 @@ params.parent = toplevel->GetNativeView(); params.native_widget = CreatePlatformNativeWidgetImpl( params, widget, kStubCapture, &state.native_widget_deleted); - widget->Init(params); + widget->Init(std::move(params)); // Destroy the widget. widget->Close(); @@ -546,7 +546,7 @@ params, widget.get(), kStubCapture, &state.native_widget_deleted); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = delegate_view; - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(delegate_view); // Now delete the Widget. There should be no crash or use-after-free. @@ -566,7 +566,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.Show(); widget.native_widget_private()->CloseNow(); @@ -878,7 +878,7 @@ // Init causes a bounds change, even while not showing. Note some platforms // cause a bounds change even when the bounds are empty. Mac does not. - widget->Init(params); + widget->Init(std::move(params)); EXPECT_TRUE(widget_bounds_changed()); reset(); @@ -959,7 +959,7 @@ TEST_F(DesktopWidgetObserverTest, OnWidgetMovedWhenOriginChangesNative) { MoveTrackingTestDesktopWidgetDelegate delegate; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - delegate.InitWidget(params); + delegate.InitWidget(std::move(params)); Widget* widget = delegate.GetWidget(); widget->Show(); widget->SetBounds(gfx::Rect(100, 100, 300, 200)); @@ -1288,7 +1288,7 @@ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); init_params.bounds = gfx::Rect(0, 0, 200, 200); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); widget.SetContentsView(contents_view); widget.Show(); widget.Activate(); @@ -1341,7 +1341,7 @@ gfx::Rect initial_bounds(0, 0, 300, 400); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); NonClientView* non_client_view = widget.non_client_view(); NonClientFrameView* frame_view = new MinimumSizeFrameView(&widget); non_client_view->SetFrameView(frame_view); @@ -1414,7 +1414,7 @@ void DesktopAuraTestValidPaintWidget::InitForTest(InitParams init_params) { init_params.bounds = gfx::Rect(0, 0, 200, 200); init_params.ownership = InitParams::WIDGET_OWNS_NATIVE_WIDGET; - Init(init_params); + Init(std::move(init_params)); View* contents_view = new View; contents_view->SetFocusBehavior(View::FocusBehavior::ALWAYS); @@ -1460,7 +1460,7 @@ gfx::Rect initial_bounds(0, 0, 300, 400); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); NonClientView* non_client_view = widget.non_client_view(); NonClientFrameView* frame_view = new MinimumSizeFrameView(&widget); non_client_view->SetFrameView(frame_view); @@ -2004,7 +2004,7 @@ TestDesktopWidgetDelegate delegate(new TestNativeWidgetDestroyedWidget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - delegate.InitWidget(params); + delegate.InitWidget(std::move(params)); delegate.GetWidget()->Show(); delegate.GetWidget()->CloseNow(); } @@ -2081,7 +2081,7 @@ init_params.native_widget = CreatePlatformNativeWidgetImpl( init_params, widget.get(), kStubCapture, nullptr); } - widget->Init(init_params); + widget->Init(std::move(init_params)); internal::NativeWidgetPrivate* native_widget = widget->native_widget_private(); @@ -2123,7 +2123,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(new CloseWidgetView(ui::ET_MOUSE_PRESSED)); @@ -2148,7 +2148,7 @@ Widget* widget = new Widget; Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_POPUP); - widget->Init(params); + widget->Init(std::move(params)); widget->SetContentsView(new CloseWidgetView(ui::ET_GESTURE_TAP_DOWN)); @@ -2182,12 +2182,11 @@ // crash. |is_first_run| is true if this is the first call. A return value of // true indicates this should be run again with a value of false. // First run uses DesktopNativeWidgetAura (if possible). Second run doesn't. -bool RunGetNativeThemeFromDestructor(const Widget::InitParams& in_params, +bool RunGetNativeThemeFromDestructor(Widget::InitParams params, bool is_first_run) { bool needs_second_run = false; // Destroyed by CloseNow() below. WidgetTest::WidgetAutoclosePtr widget(new Widget); - Widget::InitParams params(in_params); // Deletes itself when the Widget is destroyed. params.delegate = new GetNativeThemeFromDestructorView; if (!is_first_run) { @@ -2195,15 +2194,15 @@ params, widget.get(), kStubCapture, nullptr); needs_second_run = true; } - widget->Init(params); + widget->Init(std::move(params)); return needs_second_run; } // See description of RunGetNativeThemeFromDestructor() for details. TEST_F(DesktopWidgetTest, GetNativeThemeFromDestructor) { Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - if (RunGetNativeThemeFromDestructor(params, true)) - RunGetNativeThemeFromDestructor(params, false); + if (RunGetNativeThemeFromDestructor(std::move(params), true)) + RunGetNativeThemeFromDestructor(std::move(params), false); } // Used by HideCloseDestroy. Allows setting a boolean when the widget is @@ -2277,7 +2276,7 @@ Widget::InitParams params = CreateParams(views::Widget::InitParams::TYPE_MENU); params.opacity = Widget::InitParams::OPAQUE_WINDOW; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); widget->Hide(); widget->Close(); @@ -2298,7 +2297,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = gfx::Rect(50, 50, 250, 250); - widget->Init(params); + widget->Init(std::move(params)); AnimationEndObserver animation_observer; WidgetBoundsObserver widget_observer; gfx::Rect bounds(100, 100, 50, 50); @@ -2375,14 +2374,14 @@ std::unique_ptr<Widget> widget(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); } TEST_F(WidgetTest, NoCrashOnResizeConstraintsWindowTitleOnPopup) { std::unique_ptr<Widget> widget(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->OnSizeConstraintsChanged(); } @@ -2393,7 +2392,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); + widget->Init(std::move(params)); widget->Show(); ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); @@ -3239,7 +3238,7 @@ params.native_widget = CreatePlatformNativeWidgetImpl( params, top_level, kStubCapture, nullptr); } - top_level->Init(params); + top_level->Init(std::move(params)); top_level->GetRootView()->AddChildView( new DestroyedTrackingView("parent", &destroyed)); top_level->Show(); @@ -3252,7 +3251,7 @@ child_params.native_widget = CreatePlatformNativeWidgetImpl( child_params, child, kStubCapture, nullptr); } - child->Init(child_params); + child->Init(std::move(child_params)); child->GetRootView()->AddChildView( new DestroyedTrackingView("child", &destroyed)); child->Show(); @@ -3299,7 +3298,7 @@ init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; Widget top_level_widget; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); top_level_widget.SetFullscreen(true); EXPECT_EQ(top_level_widget.IsVisible(), IsNativeWindowVisible(top_level_widget.GetNativeWindow())); @@ -3316,7 +3315,7 @@ init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; Widget top_level_widget; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); top_level_widget.SetFullscreen(true); EXPECT_EQ(top_level_widget.IsVisible(), IsNativeWindowVisible(top_level_widget.GetNativeWindow())); @@ -3406,7 +3405,7 @@ Widget::InitParams parent_params = CreateParams(Widget::InitParams::TYPE_POPUP); parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget.Init(parent_params); + parent_widget.Init(std::move(parent_params)); parent_widget.Show(); Widget child_widget; @@ -3414,7 +3413,7 @@ CreateParams(Widget::InitParams::TYPE_POPUP); child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; child_params.context = parent_widget.GetNativeWindow(); - child_widget.Init(child_params); + child_widget.Init(std::move(child_params)); child_widget.AddObserver(&observer); child_widget.Show(); @@ -3595,7 +3594,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.SetBounds(gfx::Rect(0, 0, 200, 200)); widget.Show(); ::SetCursorPos(500, 500); @@ -3667,7 +3666,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.SetBounds(gfx::Rect(0, 0, 200, 200)); widget.Show(); ::SetCursorPos(500, 500); @@ -3885,7 +3884,7 @@ Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); + widget.Init(std::move(params)); widget.SetBounds(gfx::Rect(0, 0, 600, 600)); LayoutCountingView* view = widget.widget_delegate()->GetContentsView()->AddChildView( @@ -4105,7 +4104,7 @@ gfx::Rect initial_bounds(0, 0, 500, 500); init_params.bounds = initial_bounds; init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - top_level_widget.Init(init_params); + top_level_widget.Init(std::move(init_params)); top_level_widget.Show(); // Create the owner modal dialog. @@ -4123,7 +4122,7 @@ init_params.native_widget = new test::TestPlatformNativeWidget<DesktopNativeWidgetAura>( &owner_dialog_widget, false, nullptr); - owner_dialog_widget.Init(init_params); + owner_dialog_widget.Init(std::move(init_params)); HWND owner_hwnd = HWNDForWidget(&owner_dialog_widget); @@ -4144,7 +4143,7 @@ init_params.native_widget = new test::TestPlatformNativeWidget<DesktopNativeWidgetAura>( &owned_dialog_widget, false, nullptr); - owned_dialog_widget.Init(init_params); + owned_dialog_widget.Init(std::move(init_params)); HWND owned_hwnd = HWNDForWidget(&owned_dialog_widget); @@ -4181,7 +4180,7 @@ init_params.show_state = ui::SHOW_STATE_NORMAL; init_params.bounds = gfx::Rect(0, 0, 500, 500); init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); + widget.Init(std::move(init_params)); } class CompositingWidgetTest : public DesktopWidgetTest {
diff --git a/ui/views/widget/window_reorderer_unittest.cc b/ui/views/widget/window_reorderer_unittest.cc index 32b8e672..f28db1e4 100644 --- a/ui/views/widget/window_reorderer_unittest.cc +++ b/ui/views/widget/window_reorderer_unittest.cc
@@ -25,7 +25,7 @@ params.parent = parent; params.bounds = bounds; Widget* widget = new Widget(); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/window/custom_frame_view_unittest.cc b/ui/views/window/custom_frame_view_unittest.cc index fbf1e87..e65e7b9 100644 --- a/ui/views/window/custom_frame_view_unittest.cc +++ b/ui/views/window/custom_frame_view_unittest.cc
@@ -125,7 +125,7 @@ Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.delegate = minimize_and_maximize_state_control_delegate_; params.remove_standard_frame = true; - widget_->Init(params); + widget_->Init(std::move(params)); custom_frame_view_ = new CustomFrameView; widget_->non_client_view()->SetFrameView(custom_frame_view_);
diff --git a/ui/views/window/dialog_client_view_unittest.cc b/ui/views/window/dialog_client_view_unittest.cc index 152917b..c9bac83 100644 --- a/ui/views/window/dialog_client_view_unittest.cc +++ b/ui/views/window/dialog_client_view_unittest.cc
@@ -44,7 +44,7 @@ widget_ = new views::Widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.delegate = this; - widget_->Init(params); + widget_->Init(std::move(params)); EXPECT_EQ(this, GetContentsView()); }
diff --git a/ui/views/window/dialog_delegate.cc b/ui/views/window/dialog_delegate.cc index 6f1ed11c1..b397f2f 100644 --- a/ui/views/window/dialog_delegate.cc +++ b/ui/views/window/dialog_delegate.cc
@@ -46,7 +46,7 @@ views::Widget* widget = new views::Widget; views::Widget::InitParams params = GetDialogWidgetInitParams(delegate, context, parent, gfx::Rect()); - widget->Init(params); + widget->Init(std::move(params)); return widget; }
diff --git a/ui/views/window/non_client_view_unittest.cc b/ui/views/window/non_client_view_unittest.cc index 7f2d5c1..c314cd9 100644 --- a/ui/views/window/non_client_view_unittest.cc +++ b/ui/views/window/non_client_view_unittest.cc
@@ -67,7 +67,7 @@ params.delegate = new TestWidgetDelegate; params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; views::Widget widget; - widget.Init(params); + widget.Init(std::move(params)); NonClientView* non_client_view = widget.non_client_view();
diff --git a/ui/webui/resources/BUILD.gn b/ui/webui/resources/BUILD.gn index 05e762c..708ed37 100644 --- a/ui/webui/resources/BUILD.gn +++ b/ui/webui/resources/BUILD.gn
@@ -12,3 +12,10 @@ "js:closure_compile_modules", ] } + +group("modulize") { + deps = [ + "cr_elements:polymer3_elements", + "js:modulize", + ] +}
diff --git a/ui/webui/resources/cr_elements/BUILD.gn b/ui/webui/resources/cr_elements/BUILD.gn index 535b413..47a5a90 100644 --- a/ui/webui/resources/cr_elements/BUILD.gn +++ b/ui/webui/resources/cr_elements/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") group("closure_compile") { deps = [ @@ -56,3 +57,50 @@ "//ui/webui/resources/js:assert", ] } + +# Targets for auto-generating Polymer 3 JS Modules. + +polymer_modulizer("shared_vars_css") { + js_file = "shared_vars_css.m.js" + html_file = "shared_vars_css.html" + html_type = "custom-style" +} + +polymer_modulizer("shared_style_css") { + js_file = "shared_style_css.m.js" + html_file = "shared_style_css.html" + html_type = "style-module" +} + +polymer_modulizer("hidden_style_css") { + js_file = "hidden_style_css.m.js" + html_file = "hidden_style_css.html" + html_type = "style-module" +} + +polymer_modulizer("md_select_css") { + js_file = "md_select_css.m.js" + html_file = "md_select_css.html" + html_type = "style-module" +} + +polymer_modulizer("icons") { + js_file = "icons.m.js" + html_file = "icons.html" + html_type = "iron-iconset" +} + +group("polymer3_elements") { + deps = [ + ":hidden_style_css_module", + ":icons_module", + ":md_select_css_module", + ":shared_style_css_module", + ":shared_vars_css_module", + "cr_button:cr_button_module", + "cr_checkbox:cr_checkbox_module", + "cr_toast:cr_toast_module", + "cr_toggle:cr_toggle_module", + "cr_view_manager:cr_view_manager_module", + ] +}
diff --git a/ui/webui/resources/cr_elements/cr_button/BUILD.gn b/ui/webui/resources/cr_elements/cr_button/BUILD.gn index b625d826..4a25178 100644 --- a/ui/webui/resources/cr_elements/cr_button/BUILD.gn +++ b/ui/webui/resources/cr_elements/cr_button/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") js_type_check("closure_compile") { deps = [ @@ -16,3 +17,9 @@ "//ui/webui/resources/js/cr/ui:focus_outline_manager", ] } + +polymer_modulizer("cr_button") { + js_file = "cr_button.js" + html_file = "cr_button.html" + html_type = "dom-module" +}
diff --git a/ui/webui/resources/cr_elements/cr_checkbox/BUILD.gn b/ui/webui/resources/cr_elements/cr_checkbox/BUILD.gn index a1c36e2..710bc24 100644 --- a/ui/webui/resources/cr_elements/cr_checkbox/BUILD.gn +++ b/ui/webui/resources/cr_elements/cr_checkbox/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") js_type_check("closure_compile") { deps = [ @@ -15,3 +16,9 @@ "//third_party/polymer/v1_0/components-chromium/paper-behaviors:paper-ripple-behavior-extracted", ] } + +polymer_modulizer("cr_checkbox") { + js_file = "cr_checkbox.js" + html_file = "cr_checkbox.html" + html_type = "dom-module" +}
diff --git a/ui/webui/resources/cr_elements/cr_toast/BUILD.gn b/ui/webui/resources/cr_elements/cr_toast/BUILD.gn index 66df6b1..926d3df6 100644 --- a/ui/webui/resources/cr_elements/cr_toast/BUILD.gn +++ b/ui/webui/resources/cr_elements/cr_toast/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") js_type_check("closure_compile") { deps = [ @@ -22,3 +23,9 @@ "//ui/webui/resources/js:cr", ] } + +polymer_modulizer("cr_toast") { + js_file = "cr_toast.js" + html_file = "cr_toast.html" + html_type = "dom-module" +}
diff --git a/ui/webui/resources/cr_elements/cr_toggle/BUILD.gn b/ui/webui/resources/cr_elements/cr_toggle/BUILD.gn index fb433a4d..83d0724 100644 --- a/ui/webui/resources/cr_elements/cr_toggle/BUILD.gn +++ b/ui/webui/resources/cr_elements/cr_toggle/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") js_type_check("closure_compile") { deps = [ @@ -16,3 +17,9 @@ "//third_party/polymer/v1_0/components-chromium/paper-behaviors:paper-ripple-behavior-extracted", ] } + +polymer_modulizer("cr_toggle") { + js_file = "cr_toggle.js" + html_file = "cr_toggle.html" + html_type = "dom-module" +}
diff --git a/ui/webui/resources/cr_elements/cr_view_manager/BUILD.gn b/ui/webui/resources/cr_elements/cr_view_manager/BUILD.gn index 016a1189..40151b2 100644 --- a/ui/webui/resources/cr_elements/cr_view_manager/BUILD.gn +++ b/ui/webui/resources/cr_elements/cr_view_manager/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//third_party/closure_compiler/compile_js.gni") +import("//tools/polymer/polymer.gni") js_type_check("closure_compile") { deps = [ @@ -16,3 +17,10 @@ ] externs_list = [ "$externs_path/web_animations.js" ] } + +polymer_modulizer("cr_view_manager") { + js_file = "cr_view_manager.js" + html_file = "cr_view_manager.html" + html_type = "dom-module" + auto_imports = [ "ui/webui/resources/html/assert.html|assert" ] +}
diff --git a/ui/webui/resources/cr_elements_resources_v3.grdp b/ui/webui/resources/cr_elements_resources_v3.grdp new file mode 100644 index 0000000..d0fb592 --- /dev/null +++ b/ui/webui/resources/cr_elements_resources_v3.grdp
@@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="utf-8"?> +<grit-part> + <!-- Polymer 3.0 Elements --> + <include name="IDR_CR_ELEMENTS_CR_BUTTON_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/cr_button/cr_button.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_CHECKBOX_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/cr_checkbox/cr_checkbox.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_SHARED_STYLE_CSS_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/shared_style_css.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_SHARED_VARS_CSS_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/shared_vars_css.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_TOAST_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/cr_toast/cr_toast.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_TOGGLE_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/cr_toggle/cr_toggle.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_CR_VIEW_MANAGER_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/cr_view_manager/cr_view_manager.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_MD_SELECT_CSS_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/md_select_css.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_HIDDEN_STYLE_CSS_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/hidden_style_css.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> + <include name="IDR_CR_ELEMENTS_ICONS_M_JS" + file="${root_gen_dir}/ui/webui/resources/cr_elements/icons.m.js" + use_base_dir="false" + type="BINDATA" + compress="gzip" /> +</grit-part>
diff --git a/ui/webui/resources/webui_resources.grd b/ui/webui/resources/webui_resources.grd index ef6f3f0..2671502 100644 --- a/ui/webui/resources/webui_resources.grd +++ b/ui/webui/resources/webui_resources.grd
@@ -109,6 +109,7 @@ </if> <if expr="not is_android and not is_ios"> + <part file="cr_elements_resources_v3.grdp" /> <part file="cr_polymer_resources_v3.grdp" /> </if> </includes>